tvalentyn commented on code in PR #22131: URL: https://github.com/apache/beam/pull/22131#discussion_r951559085
########## sdks/python/apache_beam/ml/inference/tensorrt_inference.py: ########## @@ -0,0 +1,280 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# pytype: skip-file + +from __future__ import annotations + +import logging +import sys +from typing import Any +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence +from typing import Tuple + +import numpy as np + +from apache_beam.io.filesystems import FileSystems +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +LOGGER = logging.getLogger("TensorRTEngineHandlerNumPy") +# This try/catch block allows users to submit jobs from a machine without +# GPU and other dependencies (tensorrt, cuda, etc.) at job submission time. +try: + import tensorrt as trt + TRT_LOGGER = trt.Logger(trt.Logger.INFO) + trt.init_libnvinfer_plugins(TRT_LOGGER, namespace="") + LOGGER.info('tensorrt module successfully imported.') +except ModuleNotFoundError: + TRT_LOGGER = None + msg = 'tensorrt module was not found. This is ok as long as the specified ' \ + 'runner has tensorrt dependencies installed.' + LOGGER.warning(msg) + + +def _load_engine(engine_path): + import tensorrt as trt + file = FileSystems.open(engine_path, 'rb') + runtime = trt.Runtime(TRT_LOGGER) + engine = runtime.deserialize_cuda_engine(file.read()) + assert engine + return engine + + +def _load_onnx(onnx_path): + import tensorrt as trt + builder = trt.Builder(TRT_LOGGER) + network = builder.create_network( + flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) + parser = trt.OnnxParser(network, TRT_LOGGER) + with FileSystems.open(onnx_path) as f: + if not parser.parse(f.read()): + LOGGER.error("Failed to load ONNX file: %s", onnx_path) + for error in range(parser.num_errors): + LOGGER.error(parser.get_error(error)) + sys.exit(1) + return network, builder + + +def _build_engine(network, builder): + import tensorrt as trt + config = builder.create_builder_config() + runtime = trt.Runtime(TRT_LOGGER) + plan = builder.build_serialized_network(network, config) + engine = runtime.deserialize_cuda_engine(plan) + builder.reset() + return engine + + +def _assign_or_fail(args): + """CUDA error checking.""" + from cuda import cuda + err, ret = args[0], args[1:] + if isinstance(err, cuda.CUresult): + if err != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError("Cuda Error: {}".format(err)) + else: + raise RuntimeError("Unknown error type: {}".format(err)) + # Special case so that no unpacking is needed at call-site. + if len(ret) == 1: + return ret[0] + return ret + + +class TensorRTEngine: + def __init__(self, engine: trt.ICudaEngine): + """Implementation of the TensorRTEngine class which handles + allocations associated with TensorRT engine. + + Example Usage:: + + TensorRTEngine(engine) + + Args: + engine: trt.ICudaEngine object that contains TensorRT engine + """ + from cuda import cuda + import tensorrt as trt + self.engine = engine + self.context = engine.create_execution_context() + self.inputs = [] + self.outputs = [] + self.gpu_allocations = [] + self.cpu_allocations = [] + """Setup I/O bindings.""" + for i in range(self.engine.num_bindings): + name = self.engine.get_binding_name(i) + dtype = self.engine.get_binding_dtype(i) + shape = self.engine.get_binding_shape(i) + size = trt.volume(shape) * dtype.itemsize + allocation = _assign_or_fail(cuda.cuMemAlloc(size)) + binding = { + 'index': i, + 'name': name, + 'dtype': np.dtype(trt.nptype(dtype)), + 'shape': list(shape), + 'allocation': allocation, + 'size': size + } + self.gpu_allocations.append(allocation) + if self.engine.binding_is_input(i): + self.inputs.append(binding) + else: + self.outputs.append(binding) + + assert self.context + assert len(self.inputs) > 0 + assert len(self.outputs) > 0 + assert len(self.gpu_allocations) > 0 + + for output in self.outputs: + self.cpu_allocations.append(np.zeros(output['shape'], output['dtype'])) + # Create CUDA Stream. + self.stream = _assign_or_fail(cuda.cuStreamCreate(0)) + + def get_engine_attrs(self): + """Returns TensorRT engine attributes.""" + return ( + self.engine, + self.context, + self.inputs, + self.outputs, + self.gpu_allocations, + self.cpu_allocations, + self.stream) + + +class TensorRTEngineHandlerNumPy(ModelHandler[np.ndarray, Review Comment: No, as of now docstring has to be updated manually. https://github.com/apache/beam/issues/22265 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
