Automatically created from 모델 배포(554:triton-python-model-gu) by 그룹사용자(groupuser)
This commit is contained in:
parent
8ee76b7a19
commit
31816ca167
103
1/model.py
Normal file
103
1/model.py
Normal file
@ -0,0 +1,103 @@
|
||||
import triton_python_backend_utils as pb_utils
|
||||
import numpy as np
|
||||
import json # model_config를 파싱하기 위해 사용
|
||||
|
||||
class TritonPythonModel:
|
||||
"""
|
||||
Triton Python 백엔드 모델 클래스.
|
||||
이 클래스 이름은 반드시 'TritonPythonModel'이어야 합니다.
|
||||
"""
|
||||
|
||||
def initialize(self, args):
|
||||
"""
|
||||
모델이 로드될 때 한 번 호출되는 초기화 메서드.
|
||||
여기서 실제 ML 모델 (PyTorch, TensorFlow 등)을 로드하거나,
|
||||
전처리/후처리 설정을 초기화합니다.
|
||||
|
||||
매개변수 (Parameters)
|
||||
----------
|
||||
args: 딕셔너리(dictionary)
|
||||
키(key)와 값(value)은 모두 문자열입니다.
|
||||
딕셔너리 키와 값은 다음과 같습니다:
|
||||
* model_config: 모델 설정을 담고 있는 JSON 문자열
|
||||
* model_instance_kind: 모델 인스턴스의 종류를 담고 있는 문자열
|
||||
* model_instance_device_id: 모델 인스턴스 장치 ID를 담고 있는 문자열
|
||||
* model_repository: 모델 저장소 경로
|
||||
* model_version: 모델 버전
|
||||
* model_name: 모델 이름
|
||||
"""
|
||||
self.logger = pb_utils.Logger
|
||||
self.model_config = json.loads(args['model_config'])
|
||||
self.logger.log_info(f"Model config: {self.model_config}")
|
||||
|
||||
self.model_path = self._get_config_parameter("model_path")
|
||||
self.logger.log_info(f"Model mount path: {self.model_path}")
|
||||
|
||||
|
||||
# 출력 텐서 'OUTPUT0'의 데이터 타입을 모델 설정에서 가져옵니다.
|
||||
# 이를 통해 NumPy 배열을 Triton이 요구하는 정확한 타입으로 변환할 수 있습니다.
|
||||
output_config = [
|
||||
op for op in self.model_config['output'] if op['name'] == 'OUTPUT0'
|
||||
][0]
|
||||
self.output_dtype = pb_utils.triton_string_to_numpy(output_config['data_type'])
|
||||
|
||||
self.logger.log_info(f"Initialized Python backend for model '{args['model_name']}'")
|
||||
|
||||
def execute(self, requests):
|
||||
"""
|
||||
추론 요청이 들어올 때마다 호출되는 실행 메서드.
|
||||
주어진 요청들을 처리하고, 각 요청에 대한 응답을 반환합니다.
|
||||
"""
|
||||
responses = []
|
||||
|
||||
# 각 요청(request)에 대해 처리합니다.
|
||||
for request in requests:
|
||||
# 1. 입력 텐서 가져오기
|
||||
# 'INPUT0'과 'INPUT1'은 config.pbtxt에 정의된 입력 이름입니다.
|
||||
in0 = pb_utils.get_input_tensor_by_name(request, 'INPUT0').as_numpy()
|
||||
in1 = pb_utils.get_input_tensor_by_name(request, 'INPUT1').as_numpy()
|
||||
|
||||
self.logger.log_info(f"Processing request: INPUT0 shape {in0.shape}, INPUT1 shape {in1.shape}")
|
||||
|
||||
# 2. 핵심 로직 수행 (여기서는 간단한 덧셈)
|
||||
# 이 부분이 실제 ML 모델의 추론이 이루어지는 곳입니다.
|
||||
# 예: out0_np = self.your_ml_model.predict(in0, in1)
|
||||
out0_np = in0 + in1
|
||||
|
||||
# 3. 출력 텐서 생성
|
||||
# 'OUTPUT0'은 config.pbtxt에 정의된 출력 이름입니다.
|
||||
# NumPy 배열을 Triton Tensor 객체로 변환하고, 모델 설정에서 가져온 데이터 타입을 사용합니다.
|
||||
out0_tensor = pb_utils.Tensor('OUTPUT0', out0_np.astype(self.output_dtype))
|
||||
|
||||
# 4. 추론 응답 생성
|
||||
# 처리된 출력 텐서들을 포함하는 InferenceResponse 객체를 만듭니다.
|
||||
response = pb_utils.InferenceResponse(output_tensors=[out0_tensor])
|
||||
responses.append(response)
|
||||
|
||||
# 모든 요청에 대한 응답 리스트를 반환합니다.
|
||||
return responses
|
||||
|
||||
def _get_config_parameter(self, parameter_name):
|
||||
"""
|
||||
모델 설정(config.pbtxt)에서 특정 파라미터의 문자열 값을 가져옵니다.
|
||||
|
||||
Args:
|
||||
parameter_name (str): 가져올 파라미터의 이름.
|
||||
|
||||
Returns:
|
||||
str or None: 파라미터의 'string_value' 또는 해당 파라미터가 없거나 'string_value' 키가 없는 경우 None.
|
||||
"""
|
||||
self.parameters = self.model_config.get('parameters', {})
|
||||
parameter_dict = self.parameters.get(parameter_name)
|
||||
|
||||
if isinstance(parameter_dict, dict) and 'string_value' in parameter_dict:
|
||||
return parameter_dict['string_value']
|
||||
|
||||
return None
|
||||
|
||||
def finalize(self):
|
||||
"""
|
||||
모델이 언로드될 때 한 번 호출되는 정리(cleanup) 메서드.
|
||||
모델 로드 시 할당했던 리소스(파일 핸들, GPU 메모리 등)를 해제합니다.
|
||||
"""
|
||||
self.logger.log_info("Cleaning up Python backend...")
|
||||
Loading…
Reference in New Issue
Block a user