Update 1/model.py
This commit is contained in:
parent
e5223e815f
commit
14971e4c7a
122
1/model.py
122
1/model.py
@ -1,103 +1,93 @@
|
|||||||
|
# model.py
|
||||||
import triton_python_backend_utils as pb_utils
|
import triton_python_backend_utils as pb_utils
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import json # model_config를 파싱하기 위해 사용
|
import json
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
|
||||||
class TritonPythonModel:
|
class TritonPythonModel:
|
||||||
"""
|
|
||||||
Triton Python 백엔드 모델 클래스.
|
|
||||||
이 클래스 이름은 반드시 'TritonPythonModel'이어야 합니다.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def initialize(self, args):
|
def initialize(self, args):
|
||||||
"""
|
"""
|
||||||
모델이 로드될 때 한 번 호출되는 초기화 메서드.
|
모델이 로드될 때 딱 한 번만 호출됩니다.
|
||||||
여기서 실제 ML 모델 (PyTorch, TensorFlow 등)을 로드하거나,
|
`initialize` 함수를 구현하는 것은 선택 사항입니다. 이 함수를 통해 모델은
|
||||||
전처리/후처리 설정을 초기화합니다.
|
이 모델과 관련된 모든 상태를 초기화할 수 있습니다.
|
||||||
|
|
||||||
매개변수 (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.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.model_name = args["model_name"]
|
||||||
self.logger.log_info(f"Model mount path: {self.model_path}")
|
self.model_config = json.loads(args["model_config"])
|
||||||
|
|
||||||
|
self.logger.log_info(f"'{self.model_name}' 모델 초기화 완료")
|
||||||
|
|
||||||
# 출력 텐서 '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):
|
def execute(self, requests):
|
||||||
"""
|
"""
|
||||||
추론 요청이 들어올 때마다 호출되는 실행 메서드.
|
Triton이 각 추론 요청에 대해 호출하는 실행 함수입니다.
|
||||||
주어진 요청들을 처리하고, 각 요청에 대한 응답을 반환합니다.
|
|
||||||
"""
|
"""
|
||||||
responses = []
|
responses = []
|
||||||
|
|
||||||
# 각 요청(request)에 대해 처리합니다.
|
# 각 추론 요청을 순회하며 처리합니다.
|
||||||
for request in requests:
|
for request in requests:
|
||||||
# 1. 입력 텐서 가져오기
|
# Triton 입력 파싱
|
||||||
# 'INPUT0'과 'INPUT1'은 config.pbtxt에 정의된 입력 이름입니다.
|
input_text = self._get_input_value(request, "INPUT")
|
||||||
in0 = pb_utils.get_input_tensor_by_name(request, 'INPUT0').as_numpy()
|
self.logger.log_info(f"INPUT 출력:\n{input_text}")
|
||||||
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}")
|
random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16))
|
||||||
|
|
||||||
# 2. 핵심 로직 수행 (여기서는 간단한 덧셈)
|
output = random_string
|
||||||
# 이 부분이 실제 ML 모델의 추론이 이루어지는 곳입니다.
|
self.logger.log_info(f"OUTPUT 출력:\n{output}")
|
||||||
# 예: out0_np = self.your_ml_model.predict(in0, in1)
|
|
||||||
out0_np = in0 + in1
|
|
||||||
|
|
||||||
# 3. 출력 텐서 생성
|
# 생성된 텍스트를 Triton 출력 텐서로 변환합니다.
|
||||||
# 'OUTPUT0'은 config.pbtxt에 정의된 출력 이름입니다.
|
output_tensor = pb_utils.Tensor("OUTPUT", np.array(output.encode('utf-8'), dtype=np.bytes_))
|
||||||
# NumPy 배열을 Triton Tensor 객체로 변환하고, 모델 설정에서 가져온 데이터 타입을 사용합니다.
|
|
||||||
out0_tensor = pb_utils.Tensor('OUTPUT0', out0_np.astype(self.output_dtype))
|
|
||||||
|
|
||||||
# 4. 추론 응답 생성
|
# 응답 객체를 생성하고 출력 텐서를 추가합니다.
|
||||||
# 처리된 출력 텐서들을 포함하는 InferenceResponse 객체를 만듭니다.
|
responses.append(pb_utils.InferenceResponse(output_tensors=[output_tensor]))
|
||||||
response = pb_utils.InferenceResponse(output_tensors=[out0_tensor])
|
|
||||||
responses.append(response)
|
|
||||||
|
|
||||||
# 모든 요청에 대한 응답 리스트를 반환합니다.
|
|
||||||
return responses
|
return responses
|
||||||
|
|
||||||
def _get_config_parameter(self, parameter_name):
|
def _get_input_value(self, request, input_name: str, default=None):
|
||||||
"""
|
"""
|
||||||
모델 설정(config.pbtxt)에서 특정 파라미터의 문자열 값을 가져옵니다.
|
Triton 추론 요청에서 특정 이름의 입력 텐서 값을 가져옵니다.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
parameter_name (str): 가져올 파라미터의 이름.
|
request (pb_utils.InferenceRequest): Triton 추론 요청 객체.
|
||||||
|
input_name (str): 가져올 입력 텐서의 이름.
|
||||||
|
default (any, optional): 입력 텐서가 없을 경우 반환할 기본값. Defaults to None.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str or None: 파라미터의 'string_value' 또는 해당 파라미터가 없거나 'string_value' 키가 없는 경우 None.
|
any: 디코딩된 입력 텐서의 값. 텐서가 없으면 기본값을 반환합니다.
|
||||||
"""
|
"""
|
||||||
self.parameters = self.model_config.get('parameters', {})
|
tensor_value = pb_utils.get_input_tensor_by_name(request, input_name)
|
||||||
parameter_dict = self.parameters.get(parameter_name)
|
|
||||||
|
|
||||||
if isinstance(parameter_dict, dict) and 'string_value' in parameter_dict:
|
if tensor_value is None:
|
||||||
return parameter_dict['string_value']
|
return default
|
||||||
|
|
||||||
return None
|
return self._np_decoder(tensor_value.as_numpy()[0])
|
||||||
|
|
||||||
|
def _np_decoder(self, obj):
|
||||||
|
"""
|
||||||
|
NumPy 객체의 데이터 타입을 확인하고 Python 기본 타입으로 변환합니다.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
obj (numpy.ndarray element): 변환할 NumPy 배열의 요소.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
any: 해당 NumPy 요소에 대응하는 Python 기본 타입 (str, int, float, bool).
|
||||||
|
bytes 타입인 경우 UTF-8로 디코딩합니다.
|
||||||
|
"""
|
||||||
|
if isinstance(obj, bytes):
|
||||||
|
return obj.decode('utf-8')
|
||||||
|
if np.issubdtype(obj, np.integer):
|
||||||
|
return int(obj)
|
||||||
|
if np.issubdtype(obj, np.floating):
|
||||||
|
return round(float(obj), 3)
|
||||||
|
if isinstance(obj, np.bool_):
|
||||||
|
return bool(obj)
|
||||||
|
|
||||||
def finalize(self):
|
def finalize(self):
|
||||||
"""
|
"""
|
||||||
모델이 언로드될 때 한 번 호출되는 정리(cleanup) 메서드.
|
모델 실행이 완료된 후 Triton 서버가 종료될 때 한 번 호출되는 함수입니다.
|
||||||
모델 로드 시 할당했던 리소스(파일 핸들, GPU 메모리 등)를 해제합니다.
|
`finalize` 함수를 구현하는 것은 선택 사항입니다. 이 함수를 통해 모델은
|
||||||
|
종료 전에 필요한 모든 정리 작업을 수행할 수 있습니다.
|
||||||
"""
|
"""
|
||||||
self.logger.log_info("Cleaning up Python backend...")
|
pass
|
||||||
Loading…
Reference in New Issue
Block a user