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 등)을 로드하거나, 전처리/후처리 설정을 초기화합니다. """ self.logger = pb_utils.Logger self.model_config = json.loads(args['model_config']) self.logger.log_info(f"Model config: {self.model_config}") # 출력 텐서 '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 finalize(self): """ 모델이 언로드될 때 한 번 호출되는 정리(cleanup) 메서드. 모델 로드 시 할당했던 리소스(파일 핸들, GPU 메모리 등)를 해제합니다. """ self.logger.log_info("Cleaning up Python backend...")