python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
import torch from ldm.modules.midas.api import load_midas_transform class AddMiDaS(object): def __init__(self, model_type): super().__init__() self.transform = load_midas_transform(model_type) def pt2np(self, x): x = ((x + 1.0) * .5).detach().cpu().numpy() return x def np2pt(self, x): x = torch.from_numpy(x) * 2 - 1. return x def __call__(self, sample): # sample['jpg'] is tensor hwc in [-1, 1] at this point x = self.pt2np(sample['jpg']) x = self.transform({"image": x})["image"] sample['midas_in'] = x return sample
trt-samples-for-hackathon-cn-master
Hackathon2023/controlnet/ldm/data/util.py
trt-samples-for-hackathon-cn-master
Hackathon2023/controlnet/ldm/data/__init__.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import torch import torchvision from torchsummary import summary import time torch.manual_seed(0) resnet50 = torchvision.models.resnet50().cuda() resnet50.eval() #summary(resnet50, (3, 1080, 1920), device='cuda') input_data = torch.randn(1, 3, 1080, 1920, dtype=torch.float32, device='cuda') output_data_pytorch = resnet50(input_data).cpu().detach().numpy() nRound = 10 with torch.no_grad(): torch.cuda.synchronize() t0 = time.time() for i in range(nRound): resnet50(input_data) torch.cuda.synchronize() time_pytorch = (time.time() - t0) / nRound print('PyTorch time:', time_pytorch) input_names = ['input'] output_names = ['output'] torch.onnx.export(resnet50, input_data, 'resnet50.onnx', input_names=input_names, output_names=output_names, verbose=False, opset_version=11) torch.onnx.export(resnet50, input_data, 'resnet50.dynamic_shape.onnx', dynamic_axes={"input": [0, 2, 3]}, input_names=input_names, output_names=output_names, verbose=False, opset_version=11) #继续运行python代码前,先运行如下命令 #trtexec --verbose --onnx=resnet50.onnx --saveEngine=resnet50.trt #trtexec --verbose --onnx=resnet50.onnx --saveEngine=resnet50_fp16.trt --fp16 #以下命令不必运行,仅供参考 #trtexec --verbose --onnx=resnet50.dynamic_shape.onnx --saveEngine=resnet50.dynamic_shape.trt --optShapes=input:1x3x1080x1920 --minShapes=input:1x3x1080x1920 --maxShapes=input:1x3x1080x1920 from trt_lite2 import TrtLite import numpy as np import os for engine_file_path in ['resnet50.trt', 'resnet50_fp16.trt']: if not os.path.exists(engine_file_path): print('Engine file', engine_file_path, 'doesn\'t exist. Please run trtexec and re-run this script.') exit(1) print('====', engine_file_path, '===') trt = TrtLite(engine_file_path=engine_file_path) trt.print_info() i2shape = {0: (1, 3, 1080, 1920)} io_info = trt.get_io_info(i2shape) d_buffers = trt.allocate_io_buffers(i2shape, True) output_data_trt = np.zeros(io_info[1][2], dtype=np.float32) d_buffers[0].copy_(input_data.reshape(d_buffers[0].size())) trt.execute([t.data_ptr() for t in d_buffers], i2shape) output_data_trt = d_buffers[1].cpu().numpy() torch.cuda.synchronize() t0 = time.time() for i in range(nRound): trt.execute([t.data_ptr() for t in d_buffers], i2shape) torch.cuda.synchronize() time_trt = (time.time() - t0) / nRound print('TensorRT time:', time_trt) print('Speedup:', time_pytorch / time_trt) print('Average diff percentage:', np.mean(np.abs(output_data_pytorch - output_data_trt) / np.abs(output_data_pytorch)))
trt-samples-for-hackathon-cn-master
old/python/app_onnx_resnet50.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from datetime import datetime import numpy as np import os, sys i_gpu = 0 os.environ["CUDA_VISIBLE_DEVICES"] = str(i_gpu) import pycuda.driver as cuda import pycuda.autoinit import tensorrt as trt import tensorflow.compat.v1 as tf import tf2onnx import ctypes import onnx_graphsurgeon as gs import onnx ctypes.cdll.LoadLibrary('../build/OnehotPlugin.so') #TRT_LOGGER = trt.Logger(trt.Logger.WARNING) TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) def modify_onehot(graph): for node in graph.nodes: if node.op == "OneHot": depth = node.inputs[1].values attrs = {"depth": int(depth)} onehot = gs.Node(op="OnehotPlugin", name=node.name, attrs=attrs) graph.nodes.append(onehot) inp_output_tensor = node.inputs[0] inp_output_tensor.outputs = [onehot] onehot.outputs = node.outputs node.outputs.clear() print(onehot) # Remove the non-used node from the graph completely graph.cleanup() return graph # Simple helper data class that's a little nicer to use than a 2-tuple. class HostDeviceMem(object): def __init__(self, host_mem, device_mem): self.host = host_mem self.device = device_mem def __str__(self): return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device) def __repr__(self): return self.__str__() # Allocates all buffers required for an engine, i.e. host/device inputs/outputs. def allocate_buffers(engine): inputs = [] outputs = [] bindings = [] stream = cuda.Stream() for binding in engine: # size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size size = trt.volume(engine.get_binding_shape(binding)) dtype = trt.nptype(engine.get_binding_dtype(binding)) # Allocate host and device buffers host_mem = cuda.pagelocked_empty(size, dtype) device_mem = cuda.mem_alloc(host_mem.nbytes) # Append the device buffer to device bindings. bindings.append(int(device_mem)) # Append to the appropriate list. if engine.binding_is_input(binding): inputs.append(HostDeviceMem(host_mem, device_mem)) else: outputs.append(HostDeviceMem(host_mem, device_mem)) return inputs, outputs, bindings, stream # This function is generalized for multiple inputs/outputs. # inputs and outputs are expected to be lists of HostDeviceMem objects. def do_inference(context, bindings, inputs, outputs, stream, batch_size=1): # Transfer input data to the GPU. [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs] # Run inference. context.execute_async(batch_size=batch_size, bindings=bindings, stream_handle=stream.handle) # Transfer predictions back from the GPU. [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs] # Synchronize the stream stream.synchronize() # Return only the host outputs. return [out.host for out in outputs] def main(): tf.set_random_seed(1234) np.random.seed(0) iterations = 100 config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: batch_size = 16 input_data = np.random.rand(batch_size, 256).astype(np.float32) input_ph = tf.placeholder(dtype=tf.float32, shape=[batch_size, 256], name="input") x = tf.layers.dense(input_ph, 256) # test one_hot depth = 256 indices = tf.cast( tf.clip_by_value(tf.reshape(x, [-1]), 0, depth - 1), tf.int32) x = tf.one_hot(indices, depth) x = tf.reshape(x, [batch_size, -1]) x = tf.layers.dense(x, 256) output = tf.identity(x, name="output") sess.run(tf.global_variables_initializer()) time_sum = 0 a = datetime.now() for i in range(iterations): tf_result = sess.run([output], {input_ph: input_data}) b = datetime.now() time_sum = (b - a).total_seconds() tf_time = "[INFO] TF execution time " + str( time_sum * 1000 / iterations) + " ms" print(tf_time) output_name_without_port = ["output"] frozen_graph = tf.graph_util.convert_variables_to_constants( sess, sess.graph_def, output_name_without_port) # save frozen model with open("test_op.pb", "wb") as ofile: ofile.write(frozen_graph.SerializeToString()) model_file = "test_op.onnx" os.system("python3 -m tf2onnx.convert --input test_op.pb --inputs input:0 --outputs output:0 --output test_op.onnx --verbose --opset 11") ### use ONNX GraphSurgeon # ONNX operator is required to keep aligned (like name, inputs, outputs and attributes) with TensorRT plugin to use Fallback mechanism. # ONNX GraphSurgeon is useful for modification and you can install it by the following commands. # pip install nvidia-pyindex # pip install onnx-graphsurgeon graph = gs.import_onnx(onnx.load(model_file)) graph = modify_onehot(graph) model_file = "test_op_onehot.onnx" onnx.save(gs.export_onnx(graph), model_file) # build trt model by onnx model cuda.Device(0).make_context() with trt.Builder(TRT_LOGGER) as builder, builder.create_network( 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) ) as network, trt.OnnxParser(network, TRT_LOGGER) as parser: builder.max_batch_size = batch_size with open(model_file, 'rb') as model: # parse onnx model parser.parse(model.read()) for i in range(parser.num_errors): print(parser.get_error(i)) engine = builder.build_engine(network, builder.create_builder_config()) if engine == None: print("[ERROR] engine is None") exit(-1) inputs, outputs, bindings, stream = allocate_buffers(engine) with engine.create_execution_context() as context: input_data = input_data.ravel() np.copyto(inputs[0].host, input_data) time_sum = 0 a = datetime.now() for i in range(iterations): np.copyto(inputs[0].host, input_data) output = do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream, batch_size=batch_size) b = datetime.now() time_sum = (b - a).total_seconds() trt_time = ("TRT execution time " + str(time_sum * 1000 / iterations) + " ms") trt_result = output for i in range(len(trt_result)): print( "trt cross_check output_%d " % i + str(np.allclose(tf_result[i].flatten(), trt_result[i], atol=1e-5))) print("max diff " + str(np.fabs(tf_result[i].flatten() - trt_result[i]).max())) print("min diff " + str(np.fabs(tf_result[i].flatten() - trt_result[i]).min())) print(tf_time) print(trt_time) cuda.Context.pop() if __name__ == '__main__': main()
trt-samples-for-hackathon-cn-master
old/python/app_Onehot_plugin_TF.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from functools import reduce import numpy as np import tensorrt import ctypes import torch from trt_lite2 import TrtLite np.set_printoptions(threshold=np.inf) ctypes.cdll.LoadLibrary('../build/AddPlugin.so') def get_plugin_creator(plugin_name): plugin_creator_list = tensorrt.get_plugin_registry().plugin_creator_list plugin_creator = None for c in plugin_creator_list: if c.name == plugin_name: plugin_creator = c return plugin_creator def build_engine(builder, input_shape): plugin_creator = get_plugin_creator('AddPlugin') if plugin_creator == None: print('Plugin not found. Exiting') exit() config = builder.create_builder_config() config.max_workspace_size = 1 << 20 builder.max_batch_size = 8 network = builder.create_network() tensor = network.add_input('data', tensorrt.DataType.FLOAT, input_shape) layer = network.add_plugin_v2( [tensor], plugin_creator.create_plugin('AddPlugin', tensorrt.PluginFieldCollection([ tensorrt.PluginField('valueToAdd', np.array([100.0], dtype=np.float32), tensorrt.PluginFieldType.FLOAT32) ])) ) tensor = layer.get_output(0) network.mark_output(tensor) return builder.build_engine(network, config) def run_engine(): batch_size = 2 input_shape = (batch_size, 1, 2, 8) n = reduce(lambda x, y: x * y, input_shape) input_data = np.asarray(range(n), dtype=np.float32).reshape(input_shape) output_data = np.zeros(input_shape, dtype=np.float32) trt = TrtLite(build_engine, (input_shape[1:],)) trt.print_info() d_buffers = trt.allocate_io_buffers(batch_size, True) d_buffers[0].copy_(torch.from_numpy(input_data)) trt.execute([t.data_ptr() for t in d_buffers], batch_size) output_data = d_buffers[1].cpu().numpy() print(output_data) if __name__ == '__main__': run_engine()
trt-samples-for-hackathon-cn-master
old/python/app_plugin.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import tensorrt as trt import pycuda.autoinit import pycuda.driver as cuda import ctypes def get_plugin_creator(plugin_name): trt.init_libnvinfer_plugins(logger, '') plugin_creator_list = trt.get_plugin_registry().plugin_creator_list plugin_creator = None for c in plugin_creator_list: if c.name == plugin_name: plugin_creator = c return plugin_creator def build_engine(shape_data, shape_indices): plugin_creator = get_plugin_creator('GatherND') if plugin_creator == None: print('GatherND plugin not found. Exiting') exit() builder = trt.Builder(logger) network = builder.create_network(flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) tensor_data = network.add_input('data', trt.DataType.FLOAT, shape_data) tensor_indices = network.add_input('indices', trt.DataType.INT32, shape_indices) layer = network.add_plugin_v2( [tensor_data, tensor_indices], plugin_creator .create_plugin('GatherND', trt.PluginFieldCollection([])) ) network.mark_output(layer.get_output(0)) return builder.build_engine(network, builder.create_builder_config()) def run_trt(data, indices, output_0): engine = build_engine(data.shape, indices.shape) print("succeed to build the engine") context = engine.create_execution_context() d_indices = cuda.mem_alloc(indices.nbytes) d_data = cuda.mem_alloc(data.nbytes) d_output_0 = cuda.mem_alloc(output_0.nbytes) cuda.memcpy_htod(d_indices, indices) cuda.memcpy_htod(d_data, data) bindings = [int(d_data), int(d_indices), int(d_output_0)] context.execute_v2(bindings) cuda.memcpy_dtoh(output_0, d_output_0) return output_0 if __name__ == "__main__": logger = trt.Logger(trt.Logger.INFO) ctypes.cdll.LoadLibrary('../build/GatherND.so') data = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32) indices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int32) # Expecting output as np.array([[[2,3]],[[4,5]]], dtype=np.float32) output_0 = np.zeros([2, 1, 2], dtype=np.float32) output_0 = run_trt(data, indices, output_0) print(f"data shape: {data.shape} indices shape: {indices.shape} output shape: {output_0.shape} ") print(f"data {data} \n indices: \n {indices} \n result: \n {output_0}")
trt-samples-for-hackathon-cn-master
old/python/app_GatherND_plugin.py
# # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from functools import reduce import tensorrt import torch import numpy as np class TrtLite: def __init__(self, build_engine_proc = None, build_engine_params = None, engine_file_path = None): logger = tensorrt.Logger(tensorrt.Logger.INFO) if engine_file_path is None: with tensorrt.Builder(logger) as builder: if build_engine_params is not None: self.engine = build_engine_proc(builder, *build_engine_params) else: self.engine = build_engine_proc(builder) else: with open(engine_file_path, 'rb') as f, tensorrt.Runtime(logger) as runtime: self.engine = runtime.deserialize_cuda_engine(f.read()) self.context = self.engine.create_execution_context() def __del__(self): self.engine = None self.context = None def save_to_file(self, engine_file_path): with open(engine_file_path, 'wb') as f: f.write(self.engine.serialize()) def get_io_info(self, input_desc): def to_numpy_dtype(trt_dtype): tb = { tensorrt.DataType.BOOL: np.dtype('bool'), tensorrt.DataType.FLOAT: np.dtype('float32'), tensorrt.DataType.HALF: np.dtype('float16'), tensorrt.DataType.INT32: np.dtype('int32'), tensorrt.DataType.INT8: np.dtype('int8'), } return tb[trt_dtype] if isinstance(input_desc, dict): if self.engine.has_implicit_batch_dimension: print('Engine was built with static-shaped input so you should provide batch_size instead of i2shape') return i2shape = input_desc for i, shape in i2shape.items(): self.context.set_binding_shape(i, shape) return [(self.engine.get_binding_name(i), self.engine.binding_is_input(i), tuple(self.context.get_binding_shape(i)), to_numpy_dtype(self.engine.get_binding_dtype(i))) for i in range(self.engine.num_bindings)] batch_size = input_desc return [(self.engine.get_binding_name(i), self.engine.binding_is_input(i), (batch_size,) + tuple(self.context.get_binding_shape(i)), to_numpy_dtype(self.engine.get_binding_dtype(i))) for i in range(self.engine.num_bindings)] def allocate_io_buffers(self, input_desc, on_gpu): io_info = self.get_io_info(input_desc) if io_info is None: return if on_gpu: cuda = torch.device('cuda') np2pth = { np.dtype('bool'): torch.bool, np.dtype('float32'): torch.float32, np.dtype('float16'): torch.float16, np.dtype('int32'): torch.int32, np.dtype('int8'): torch.int8, } return [torch.empty(i[2], dtype=np2pth[i[3]], device=cuda).contiguous() for i in io_info] else: return [np.zeros(i[2], i[3]) for i in io_info] def execute(self, bindings, input_desc, stream_handle = 0, input_consumed = None): if isinstance(input_desc, dict): i2shape = input_desc for i, shape in i2shape.items(): self.context.set_binding_shape(i, shape) self.context.execute_async_v2(bindings, stream_handle, input_consumed) return batch_size = input_desc self.context.execute_async(batch_size, bindings, stream_handle, input_consumed) def print_info(self): print("Batch dimension is", "implicit" if self.engine.has_implicit_batch_dimension else "explicit") for i in range(self.engine.num_bindings): print("input" if self.engine.binding_is_input(i) else "output", self.engine.get_binding_name(i), self.engine.get_binding_dtype(i), self.engine.get_binding_shape(i), -1 if -1 in self.engine.get_binding_shape(i) else reduce( lambda x, y: x * y, self.engine.get_binding_shape(i)) * self.engine.get_binding_dtype(i).itemsize)
trt-samples-for-hackathon-cn-master
old/python/trt_lite2.py
# # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from functools import reduce import tensorrt import pycuda.driver as cuda import numpy as np class TrtLite: def __init__(self, build_engine_proc = None, build_engine_params = None, engine_file_path = None): logger = tensorrt.Logger(tensorrt.Logger.INFO) if engine_file_path is None: with tensorrt.Builder(logger) as builder: if build_engine_params is not None: self.engine = build_engine_proc(builder, *build_engine_params) else: self.engine = build_engine_proc(builder) else: with open(engine_file_path, 'rb') as f, tensorrt.Runtime(logger) as runtime: self.engine = runtime.deserialize_cuda_engine(f.read()) self.context = self.engine.create_execution_context() def __del__(self): self.engine = None self.context = None def save_to_file(self, engine_file_path): with open(engine_file_path, 'wb') as f: f.write(self.engine.serialize()) def get_io_info(self, input_desc): def to_numpy_dtype(trt_dtype): tb = { tensorrt.DataType.BOOL: np.dtype('bool'), tensorrt.DataType.FLOAT: np.dtype('float32'), tensorrt.DataType.HALF: np.dtype('float16'), tensorrt.DataType.INT32: np.dtype('int32'), tensorrt.DataType.INT8: np.dtype('int8'), } return tb[trt_dtype] if isinstance(input_desc, dict): if self.engine.has_implicit_batch_dimension: print('Engine was built with static-shaped input so you should provide batch_size instead of i2shape') return i2shape = input_desc for i, shape in i2shape.items(): self.context.set_binding_shape(i, shape) return [(self.engine.get_binding_name(i), self.engine.binding_is_input(i), self.context.get_binding_shape(i), to_numpy_dtype(self.engine.get_binding_dtype(i))) for i in range(self.engine.num_bindings)] batch_size = input_desc return [(self.engine.get_binding_name(i), self.engine.binding_is_input(i), (batch_size,) + tuple(self.context.get_binding_shape(i)), to_numpy_dtype(self.engine.get_binding_dtype(i))) for i in range(self.engine.num_bindings)] def allocate_io_buffers(self, input_desc, on_gpu): io_info = self.get_io_info(input_desc) if io_info is None: return if on_gpu: return [cuda.mem_alloc(reduce(lambda x, y: x * y, i[2]) * i[3].itemsize) for i in io_info] else: return [np.zeros(i[2], i[3]) for i in io_info] def execute(self, bindings, input_desc, stream_handle = 0, input_consumed = None): if isinstance(input_desc, dict): i2shape = input_desc for i, shape in i2shape.items(): self.context.set_binding_shape(i, shape) self.context.execute_async_v2(bindings, stream_handle, input_consumed) return batch_size = input_desc self.context.execute_async(batch_size, bindings, stream_handle, input_consumed) def print_info(self): print("Batch dimension is", "implicit" if self.engine.has_implicit_batch_dimension else "explicit") for i in range(self.engine.num_bindings): print("input" if self.engine.binding_is_input(i) else "output", self.engine.get_binding_name(i), self.engine.get_binding_dtype(i), self.engine.get_binding_shape(i), -1 if -1 in self.engine.get_binding_shape(i) else reduce( lambda x, y: x * y, self.engine.get_binding_shape(i)) * self.engine.get_binding_dtype(i).itemsize)
trt-samples-for-hackathon-cn-master
old/python/trt_lite.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import tensorrt as trt import pycuda.autoinit import pycuda.driver as cuda import ctypes def get_plugin_creator(plugin_name): trt.init_libnvinfer_plugins(logger, '') plugin_creator_list = trt.get_plugin_registry().plugin_creator_list plugin_creator = None for c in plugin_creator_list: if c.name == plugin_name: plugin_creator = c return plugin_creator def build_engine(shape_data, shape_indices, shape_updates): plugin_creator = get_plugin_creator('ScatterND') if plugin_creator == None: print('scatterND plugin not found. Exiting') exit() builder = trt.Builder(logger) network = builder.create_network(flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) tensor_data = network.add_input('data', trt.DataType.FLOAT, shape_data) tensor_indices = network.add_input('indices', trt.DataType.INT32, shape_indices) tensor_updates = network.add_input('updates', trt.DataType.FLOAT, shape_updates) layer = network.add_plugin_v2( [tensor_data, tensor_indices, tensor_updates], plugin_creator .create_plugin('ScatterND', trt.PluginFieldCollection([ ])) ) network.mark_output(layer.get_output(0)) return builder.build_engine(network, builder.create_builder_config()) def run_trt(data, indices, updates, output_0): engine = build_engine(data.shape, indices.shape, updates.shape) print("succeed to build the engine") context = engine.create_execution_context() d_indices = cuda.mem_alloc(indices.nbytes) d_data = cuda.mem_alloc(data.nbytes) d_updates = cuda.mem_alloc(updates.nbytes) d_output_0 = cuda.mem_alloc(output_0.nbytes) cuda.memcpy_htod(d_indices, indices) cuda.memcpy_htod(d_data, data) cuda.memcpy_htod(d_updates, updates) bindings = [int(d_data), int(d_indices), int(d_updates), int(d_output_0)] context.execute_v2(bindings) cuda.memcpy_dtoh(output_0, d_output_0) return output_0 if __name__ == "__main__": logger = trt.Logger(trt.Logger.INFO) ctypes.cdll.LoadLibrary('../build/ScatterND.so') data = np.array( [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32) indices = np.array([[0], [2]], dtype=np.int32) updates = np.array( [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32) # Expecting output as np.array( # [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], # [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], # [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], # [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32) output_0 = np.zeros(data.shape, dtype=np.float32) output_0 = run_trt(data, indices, updates, output_0) print(f"data shape: {data.shape} indices shape: {indices.shape} updates shape: {updates.shape} output shape: {output_0.shape} ") print(f"data {data} \n indices: \n {indices} \n updates: \n {updates} \n result: \n {output_0}")
trt-samples-for-hackathon-cn-master
old/python/app_ScatterND_plugin.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from functools import reduce import numpy as np import tensorrt import pycuda.driver as cuda import pycuda.autoinit from trt_lite import TrtLite np.set_printoptions(threshold=np.inf) def build_engine_static(builder, input_shape): network = builder.create_network() data = network.add_input("data", tensorrt.DataType.FLOAT, input_shape) w = np.asarray( [0, 0, 0, 0, 1, 0, 0, 0, 0], dtype = np.float32) b = np.zeros((1,), np.float32) conv = network.add_convolution(data, 1, (3, 3), w, b) conv.stride = (1, 1) conv.padding = (1, 1) print('conv', conv.get_output(0).shape) network.mark_output(conv.get_output(0)) builder.max_batch_size = 64 return builder.build_engine(network, builder.create_builder_config()) def run_engine_static(save_and_load=False): batch_size = 1 input_shape = (batch_size, 1, 5, 5) n = reduce(lambda x, y: x * y, input_shape) input_data = np.asarray(range(n), dtype=np.float32).reshape(input_shape) output_data = np.zeros(input_shape, dtype=np.float32) trt = TrtLite(build_engine_static, (input_shape[1:],)) if save_and_load: trt.save_to_file("out.trt") trt = TrtLite(engine_file_path="out.trt") trt.print_info() d_buffers = trt.allocate_io_buffers(batch_size, True) cuda.memcpy_htod(d_buffers[0], input_data) trt.execute(d_buffers, batch_size) cuda.memcpy_dtoh(output_data, d_buffers[1]) print(output_data) def build_engine_dynamic(builder): network = builder.create_network(1) data = network.add_input("data", tensorrt.DataType.FLOAT, (-1, 1, -1, -1)) w = np.asarray( [0, 0, 0, 0, 1, 0, 0, 0, 0], dtype = np.float32) b = np.zeros((1,), np.float32) conv = network.add_convolution(data, 1, (3, 3), w, b) conv.stride = (1, 1) conv.padding = (1, 1) print('conv', conv.get_output(0).shape) network.mark_output(conv.get_output(0)) op = builder.create_optimization_profile() op.set_shape('data', (1, 1, 3, 3), (1, 1, 5, 5), (16, 1, 128, 128)) config = builder.create_builder_config() config.add_optimization_profile(op) return builder.build_engine(network, config) def run_engine_dynamic(save_and_load=False): input_shape = (1, 1, 5, 5) n = reduce(lambda x, y: x * y, input_shape) input_data = np.asarray(range(n), dtype=np.float32).reshape(input_shape) output_data = np.zeros(input_shape, dtype=np.float32) trt = TrtLite(build_engine_dynamic) if save_and_load: trt.save_to_file("out.trt") trt = TrtLite(engine_file_path="out.trt") trt.print_info() i2shape = {0: input_shape} d_buffers = trt.allocate_io_buffers(i2shape, True) cuda.memcpy_htod(d_buffers[0], input_data) trt.execute(d_buffers, i2shape) cuda.memcpy_dtoh(output_data, d_buffers[1]) print(output_data) if __name__ == '__main__': run_engine_static() run_engine_static(True) run_engine_dynamic() run_engine_dynamic(True)
trt-samples-for-hackathon-cn-master
old/python/app_basic.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import torch import numpy as np src_onnx = 'custom.onnx' dst_onnx = 'custom_surgeon.onnx' class CustomModel(torch.nn.Module): def forward(self, x, grid): grid = torch.clamp(grid, -1.0, 1.0) return torch.nn.functional.grid_sample(input=x, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=True) x = torch.randn(1, 3, 544, 960) grid = torch.randn(1, 544, 960, 2) custom = CustomModel() print('output shape:', custom(x, grid).size()) input_names = ['x', 'grid'] output_names = ['y'] torch.onnx.export(custom, (x, grid), src_onnx, input_names=input_names, output_names=output_names, opset_version=11, verbose=True, operator_export_type=torch.onnx.OperatorExportTypes.ONNX_FALLTHROUGH, do_constant_folding=False) import onnx_graphsurgeon as gs import onnx import numpy as np graph = gs.import_onnx(onnx.load(src_onnx)) for node in graph.nodes: if node.op == 'Resize' and node.i(2, 0).op == 'Concat': # actually not used in this sample node_concat = node.i(2, 0) values = [] for i in range(len(node_concat.inputs)): c = node_concat.i(i, 0) # print(c) while c.op != 'Constant': c = c.i(0, 0) values.append(c.attrs['value'].values) #以下是不可靠的写法(不可靠地假定了0号父亲是Constant) #node_concat.i(0, 0).attrs['value'] = gs.Constant('', np.concatenate(values)) #node.inputs[2] = node_concat.inputs[0] #以下是更可靠的写法 node_constant = gs.Node(op="Constant", name=node_concat.name, attrs={'value':gs.Constant('', np.concatenate(values))}) node_constant.outputs = node_concat.outputs[:] graph.nodes.append(node_constant) node_concat.outputs.clear() if node.op == 'Unsqueeze' and node.i(0, 0).op == 'Constant' and node.i(0, 0).attrs['value'].dtype == np.float64: node.i(0, 0).attrs['value'] = gs.Constant('', np.asarray([node.i(0, 0).attrs['value'].values], dtype=np.float32)) if node.op == 'Clip': node_cast0 = node.i(1, 0) node_cast1 = node.i(2, 0) #change data type to fp32 node_cast0.i(0, 0).attrs['value'] = gs.Constant('', np.asarray([-1.0], dtype=np.float32)) node_cast1.i(0, 0).attrs['value'] = gs.Constant('', np.asarray([1.0], dtype=np.float32)) #skip cast node.inputs = [node.inputs[0], node_cast0.inputs[0], node_cast1.inputs[0]] #cleanup cast node_cast0.outputs.clear() node_cast1.outputs.clear() if node.op == 'grid_sampler': #cleanup 3 unused inputs for i in [4, 3, 2]: node.i(i, 0).outputs.clear() del node.inputs[i] graph.cleanup() onnx.save(gs.export_onnx(graph), dst_onnx) model = onnx.load(dst_onnx) # May not work with non-standard ONNX op #onnx.checker.check_model(model) #print(onnx.helper.printable_graph(model.graph)) #trtexec --verbose --onnx=custom_surgeon.onnx --saveEngine=custom_surgeon.trt --plugins=./GridSamplerPlugin.so
trt-samples-for-hackathon-cn-master
old/python/app_onnx_custom.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import torch import torchvision import time import ctypes cudart = ctypes.CDLL('libcudart.so') torch.manual_seed(0) resnet50 = torchvision.models.resnet50().cuda() resnet50.eval() input_data = torch.randn(1, 3, 1080, 1920, dtype=torch.float32, device='cuda') nRound = 10 cudart.cudaProfilerStart() with torch.no_grad(): torch.cuda.synchronize() t0 = time.time() for i in range(nRound): resnet50(input_data) torch.cuda.synchronize() time_pytorch = (time.time() - t0) / nRound print('PyTorch time:', time_pytorch) cudart.cudaProfilerStop()
trt-samples-for-hackathon-cn-master
old/python/app_decode_inference.py
#!/usr/bin/python3 # # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import tensorrt as trt import pycuda.autoinit import pycuda.driver as cuda import ctypes def get_plugin_creator(plugin_name): trt.init_libnvinfer_plugins(logger, '') plugin_creator_list = trt.get_plugin_registry().plugin_creator_list plugin_creator = None for c in plugin_creator_list: if c.name == plugin_name: plugin_creator = c return plugin_creator def build_engine(shape_indices): plugin_creator = get_plugin_creator('OnehotPlugin') if plugin_creator == None: print('OnehotPlugin plugin not found. Exiting') exit() builder = trt.Builder(logger) network = builder.create_network(flags=1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) tensor_indices = network.add_input('indices', trt.DataType.INT32, shape_indices) depth = 10 layer = network.add_plugin_v2( [tensor_indices], plugin_creator.create_plugin('OnehotPlugin', trt.PluginFieldCollection([ trt.PluginField('depth', np.array([depth], dtype=np.int32), trt.PluginFieldType.INT32) ]))) network.mark_output(layer.get_output(0)) return builder.build_engine(network, builder.create_builder_config()) def run_trt(indices, output_0): engine = build_engine(indices.shape) print("succeed to build the engine") context = engine.create_execution_context() d_indices = cuda.mem_alloc(indices.nbytes) d_output_0 = cuda.mem_alloc(output_0.nbytes) cuda.memcpy_htod(d_indices, indices) bindings = [int(d_indices), int(d_output_0)] context.execute_v2(bindings) cuda.memcpy_dtoh(output_0, d_output_0) return output_0 if __name__ == "__main__": logger = trt.Logger(trt.Logger.INFO) ctypes.cdll.LoadLibrary('../build/OnehotPlugin.so') indices = np.array([[1, 9], [2, 4]], dtype=np.int32) output_0 = np.zeros([2, 2, 10], dtype=np.float32) output_0 = run_trt(indices, output_0) print(f"indices shape: {indices.shape} output shape: {output_0.shape} ") print(f"indices: \n {indices} \n result: \n {output_0}")
trt-samples-for-hackathon-cn-master
old/python/app_Onehot_plugin.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # import json import subprocess from parseTrtexecLog import parse_build_log, parse_profiling_log from trex import EnginePlan, layer_type_formatter, render_dot, to_dot onnxFile = "./model/model.onnx" trtFile = "./model/model.plan" # build buildLogfile = "./model/build.log" buildMetadataJsonFile = "./model/build.metadata.json" buildTimingCacheFile = "./model/build.timingCache.cache" # profile profileLogFile = "./model/profile.log" profileJsonFile = "./model/profile.json" profileMetadatadJsonFile = "./model/profile.metadata.json" profileTimingJsonFile = "./model/profile.timing.json" # draw graphJsonFile = "./model/graph.json" # build engine ----------------------------------------------------------------- cmd_line = "trtexec --verbose --profilingVerbosity=detailed --buildOnly --workspace=4096 --onnx=%s --saveEngine=%s --timingCacheFile=%s" % \ (onnxFile,trtFile,buildTimingCacheFile) with open(buildLogfile, "w") as f: log = subprocess.run(cmd_line.split(" "), check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) f.write(log.stdout) with open(buildMetadataJsonFile, "w") as f: json.dump(parse_build_log(buildLogfile), f) print("\nSucceeded building engine\n\t%s\n\t%s\n\t%s" % (buildLogfile, buildTimingCacheFile, buildMetadataJsonFile)) # profile engine --------------------------------------------------------------- cmd_line = "trtexec --verbose --profilingVerbosity=detailed --noDataTransfers --useCudaGraph --separateProfileRun --useSpinWait --loadEngine=%s --exportProfile=%s --exportTimes=%s --exportLayerInfo=%s" % \ (trtFile, profileJsonFile, profileTimingJsonFile, graphJsonFile) with open(profileLogFile, "w") as f: log = subprocess.run(cmd_line.split(" "), check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) f.write(log.stdout) with open(profileMetadatadJsonFile, "w") as f: json.dump(parse_profiling_log(profileLogFile), f) print("\nSucceeded profiling engine\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s" % (profileLogFile, profileJsonFile, profileTimingJsonFile, graphJsonFile, profileMetadatadJsonFile)) # draw graph ------------------------------------------------------------------- plan = EnginePlan(graphJsonFile) formatter = layer_type_formatter graph = to_dot(plan, formatter, display_regions=True, expand_layer_details=False) render_dot(graph, graphJsonFile, "svg") print("\nSucceeded drawing graph\n\t%s" % graphJsonFile)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/mainProcess.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs onnxFile = "./model.onnx" # 创建 .onnx 模型文件 ------------------------------------------------------------ tensor0 = gs.Variable("tensor-0", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) graphNodeList = [] tensor1 = gs.Variable("tensor-1", np.float32, None) node1 = gs.Node("Conv", "Conv-1", inputs=[tensor0, constant32x1, constant32], outputs=[tensor1]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor2 = gs.Variable("tensor-2", np.float32, None) node2 = gs.Node("Relu", "ReLU-2", inputs=[tensor1], outputs=[tensor2]) graphNodeList.append(node2) tensor3 = gs.Variable("tensor-3", np.float32, None) node3 = gs.Node("MaxPool", "MaxPool-3", inputs=[tensor2], outputs=[tensor3]) node3.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node3) tensor4 = gs.Variable("tensor-4", np.float32, None) node1 = gs.Node("Conv", "Conv-4", inputs=[tensor3, constant64x32, constant64], outputs=[tensor4]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor5 = gs.Variable("tensor-5", np.float32, None) node5 = gs.Node("Relu", "ReLU-5", inputs=[tensor4], outputs=[tensor5]) graphNodeList.append(node5) tensor6 = gs.Variable("tensor-6", np.float32, None) node6 = gs.Node("MaxPool", "MaxPool-6", inputs=[tensor5], outputs=[tensor6]) node6.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node6) tensor7 = gs.Variable("tensor-7", np.float32, None) node7 = gs.Node("Transpose", "Transpose-7", inputs=[tensor6], outputs=[tensor7], attrs=OrderedDict([("perm", [0, 2, 3, 1])])) graphNodeList.append(node7) tensor8 = gs.Variable("tensor-8", np.float32, None) node8 = gs.Node("Reshape", "Reshape-7", inputs=[tensor7, constantM1Comma3136], outputs=[tensor8]) graphNodeList.append(node8) tensor9 = gs.Variable("tensor-9", np.float32, None) node9 = gs.Node("MatMul", "MatMul-9", inputs=[tensor8, constant3136x1024], outputs=[tensor9]) graphNodeList.append(node9) tensor10 = gs.Variable("tensor-10", np.float32, None) node10 = gs.Node("Add", "Add-10", inputs=[tensor9, constant1024], outputs=[tensor10]) graphNodeList.append(node10) tensor11 = gs.Variable("tensor-11", np.float32, None) node11 = gs.Node("Relu", "ReLU-11", inputs=[tensor10], outputs=[tensor11]) graphNodeList.append(node11) tensor12 = gs.Variable("tensor-12", np.float32, None) node12 = gs.Node("MatMul", "MatMul-12", inputs=[tensor11, constant1024x10], outputs=[tensor12]) graphNodeList.append(node12) tensor13 = gs.Variable("tensor-13", np.float32, None) node13 = gs.Node("Add", "Add-13", inputs=[tensor12, constant10], outputs=[tensor13]) graphNodeList.append(node13) tensor14 = gs.Variable("tensor-14", np.float32, None) node14 = gs.Node("Softmax", "Softmax-14", inputs=[tensor13], outputs=[tensor14], attrs=OrderedDict([("axis", 1)])) graphNodeList.append(node14) tensor15 = gs.Variable("tensor-15", np.int64, None) node15 = gs.Node("ArgMax", "ArgMax-15", inputs=[tensor14], outputs=[tensor15], attrs=OrderedDict([("axis", 1), ("keepdims", 0)])) graphNodeList.append(node15) graph = gs.Graph(nodes=graphNodeList, inputs=[tensor0], outputs=[tensor15]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), onnxFile) print("Succeeded create %s" % onnxFile)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/getOnnxModel.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # import os import sys from setuptools import find_packages, setup def no_publish(): blacklist = ["register"] for cmd in blacklist: if cmd in sys.argv: raise RuntimeError('Command "{}" blacklisted'.format(cmd)) def main(): no_publish() with open("requirements.txt", "r") as req_file: required_pckgs = [line.strip() for line in req_file.readlines()] setup( name="trex", version="0.1.2", description="TREX: TensorRT Engine Exploration Toolkit", long_description="", author="NVIDIA", author_email="[email protected]", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python :: 3", ], license="Apache 2.0", install_requires=required_pckgs, packages=find_packages(exclude=("model")), zip_safe=True, ) if __name__ == "__main__": main()
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/setup.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ trtexec log file parsing """ import json import re from enum import Enum, unique from pickle import BUILD from typing import Any, Dict, List, Tuple def __to_float(line: str) -> float: """Scan the input string and extract the first float instance.""" # https://docs.python.org/3/library/re.html#simulating-scanf float_match = re.search(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?", line) if float_match is None: raise ValueError start, end = float_match.span() return float(line[start:end]) def __get_stats(line: str) -> List[float]: """Parse a string containing pairs of "key = value" and return the list of values. Here's a sample input line: "min = 0.87854 ms, max = 0.894043 ms, mean = 0.881251 ms" The values are expected to be floats. Split the kv list to "k = v" substrings, then split each substring to k, v and return float(v) """ return [__to_float(substr.split("=")[1]) for substr in line.split(",")] class FileSection: def __init__(self, section_header: str): self.section_header = section_header self.dict = {} def entered_section(self, line: str): s = re.search(self.section_header, line) return s is not None def parse_line(self, line: str): def parse_kv_line(line: str) -> Tuple[Any, Any]: """Parse a log line that reports a key-value pair. The log line has this format: [mm/dd/yyyy-hh:mm:ss] [I] key_name: key_value """ match = re.search(r'(\[\d+/\d+/\d+-\d+:\d+:\d+\] \[I\] )', line) if match is not None: match_end = match.span()[1] kv_line = line[match_end:].strip() kv = kv_line.split(": ") if len(kv) > 1: return kv[0], kv[1] return None, None k, v = parse_kv_line(line) if k is not None and v is not None: self.dict[k] = v return True return False def __parse_log_file(file_name: str, sections: List) -> List[Dict]: current_section = None with open(file_name, "r") as file: for line in file.readlines(): if current_section is None: for section in sections: if section.entered_section(line): current_section = section break else: if not current_section.parse_line(line): current_section = None dicts = [section.dict for section in sections] return dicts def parse_build_log(file_name: str) -> List[Dict]: """Parse the TensorRT engine build log and extract the builder configuration. Returns the model and engine build configurations as dictionaries. """ model_options = FileSection("=== Model Options ===") build_options = FileSection("=== Build Options ===") sections = [model_options, build_options] __parse_log_file(file_name, sections) return { "model_options": model_options.dict, "build_options": build_options.dict, } def parse_profiling_log(file_name: str): performance_summary = FileSection("=== Performance summary ===") inference_options = FileSection("=== Inference Options ===") device_information = FileSection("=== Device Information ===") sections = [performance_summary, inference_options, device_information] __parse_log_file(file_name, sections) def post_process_perf(perf_summary: dict): """Normalize the log results to a standard format""" for k, v in perf_summary.items(): if k in ["Throughput", "Total Host Walltime", "Total GPU Compute Time"]: perf_summary[k] = __to_float(v) if k in ["Latency", "Enqueue Time", "H2D Latency", "GPU Compute Time", "D2H Latency"]: perf_summary[k] = __get_stats(v) return perf_summary def post_process_device_info(device_info: dict): """Convert some value fields to float""" for k, v in device_info.items(): if k in ["Compute Clock Rate", "Memory Bus Width", "Memory Clock Rate", "Compute Capability", "SMs"]: device_info[k] = __to_float(v) return device_info return {"performance_summary": post_process_perf(performance_summary.dict), "inference_options": inference_options.dict, "device_information": post_process_device_info(device_information.dict)}
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/parseTrtexecLog.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ TensorRT Engine Exploration API - EnginePlan """ import ntpath import warnings from copy import deepcopy from typing import List, Tuple import pandas as pd from .df_preprocessing import * from .layer import Layer, fold_no_ops from .parser import * class EnginePlan: def __init__( self, graph_file: str, profiling_file: str = None, profiling_metadata_file: str = None, build_metadata_file: str = None, name: str = None, ): def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) def create_layers(self, raw_layers): layers = [Layer(raw_layer) for raw_layer in raw_layers] self.layers = fold_no_ops(layers, self.bindings) self.all_layers = deepcopy(self.layers) self.layers = [layer for layer in self.layers if layer.type != "Constant"] return raw_layers def process_profiling_file(profiling_file, ignore_layers): if not profiling_file: return None raw_perf = read_profiling_file(profiling_file) raw_perf = [perf_rec for perf_rec in raw_perf if perf_rec["name"] not in ignore_layers] return raw_perf def merge_profiling_data(graph_df, raw_perf): if raw_perf is not None: perf_df = pd.DataFrame.from_dict(raw_perf) perf_df.drop(columns=["name"], inplace=True) perf_df.rename(columns={ "percentage": "latency.pct_time", "averageMs": "latency.avg_time", "timeMs": "latency.time", }, inplace=True) df = graph_df.join(perf_df) else: warnings.warn("Profiling data was not provided.") df = graph_df df["latency.pct_time"] = [0] * len(df) df["latency.avg_time"] = [0] * len(df) df["latency.time"] = [0] * len(df) return df def add_graph_summation_cols(df, layers): # Add new (summation) columns df["total_io_size_bytes"] = [l.total_io_size_bytes for l in layers] df["weights_size"] = [l.weights_size for l in layers] df["total_footprint_bytes"] = [l.total_footprint_bytes for l in layers] df["precision"] = [l.precision for l in layers] return df def construct_df(raw_layers): raw_layers = [raw_layer for raw_layer in raw_layers if raw_layer["LayerType"] not in ["Constant", "NoOp"]] graph_df = pd.DataFrame.from_dict(raw_layers) graph_df = fix_df(graph_df) return graph_df def compute_summary(self): self.total_act_size = sum([l.total_io_size_bytes for l in self.layers]) self.total_weights_size = sum([l.weights_size for l in self.layers]) assert self.total_weights_size == self.df["weights_size"].sum() self.total_runtime = sum([avg_time for avg_time in self._df["latency.avg_time"]]) self.name = name or path_leaf(graph_file) raw_layers, self.bindings = import_graph_file(graph_file) raw_layers = create_layers(self, raw_layers) self._df = None ignore_layers = [raw_layer["Name"] for raw_layer in raw_layers if raw_layer["LayerType"] in ["Constant", "NoOp"]] self._raw_perf = process_profiling_file(profiling_file, ignore_layers=ignore_layers) graph_df = construct_df(raw_layers) graph_df = add_graph_summation_cols(graph_df, self.layers) self._df = merge_profiling_data(graph_df, self._raw_perf) compute_summary(self) self.device_properties = get_device_properties(profiling_metadata_file) self.performance_summary = get_performance_summary(profiling_metadata_file) self.builder_cfg = get_builder_config(build_metadata_file) assert self._df is not None, f"Failed parsing plan file {graph_file}" @property def df(self): return self._df def get_layers_by_type(self, layer_type): return filter_by_layer(self._df, layer_type) def find(self, layer_name: str): for l in self.layers: if layer_name == l.name: return l return None def get_bindings(self) -> Tuple[List[Activation], List[Activation]]: """Return a list of the inputs bindings and a list of the output bindings""" inputs, outputs = [], [] for layer in self.layers: inputs += [inp for inp in layer.inputs if inp.name in self.bindings] outputs += [outp for outp in layer.outputs if outp.name in self.bindings] return inputs, outputs def summary(self): return print_summary(self) def summary_dict(plan: EnginePlan): """Create a dictionary of important attributes of the engine plan.""" MB_1 = 1024 * 1024 bindings = plan.get_bindings() d = { "Inputs": f"{bindings[0]}", "Average time": f"{plan.total_runtime:.3f} ms", "Layers": f"{len(plan.df)}", "Weights": f"{plan.total_weights_size / MB_1 :.1f} MB", "Activations": f"{plan.total_act_size/ MB_1 :.1f} MB", } return d def print_summary(plan: EnginePlan): def print_dict(d: Dict): for k, v in d.items(): print(f"\t{k}: {v}") print("Model:") print_dict(summary_dict(plan)) print("Device Properties:") print_dict(plan.device_properties) print("Performance Summary:") print_dict(plan.performance_summary)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/engine_plan.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains miscellanous utility functions. """ import functools from typing import Dict, List, Tuple import pandas as pd def group_count(df, grouping_attr): grp = df.groupby([grouping_attr]).size().to_frame().reset_index() grp.rename(columns={0: "count"}, inplace=True) return grp def group_sum_attr(df, grouping_attr, reduced_attr): grp = df.groupby([grouping_attr]).sum()[reduced_attr].to_frame().reset_index() return grp def shape_to_str(shape): return "[" + ",".join(str(dim) for dim in shape) + "]" def _merge_keys_values(keys_lists: List[List], values_lists: List[List], empty_placeholder: object) -> Dict: # Concatenate the keys lists into a set of all keys all_keys = set(functools.reduce(lambda a, b: a + b, keys_lists)) # Create the stacked output dictionary, and fill missing values. dicts = [dict(zip(keys, values)) for keys, values in zip(keys_lists, values_lists)] result = {} for key in all_keys: for d in dicts: if key not in d: d[key] = empty_placeholder result[key] = [d[key] for d in dicts] return result def stack_dicts(dict_list: List[dict], empty_placeholder: object = 0): """Stack lists of dictionaries as a single dictionary""" # A list of names lists. keys_lists = [list(d.keys()) for d in dict_list] # A list of values lists. values_lists = [list(d.values()) for d in dict_list] return _merge_keys_values(keys_lists, values_lists, empty_placeholder) def stack_dataframes( df_list: List[pd.DataFrame], names_col: str, values_col: str, empty_placeholder: object = 0, ): # A list of names lists. names = [df[names_col].tolist() for df in df_list] # A list of values lists. values = [df[values_col].tolist() for df in df_list] return _merge_keys_values(names, values, empty_placeholder)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/misc.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ Performance report card. This file contains interaction cells for the engine_report_card.ipynb notebook. """ from functools import partial from .df_preprocessing import clean_for_display from .graphing import * from .interactive import InteractiveDiagram, InteractiveDiagram_2 from .misc import group_count, group_sum_attr from .notebook import display_df from .parser import read_timing_file from .plotting import * def report_card_perf_overview(plan: EnginePlan): """Display performance overview diagrams. Display a dropdown widget to choose between diagrams showing various characteristics of the plan's convolution layers.""" layer_types = group_count(plan.df, "type") count_per_layer_type = partial(plotly_bar2, layer_types, values_col="count", names_col="type", color="type", colormap=layer_colormap, orientation="h", show_axis_ticks=(True, True)) time_pct_by_type = plan.df.groupby(["type"]).sum()[["latency.pct_time", "latency.avg_time"]].reset_index() latency_per_type_ms = partial(plotly_bar2, time_pct_by_type, values_col="latency.avg_time", names_col="type", color="type", colormap=layer_colormap, orientation="h", show_axis_ticks=(True, True)) latency_per_type_pct = partial(plotly_bar2, time_pct_by_type, values_col="latency.pct_time", names_col="type", color="type", colormap=layer_colormap, orientation="h", show_axis_ticks=(True, True)) precision_per_layer = partial(plotly_bar2, plan.df, values_col="latency.avg_time", names_col="Name", color="precision", colormap=precision_colormap, xaxis_title="Layer") output_precision_per_layer = partial(plotly_bar2, plan.df, values_col="latency.avg_time", names_col="Name", color="output_precision", colormap=precision_colormap, xaxis_title="Layer") output_precision_per_layer = partial(plotly_bar2, plan.df, values_col="latency.avg_time", names_col="Name", color="output_precision", colormap=precision_colormap, xaxis_title="Layer") latency_distribution = partial(plotly_hist, plan.df, values_col="latency.pct_time", xaxis_title='Latency (ms)', color="type", colormap=layer_colormap) latency_per_layer = partial(plotly_bar2, plan.df, values_col="latency.pct_time", names_col="Name", color="type", colormap=layer_colormap, xaxis_title="Layer") latency_per_layer_ms = partial(plotly_bar2, plan.df, values_col="latency.avg_time", names_col="Name", color="type", colormap=layer_colormap, xaxis_title="Layer") precision_charts = [] layer_precisions = group_count(plan.df, "precision") precision_charts.append((layer_precisions, 'Layer Count By Precision', "count", "precision")) layers_time_pct_by_precision = group_sum_attr(plan.df, grouping_attr="precision", reduced_attr="latency.pct_time") precision_charts.append((layers_time_pct_by_precision, '% Latency By Precision', "latency.pct_time", "precision")) precision_statistics = partial(plotly_pie2, charts=precision_charts, colormap=precision_colormap) def precision_per_type(title): title = f"{title}\n({plan.name})" df = plan.df precision_sunburst = df.groupby(["type", "precision"]).count().reset_index() color = [precision_colormap[p] for p in df["precision"]] fig = px.sunburst(precision_sunburst, path=["type", "precision"], values="Name", color_discrete_map=precision_colormap, color="precision") fig.update_layout( title=title, title_x=0.5, font_size=15, ) fig.show() dropdown_choices = { "Latency per layer (%)": latency_per_layer, "Latency per layer (ms)": latency_per_layer_ms, "Layer latency distribution": latency_distribution, "Precision per layer": precision_per_layer, "Output precision per layer": output_precision_per_layer, "Count per layer type": count_per_layer_type, "Latency per layer type (ms)": latency_per_type_ms, "Latency per layer type (%)": latency_per_type_pct, "Precision per layer type": precision_per_type, "Precision rollup": precision_statistics, } return InteractiveDiagram_2(dropdown_choices, 'Diagram:') def report_card_convolutions_overview(convs: pd.DataFrame): """Display convolution layer diagrams. Display a dropdown widget to choose between diagrams showing various characteristics of the plan's convolution layers""" latency_vs_ai_per_conv = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="attr.arithmetic_intensity", colormap=precision_colormap) latency_vs_prec_per_conv = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="precision", colormap=precision_colormap) latency_vs_fmas = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="attr.macs") latency_vs_data = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="total_footprint_bytes") latency_vs_ce_per_conv = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="attr.compute_efficiency", colormap=precision_colormap) latency_vs_group_size = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="attr.groups") latency_vs_kernel_size = partial(plotly_bar2, convs, values_col="latency.pct_time", names_col="Name", color="attr.kernel") footprint_per_conv = partial(plotly_bar2, convs, values_col="total_footprint_bytes", names_col="Name", color="latency.pct_time") fmas_per_conv = partial(plotly_bar2, convs, values_col="attr.macs", names_col="Name", color="latency.pct_time") ai_vs_latency_per_conv = partial(plotly_bar2, convs, values_col="attr.arithmetic_intensity", names_col="Name", color="latency.pct_time") ai_vs_footprint_per_conv = partial(plotly_bar2, convs, values_col="attr.arithmetic_intensity", names_col="Name", color="total_footprint_bytes") ce_vs_latency_per_conv = partial(plotly_bar2, convs, values_col="attr.compute_efficiency", names_col="Name", color="latency.pct_time") me_vs_latency_per_conv = partial(plotly_bar2, convs, values_col="attr.memory_efficiency", names_col="Name", color="latency.pct_time") dropdown_choices = { "Latency per convolution (color = precision)": latency_vs_prec_per_conv, "Latency per convolution (color = FMAs)": latency_vs_fmas, "Latency per convolution (color = data size)": latency_vs_data, "Latency per convolution (color = arithmetic intensity)": latency_vs_ai_per_conv, "Latency per convolution (color = compute efficiency)": latency_vs_ce_per_conv, "Latency per convolution (color = group size)": latency_vs_group_size, "Latency per convolution (color = kernel size)": latency_vs_kernel_size, "Data footprints": footprint_per_conv, "Fused Multiply-Accumulate (FMAs)": fmas_per_conv, "Arithmetic intensity (color = latency)": ai_vs_latency_per_conv, "Arithmetic intensity (color = footprint)": ai_vs_footprint_per_conv, "Compute efficiency (color = latency)": ce_vs_latency_per_conv, "Memory efficiency (color = latency)": me_vs_latency_per_conv, } InteractiveDiagram_2(dropdown_choices, 'Diagram:') def report_card_table_view(plan: EnginePlan): """Layers tabular views. Display a dropdown widget to choose among tabular views of all, or specific, layers""" def render_diagram(choice, ignore): if choice == "All": display_df(clean_for_display(plan.df)) else: df = plan.get_layers_by_type(choice) print(f"There are {len(df)} {choice} layers which account for" f"{df["latency.pct_time"].sum(): .2f}% ({df["latency.avg_time"].sum(): .5f} ms) of the overall latency.") display_df(clean_for_display(df)) types = ["All"] + list(set(plan.df["type"])) dropdown_choices = {t: t for t in types} InteractiveDiagram(render_diagram, dropdown_choices, "Dataframe") def report_card_memory_footprint(plan: EnginePlan): """Memory footprint diagrams""" def render_diagram(choice, values_col, colormap): if "distribution" in choice: plotly_hist(plan.df, f"{choice}", values_col, "Size (bytes)", color="type", colormap=colormap) else: plotly_bar2(plan.df, f"{choice}", values_col, "Name", color="type", colormap=colormap, show_axis_ticks=(False, True)) dropdown_choices = { "Weights footprint per layer": ("weights_size", layer_colormap), "Activation footprint per layer": ("total_io_size_bytes", layer_colormap), "Total footprint per layer": ("total_footprint_bytes", layer_colormap), "Weights footprint distribution per layer": ("weights_size", layer_colormap), "Activations footprint distribution per layer": ("total_io_size_bytes", layer_colormap), "Total footprint distribution per layer": ("total_footprint_bytes", layer_colormap), } InteractiveDiagram(render_diagram, dropdown_choices, 'Bar color') def report_card_draw_plan_graph(plan: EnginePlan, engine_name: str): """Draw the plan graph (export to SVG)""" def render_diagram(choice, formatter, display_regions, expand_layer_details): graph = to_dot(plan, formatter, display_regions=display_regions, expand_layer_details=expand_layer_details) render_dot(graph, engine_name, "svg") # Color code nodes by precision or layer-type dropdown_choices = { "Color nodes by type": (layer_type_formatter, False, False), "Color nodes by type (detailed)": (layer_type_formatter, True, True), "Color nodes by precision": (precision_formatter, False, False), "Color nodes by precision (detailed)": (precision_formatter, True, True), } InteractiveDiagram(render_diagram, dropdown_choices, 'Color formatting:') def report_card_pointwise_lint(plan: EnginePlan): pws = plan.get_layers_by_type("PointWise") if len(pws) == 0: print("The engine plan does not contain pointwise layers.") return charts = [] by_n_operations = group_count(pws, "attr.n_operations") charts.append((by_n_operations, "Pointwise layers by number of operations", "count", "attr.n_operations")) layers_time_pct_by_n_operations = group_sum_attr(pws, grouping_attr="attr.n_operations", reduced_attr="latency.pct_time") charts.append((layers_time_pct_by_n_operations, "Latency by number of operations (%)", "latency.pct_time", "attr.n_operations")) df = layers_time_pct_by_n_operations.merge(by_n_operations, on="attr.n_operations") df["per_op_latency"] = df["latency.pct_time"] / (df["count"] * df["attr.n_operations"]) pws["per_op_latency"] = pws["latency.pct_time"] / pws["attr.n_operations"] charts.append((df, "Per op latency by number of operations", "per_op_latency", "attr.n_operations")) def list_pw_operations(pws): for _, pw in pws.iterrows(): if pw["attr.n_operations"] < 2: continue operations = "\n\t".join([op for op in pw["attr.operations"]]) print(f"{pw.name}\n\t{operations}") plotly_pie2("Pointwise Statistics", charts) list_pw_operations(pws) print(pws["per_op_latency"]) def layer_latency_sunburst(df: pd.DataFrame, title: str): precision_sunburst = df.groupby(["type", "latency.pct_time"]).count().reset_index() fig = px.sunburst(precision_sunburst, path=["type", "latency.pct_time"], values="latency.avg_time", color_discrete_map=layer_colormap, color="type") fig.update_layout( title=title, title_x=0.5, font_size=15, ) fig.show() def plot_engine_timings(timing_json_file: str): """Plot the engine profiling timings""" latencies = read_timing_file(timing_json_file) samples = range(len(latencies)) fig = px.scatter(title="Engine Timing Samples", x=samples, y=latencies) trex_base_layout(fig) fig.update_layout({"yaxis_title": "Latency (ms)", "xaxis_title": "Timing Samples", "title_x": 0.5}) fig.show() def report_card_gemm_MNK(plan: pd.DataFrame): def render_scatter3d(choice, x, y, z, color, size): convs = plan.get_layers_by_type("Convolution") fig = px.scatter_3d(convs, x=x, y=y, z=z, color=color, size=size, size_max=18, opacity=0.7) trex_base_layout(fig) fig.update_layout({"title": "Implicit GEMM " + choice, "title_x": 0.5}) fig.show() dropdown_choices = { "MxNxK color=mean time; size=mean time": ( "attr.M", "attr.N", "attr.K", "latency.avg_time", "latency.avg_time", ), "MxNxK color=arithmetic intensity; size=mean time": ( "attr.M", "attr.N", "attr.K", "attr.arithmetic_intensity", "latency.avg_time", ), "MxNxK color=compute efficiency; size=mean time": ( "attr.M", "attr.N", "attr.K", "attr.compute_efficiency", "latency.avg_time", ), "MxNxK color=memory efficiency; size=mean time": ( "attr.M", "attr.N", "attr.K", "attr.memory_efficiency", "latency.avg_time", ), } InteractiveDiagram(render_scatter3d, dropdown_choices, "Diagram") def report_card_gemm_MNK_scatter(plan: pd.DataFrame): def render_scatter(choice, x, y, color, size): convs = plan.get_layers_by_type("Convolution") fig = px.scatter(convs, x=x, y=y, color=color, size=size, size_max=18, opacity=0.7) fig.update_layout(margin=dict(l=0, r=0, b=0, t=50), title=choice, title_x=0.5) fig.show() dropdown_choices = { "M vs. Latency (color = foorprint)": ("attr.M", "latency.avg_time", "total_footprint_bytes", None), "N vs. Latency (color = foorprint)": ("attr.N", "latency.avg_time", "total_footprint_bytes", None), "K vs. Latency (color = foorprint)": ("attr.K", "latency.avg_time", "total_footprint_bytes", None), } InteractiveDiagram(render_scatter, dropdown_choices, "Diagram") def report_card_efficiency_vs_latency_3d(plan: pd.DataFrame): convs = plan.get_layers_by_type("Convolution") fig = px.scatter_3d(convs, x="attr.compute_efficiency", y="attr.memory_efficiency", z="latency.avg_time", color="total_footprint_bytes", size="latency.avg_time", size_max=18, opacity=0.7) fig.update_layout(margin=dict(l=0, r=0, b=0, t=50), title="Compute-efficiency vs Memory-efficiency vs Latency", title_x=0.5) trex_base_layout(fig) fig.show() def report_card_perf_scatter(plan: pd.DataFrame): def render_scatter(choice, x, y, color, size): convs = plan.get_layers_by_type("Convolution") fig = px.scatter(convs, x=x, y=y, color=color, size=size, size_max=18, opacity=0.7) fig.update_layout(margin=dict(l=0, r=0, b=0, t=50), title=choice, title_x=0.5) fig.show() dropdown_choices = { "Compute-efficiency vs. FMAs (size = foorprint)": ( "attr.compute_efficiency", "attr.macs", "latency.avg_time", "total_footprint_bytes", ), "Memory-efficiency vs. footprint (size = FMAs)": ( "attr.memory_efficiency", "total_footprint_bytes", "latency.avg_time", "attr.macs", ), "Compute-efficiency vs. memory-efficiency (size = AI)": ("attr.compute_efficiency", "attr.memory_efficiency", "latency.avg_time", "attr.arithmetic_intensity"), "Memory footprint vs FMAs (size = AI)": ("total_footprint_bytes", "attr.macs", "latency.avg_time", "attr.arithmetic_intensity"), "Arithmetic-intensity vs. compute-efficiency (size = memory-efficiency)": ("attr.arithmetic_intensity", "attr.compute_efficiency", "latency.avg_time", "attr.memory_efficiency"), "Arithmetic-intensity vs. memory-efficiency (size = compute-efficiency)": ("attr.arithmetic_intensity", "attr.memory_efficiency", "latency.avg_time", "attr.compute_efficiency"), } InteractiveDiagram(render_scatter, dropdown_choices, "Diagram")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/report_card.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains interaction cells for the compare_engines.ipynb notebook. """ import copy from functools import partial from typing import List import numpy as np from matplotlib.pyplot import colormaps from .activations import create_activations from .engine_plan import EnginePlan, summary_dict from .interactive import * from .misc import group_count, group_sum_attr, stack_dicts from .plotting import * def get_plans_names(plans: List[EnginePlan]): """Create unique plans names""" engine_names = [plan.name for plan in plans] if len(set(engine_names)) != len(plans): engine_names = [plan.name + str(i) for i, plan in enumerate(plans)] return engine_names def compare_engines_overview(plans: List[EnginePlan]): """A dropdown widget to choose from several diagrams that compare 2 or more engine plans. """ engine_names = get_plans_names(plans) # Get throughtput data. throughtput = [plan.performance_summary.get("Throughput", 0) for plan in plans] have_throughput_data = all([tp > 0 for tp in throughtput]) def throughput_per_plan(title: str): y = [plan.performance_summary.get("Throughput", 0) for plan in plans] x = [plan.name for plan in plans] fig = px.bar(x=y, y=x, orientation="h") trex_base_layout(fig) fig.update_layout({"xaxis_title": "Throughput (inferences / sec)", "yaxis_title": "Engine"}) fig.show() time_by_type = [plan.df.groupby(["type"]).sum() \ [["latency.pct_time", "latency.avg_time"]].reset_index() for plan in plans] cnt_by_type = [group_count(plan.df, "type") for plan in plans] # Normalize timings by the batch-size. df_list_bs_normalized = [copy.deepcopy(plan.df) for plan in plans] for i, plan in enumerate(plans): inputs, outputs = plan.get_bindings() bs = inputs[0].shape[0] df_list_bs_normalized[i]["latency.avg_time"] /= bs time_by_type_bs_normalized = [df.groupby(["type"]).sum() \ [["latency.pct_time", "latency.avg_time"]].reset_index() for df in df_list_bs_normalized] def latency_per_type(title): stacked_latencies_bars = partial(stacked_bars, title, bar_names=engine_names, df_list=time_by_type, names_col="type", values_col="latency.avg_time", colormap=layer_colormap, display_tbl=False, xaxis_title="Engine", yaxis_title="Latency (ms)") if have_throughput_data: # Display throughput scatter plot together with the latencies bars. fig = make_subplots(specs=[[{"secondary_y": True}]]) stacked_latencies_bars(fig=fig) fig.add_trace(go.Scatter(x=engine_names, y=throughtput, name="Throughput (IPS)", marker=dict(size=12)), secondary_y=True) trex_base_layout(fig) fig.update_yaxes(title_text="Throughput (inferences / sec)", secondary_y=True) fig.show() else: stacked_latencies_bars() df = stacked_tabular_df(engine_names, time_by_type, "type", "latency.avg_time", empty_symbol=np.NaN) # Compute the speedup of the last engine vs. the first engine. df["speedup"] = df[engine_names[0]] / df[engine_names[-1]] print(f"\'speedup\' refers to the speedup of \"{engine_names[-1]}\" relative to \"{engine_names[0]}\"") display_df(df, range_highlights=speedup_range_highlights(col_name="speedup", threshold=0.03)) latency_per_type_bs_normalized = partial(stacked_bars, bar_names=engine_names, df_list=time_by_type_bs_normalized, names_col="type", values_col="latency.avg_time", empty_symbol=np.NaN, colormap=layer_colormap, xaxis_title="Engine", yaxis_title="Latency (ms)") d = {engine_name: df for engine_name, df in zip(engine_names, time_by_type)} latency_per_type_comparison = partial(plotly_bar2, df=d, values_col="latency.avg_time", names_col="type", orientation="h", showlegend=True) d = {engine_name: df for engine_name, df in zip(engine_names, cnt_by_type)} count_comparison = partial(plotly_bar2, df=d, values_col="count", names_col="type", orientation="h", showlegend=True) time_by_precision = [plan.df.groupby(["precision"]).sum() \ [["latency.avg_time"]].reset_index() for plan in plans] stacked_layers_by_precision = partial(stacked_bars, bar_names=engine_names, df_list=time_by_precision, names_col="precision", values_col="latency.avg_time", colormap=precision_colormap) precision_subplots = [(group_count(plan.df, "precision"), plan.name, "count", "precision") for plan in plans] precision_cnts = partial(plotly_pie2, charts=precision_subplots, colormap=precision_colormap) output_precision_subplots = [(group_count(plan.df, "output_precision"), plan.name, "count", "output_precision") for plan in plans] output_precision_cnts = partial(plotly_pie2, charts=output_precision_subplots, colormap=precision_colormap) precision_subplots = [(group_sum_attr(plan.df, grouping_attr="precision", reduced_attr="latency.pct_time"), plan.name, "latency.pct_time", "precision") for plan in plans] precision_latency = partial(plotly_pie2, charts=precision_subplots, colormap=precision_colormap) dropdown_choices = { "Stacked latencies by layer type": latency_per_type, "Stacked latencies by layer type (BS normalized)": latency_per_type_bs_normalized, "Layer count comparison": count_comparison, "Layer-type latency comparison": latency_per_type_comparison, "Layer latency by precision": stacked_layers_by_precision, "Precision counts": precision_cnts, "Output precision counts": output_precision_cnts, "Precision latency": precision_latency, } if have_throughput_data: dropdown_choices["Throughput"] = throughput_per_plan InteractiveDiagram_2(dropdown_choices, 'Diagram:') def compare_engines_summaries_tbl(plans: List[EnginePlan], orientation: str = "vertical"): """Display a tabular comparison of several engine plans.""" merged_summaries = {} summary_dicts_list = ([summary_dict(plan) for plan in plans], [plan.performance_summary for plan in plans], [plan.device_properties for plan in plans], [plan.builder_cfg for plan in plans]) for d in summary_dicts_list: merged_summaries.update(stack_dicts(d, empty_placeholder="")) if orientation == "vertical": df = pd.DataFrame.from_dict(merged_summaries, orient="index", columns=get_plans_names(plans)) df["attribute"] = list(merged_summaries.keys()) df = rotate_columns(df) df.set_index("attribute") else: df = pd.DataFrame.from_dict(merged_summaries) df["plan"] = get_plans_names(plans) df = rotate_columns(df) print(("\"Average time\": " "refers to the sum of the layer latencies, when profiling layers separately")) print(("\"Latency\": " "refers to the [min, max, mean, median, 99% percentile] of the engine latency " "measurements, when timing the engine w/o profiling layers.")) display_df(df) # Code to align and compare two plans def get_io_dimensions(layer: pd.Series, use_all_tensors: bool) -> tuple: """Return a tuple containing all the dimensions of layer's inputs and outputs. The first dimension (batch) of each input/output tensor is not included so that the batch-size is not a cause for a mismatch. For an exact (conservative) matching set `use_all_tensors` to True. To match using only the first input and output, set to False. """ inputs, outputs = create_activations(layer) if not use_all_tensors: inputs = [ inputs[0], ] outputs = [ outputs[0], ] dims_dict = {"inputs": [t.shape[1:] for t in inputs], "outputs": [t.shape[1:] for t in outputs]} return dims_dict def get_io_formats(layer: pd.Series) -> tuple: """Return a string representation of the inputs and outputs.""" inputs, outputs = create_activations(layer) in_formats = "in: " + ", ".join((f"{t.format}:{t.shape}" for t in inputs)) out_formats = "out: " + ", ".join((f"{t.format}:{t.shape}" for t in outputs)) return in_formats + "\t" + out_formats def get_io_precisions(layer: pd.Series) -> tuple: """Return two tuples representing the precisions of layer's inputs and outputs.""" if layer is None: return "", "" inputs, outputs = create_activations(layer) assert len(inputs) > 0 and len(outputs) > 0 p_in = ", ".join((t.precision for t in inputs)) p_out = ", ".join((t.precision for t in outputs)) return p_in, p_out def match_layers(plan1: EnginePlan, plan2: EnginePlan, exact_matching: bool) -> List[Tuple]: """Align two plans by their layers. When comparing the layers of two engine plans, we want to find pairs of layers, one from each plan, that correspond to the same trt.Network layer. This is not trivial since the plans may have a different number of layers, the layers may be fused differently, and they may have different names. A heuristic assigns a `signature` to each layer in the two plans. To determine if two layers correspond to the same trt.Network layer, their signatures are compared. Aligining two plans is the task of finding pairs of layers with the same signature. This function returns a list of index pairs. """ def signature(layer: pd.Series, exact: bool) -> Dict: """Returns the heuristic layer signature. The signature is composed of the layer's type and dimensions. """ sig = get_io_dimensions(layer, exact) sig["type"] = layer["type"] return sig def clamp_indexes(i1: int, i2: int) -> Tuple: i1 = min(i1, len(plan1.df) - 1) i2 = min(i2, len(plan2.df) - 1) return i1, i2 def are_equal(s1: Dict, s2: Dict) -> bool: assert list(s1.keys()) == list(s2.keys()), "Internal error: signature are corrupt" for k in s1.keys(): if s1[k] != s2[k]: return False return True def is_aligned(i1: int, i2: int, exact_matching: bool) -> bool: """Return True if row `i1` of plan1 is aligned with row `i2` of plan2. """ def pointwise_same(s1: Dict, s2: Dict): """Special signatures comparison for pointwise layers. When comparing PointWise layers allow the inputs to be connected in reverse order.""" same = False types_ok = s1["type"] == s2["type"] == "PointWise" in_lengths_ok = len(s1["inputs"]) == 2 and len(s2["inputs"]) == 2 out_lengths_ok = len(s1["outputs"]) == 1 and len(s2["outputs"]) == 1 if types_ok and in_lengths_ok and out_lengths_ok: same = s1["inputs"][0] == s2["inputs"][1] and s1["inputs"][1] == s2["inputs"][0] return same i1, i2 = clamp_indexes(i1, i2) s1 = signature(plan1.df.loc[i1], exact_matching) s2 = signature(plan2.df.loc[i2], exact_matching) aligned = are_equal(s1, s2) if not aligned: aligned = pointwise_same(s1, s2) return aligned def beam_search(beam_size, unprocessed_indices, list_id): """Shine a search beam and look for a match in the other list. """ i1 = unprocessed_indices[0][0] i2 = unprocessed_indices[1][0] for s in range(beam_size): # clamp idx = min(s, len(unprocessed_indices[list_id]) - 1) if list_id == 1: i2 = unprocessed_indices[list_id][idx] else: i1 = unprocessed_indices[list_id][idx] if is_aligned(i1, i2, exact_matching): return i1, i2 if list_id == 1: return i1, None else: return None, i2 def debug_print(i1: int, i2: int): return # disable print t1 = plan1.df.loc[i1]["type"] if i1 is not None else "None" t2 = plan2.df.loc[i2]["type"] if i2 is not None else "None" print(f"{i1}: {t1} {i2}: {t2}") matched_indices_pairs = [] unprocessed_indices_1 = [*range(len(plan1.df))] unprocessed_indices_2 = [*range(len(plan2.df))] while unprocessed_indices_1 and unprocessed_indices_2: beam_size = max(len(unprocessed_indices_1), len(unprocessed_indices_2)) for list_id in (1, 0): i1, i2 = beam_search(beam_size, (unprocessed_indices_1, unprocessed_indices_2), list_id) debug_print(i1, i2) matched_indices_pairs.append((i1, i2)) if i1 is not None: unprocessed_indices_1.remove(i1) if i2 is not None: unprocessed_indices_2.remove(i2) if not unprocessed_indices_1 or not unprocessed_indices_2: break # Process "left-over" layers for i1 in unprocessed_indices_1: matched_indices_pairs.append((i1, None)) for i2 in unprocessed_indices_2: matched_indices_pairs.append((None, i2)) return matched_indices_pairs def aligned_merge_plans(plan1: EnginePlan, plan2: EnginePlan, matched_indices_pairs: List[Tuple]) -> pd.DataFrame: """Return a dataframe containing merged layers from the two plans, after their layers have been aligned. """ def append_layer(merged: List, layer1: pd.Series, layer2: pd.Series): p1_in, p1_out = get_io_precisions(layer1) p2_in, p2_out = get_io_precisions(layer2) merged.append(( layer1["type"] if layer1 is not None else layer2["type"], layer1["latency.avg_time"] if layer1 is not None else 0, layer2["latency.avg_time"] if layer2 is not None else 0, layer1["latency.avg_time"] / layer2["latency.avg_time"] if layer1 is not None and layer2 is not None else np.NaN, p1_in, p2_in, p1_out, p2_out, layer1["tactic"] if layer1 is not None else "", layer2["tactic"] if layer2 is not None else "", get_io_formats(layer1) if layer1 is not None else "", get_io_formats(layer2) if layer2 is not None else "", layer1["Name"] if layer1 is not None else "", layer2["Name"] if layer2 is not None else "", )) merged = [] for pair in matched_indices_pairs: # A pair of matched indices m1 = pair[0] m2 = pair[1] # Add the pair of matched layers. layer1 = plan1.df.loc[m1] if m1 is not None else None layer2 = plan2.df.loc[m2] if m2 is not None else None append_layer(merged, layer1, layer2) df = pd.DataFrame(merged, columns=("type", 'avg_time (1)', 'avg_time (2)', 'speedup (2)', 'in-p (1)', 'in-p (2)', 'out-p (1)', 'out-p (2)', 'tactic (1)', 'tactic (2)', 'formats (1)', 'formats (2)', plan1.name, plan2.name)) return df def aligned_layers(plan1: EnginePlan, plan2: EnginePlan, matched_indices_pairs: List[Tuple], layer_type: str = None) -> Tuple[pd.DataFrame, pd.DataFrame]: """Return the dataframes of the two plans, after their layers have been aligned. Where the two plans do not align, insert space-holder rows. """ def append_layer(layers_tbl, layer): if layer is None: # Add a "space-holder" layers_tbl.append((len(layers_tbl), "", "", 0)) else: layers_tbl.append((len(layers_tbl), layer["Name"], layer["type"], layer["latency.avg_time"])) # Create a table of layers for each engine. # Empty rows are inserted to an engine's table as space-holders when there's # no matching layer in the other engine. layers_tbl1, layers_tbl2 = [], [] def filer_layer(layer, layer_type): ignore = layer is not None and (layer_type is None or layer["type"] == layer_type) return ignore for pair in matched_indices_pairs: # A pair of matched indices m1, m2 = pair[0], pair[1] # Add the pair of matched layers. layer1 = plan1.df.loc[m1] if m1 is not None else None layer2 = plan2.df.loc[m2] if m2 is not None else None if layer1 is not None and layer2 is not None: if (layer_type is None or layer1["type"] == layer_type): append_layer(layers_tbl1, layer1) append_layer(layers_tbl2, layer2) else: if filer_layer(layer1, layer_type): append_layer(layers_tbl2, None) append_layer(layers_tbl1, layer1) if filer_layer(layer2, layer_type): append_layer(layers_tbl1, None) append_layer(layers_tbl2, layer2) df1 = pd.DataFrame(layers_tbl1, columns=("id", "name", "type", "latency.avg_time")) df2 = pd.DataFrame(layers_tbl2, columns=("id", "name", "type", "latency.avg_time")) return df1, df2 def speedup_range_highlights(col_name, threshold: float): light_yellow = {"r": 255, "g": 245, "b": 157, "a": 0} green = {"r": 0, "g": 255, "b": 0, "a": 1} orange = {"r": 245, "g": 166, "b": 35, "a": 1} range_highlights = { col_name: { "active": True, "equals": { "active": True, "value": 1, "color": light_yellow }, "greaterThan": { "active": True, "value": 1. + threshold, "color": green }, "lessThan": { "active": True, "value": 1. - threshold, "color": orange }, } } return range_highlights def compare_engines_layer_latencies(plan1: EnginePlan, plan2: EnginePlan, threshold: float, exact_matching: bool): """Display a table and a bar diagram comparing the latencies of layers from two plans. """ def render_diagram(choice: str, ignore): if plan1.name == plan2.name: plan1.name += ".0" plan2.name += ".1" matched_indices_pairs = match_layers(plan1, plan2, exact_matching) # Display a table comparison df = aligned_merge_plans(plan1, plan2, matched_indices_pairs) if choice != "All": df = df.query(f"type == \"{choice}\"") print(f"Legend:\n\t1: {plan1.name}\n\t2: {plan2.name}") display_df(df, range_highlights=speedup_range_highlights('speedup (2)', threshold)) # Display a bar diagram comparison layer_type = None if choice == "All" else choice df1, df2 = aligned_layers(plan1, plan2, matched_indices_pairs, layer_type) latency_str = lambda name, df: f"\n\t{name}: {df["latency.avg_time"].sum():.3f} ms" print(f"Latencies:{latency_str(plan1.name, df1)}{latency_str(plan2.name, df2)}") d = {plan1.name: df1, plan2.name: df2} plotly_bar2(title="Layer Latency Comparison", df=d, values_col="latency.avg_time", names_col="id", orientation="v", showlegend=True) types = ["All"] + list(set(plan1.df["type"].tolist() + plan2.df["type"].tolist())) dropdown_choices = {t: t for t in types} InteractiveDiagram(render_diagram, dropdown_choices, "Dataframe") def compare_engines_layer_details( plan1: EnginePlan, plan2: EnginePlan, ): """Compare the details of two layers from two aligned plans. Align plan1 and plan2 and display a drop-down list of the layers of the combined dataframe. This allows easier comparison of individual layers. """ def render_diagram(choice: str, row_id: int): if plan1.name == plan2.name: plan1.name += ".0" plan2.name += ".1" row = df.iloc[row_id] d = { "name": (row[plan1.name], row[plan2.name]), "avg_time": (row['avg_time (1)'], row['avg_time (2)']), "tactic": (row['tactic (1)'], row['tactic (2)']), "in-p": (row['in-p (1)'], row['in-p (2)']), "out-p": (row['out-p (1)'], row['out-p (2)']), "format": (row['formats (1)'], row['formats (2)']), } df2 = pd.DataFrame.from_dict(d, orient="index", columns=( plan1.name, plan2.name, )) speedup = row['avg_time (1)'] / row['avg_time (2)'] tactic = "Same" if row['tactic (1)'] == row['tactic (2)'] else "Different" inp_precision = "Same" if row['in-p (1)'] == row['in-p (2)'] else "Different" out_precision = "Same" if row['out-p (1)'] == row['out-p (2)'] else "Different" formats = "Same" if row['formats (1)'] == row['formats (2)'] else "Different" df2["comparison"] = ('', speedup, tactic, inp_precision, out_precision, formats) df2 = rotate_columns(df2) df2["attribute"] = ("name", "avg_time", "tactic", 'input precision', 'output precision', "formats") df2 = rotate_columns(df2) df2.set_index("attribute") display_df(df2) matched_indices_pairs = match_layers(plan1, plan2, exact_matching=True) df = aligned_merge_plans(plan1, plan2, matched_indices_pairs) dropdown_choices = {f"{t}: {df.iloc[t]["type"]}": t for t in range(len(df))} InteractiveDiagram(render_diagram, dropdown_choices, "Dataframe")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/compare_engines.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains the Activation class which abstracts plan Region views. """ from typing import Dict import numpy as np import pandas as pd # This dictionary compresses JSON's long format description strings. _regionFormatDict = {"Four wide channel vectorized row major Int8 format": "Int8 NC/4HW4", "Four wide channel vectorized row major FP32 format": "FP32 NC/4HW4", "Thirty-two wide channel vectorized row major Int8 format": "Int8 NC/32HW32", "Thirty-two wide channel vectorized row major FP32 format": "FP32 NC/32HW32", "Thirty-two wide channel vectorized row major FP16 format": "FP16 NC/32HW32", "Thirty-two wide channel vectorized row major Int8 format with 3 spatial dimensions": "Int8 NC32DHW", "Thirty-two wide channel vectorized row major FP16 format with 3 spatial dimensions": "FP16 NC32DHW", "Sixteen wide channel vectorized row major FP16 format": "FP16 NC16HW", "Channel major FP16 format where channel % 4 == 0": "FP16 NHWC4", "Channel major FP32 format where channel % 4 == 0": "FP32 NHWC4", "Channel major Int8 format where channel % 4 == 0": "Int8 NHWC4", "Channel major FP16 format where channel % 8 == 0": "FP16 NHWC8", "Channel major FP16 format where channel % 16 == 0": "FP16 NHWC16", "Channel major FP16 format where channel == 4 and column stride % 32 == 0": "FP16 NHWC4", "Channel major INT8 format where channel == 4 and column stride % 32 == 0": "Int8 NHWC4", "Channel major INT8 format where column stride % 32 == 0": "Int8 NHWC1", "Row major INT8 format where column stride % 64 == 0": "Int8 NCHW", "Channel major FP16 format where channel % 8 == 0 with 3 spatial dimensions": "FP16 NDHWC8", "Channel major FP16 format where channel == 1 and column stride % 32 == 0": "FP16 NHWC1", "Row major FP16 format where column stride % 64 == 0": "FP16", "Two wide channel vectorized row major FP16 format": "FP16 NC/2HW2", "Row major linear FP32": "FP32 NCHW", "Row major linear Int32": "INT32 NCHW", "Row major linear FP16 format": "FP16 NCHW", "Row major Int8 format": "Int8 NCHW", "Channel major FP32 format": "FP32 NHWC", "Channel major FP16 format": "FP16 NHWC", "Channel major Int8 format": "Int8 NHWC", "Row major linear BOOL": "Bool", "Unknown format": "Unknown format"} class Activation: """Convenience class wrapping activation regions.""" def __init__(self, raw_dict: Dict): def parse_tensor_info(desc): if "Int8" in desc: precision = "INT8" data_size = 1 elif "FP32" in desc: precision = "FP32" data_size = 4 elif "FP16" in desc: precision = "FP16" data_size = 2 elif "INT32" in desc: precision = "INT32" data_size = 4 elif "Bool" in desc: precision = "BOOL" data_size = 4 elif desc == "Unknown format": precision = "Unknown" data_size = 0 else: raise ValueError(f"Uknown precision {desc}") return precision, data_size self.name = raw_dict["Name"] self.shape = raw_dict["Dimensions"] format = raw_dict["Format/Datatype"].replace(".", '') self.format = _regionFormatDict.get(format, "Unknown format") self.precision, self.data_size = parse_tensor_info(self.format) self.size_bytes = np.prod(self.shape) * self.data_size def tooltip(self): tip = "\\n".join(( str(self.shape), self.format, )) return tip def __repr__(self): return f"{self.name}: {str(self.shape)}x{self.format}" def create_activations(layer: pd.Series): inputs = [Activation(tensor) for tensor in layer.Inputs] outputs = [Activation(tensor) for tensor in layer.Outputs] return inputs, outputs
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/activations.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains pyplot plotting wrappers. """ import math from collections import defaultdict from typing import Dict, List, Tuple import pandas as pd import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots from .misc import stack_dataframes from .notebook import display_df NVDA_GREEN = '#76b900' UNKNOWN_KEY_COLOR = "gray" GRID_COLOR = 'rgba(114, 179, 24, 0.3)' # pallete = px.colors.qualitative.G10 # https://medialab.github.io/iwanthue/ default_pallete = ["#a11350", "#008619", "#4064ec", "#ffb519", "#8f1a8e", "#b2b200", "#64b0ff", "#e46d00", "#02d2ba", "#ef393d", "#f1b0f7", "#7e4401", UNKNOWN_KEY_COLOR] # Set a color for each precision datatype. precision_colormap = defaultdict(lambda: UNKNOWN_KEY_COLOR, { "INT8": NVDA_GREEN, "FP32": "red", "FP16": "orange", "INT32": "lightgray", }) # Set a color for each layer type. layer_colormap = defaultdict( lambda: UNKNOWN_KEY_COLOR, { # https://htmlcolorcodes.com/ "Convolution": "#4682B4", # SteelBlue "Deconvolution": "#7B68EE", # MediumSlateBlue "ConvActPool": "#6495ED", # CornflowerBlue "MatrixMultiply": "#1E90FF", # DodgerBlue "Reformat": "#00FFFF", # Cyan "Shuffle": "#BC8F8F", # RosyBrown "Slice": "#FFA500", # Orange "Scale": "#8FBC8B", # DarkSeaGreen "Quantize": "#6B8E23", # OliveDrab "Pooling": "#3CB371", # MediumSeaGreen "PluginV2": "#C71585", # MediumVioletRed "PointWise": "#9ACD32", # YellowGreen "ElementWise": "#9ACD32", # YellowGreen "Reduce": "#90EE90", # LightGreen "SoftMax": "#DA70D6", # Orchid "Myelin": "#800080", # Purple } ) def _categorical_colormap(df: pd.DataFrame, color_col: str): # Protect against index-out-of-range max_idx = len(default_pallete) - 1 colormap = {category: default_pallete[min(i, max_idx)] for i, category in enumerate(set(df[color_col]))} return colormap def _create_categorical_marker(df: pd.DataFrame, color_col: str, colormap: Dict = None): if not colormap: colormap = _categorical_colormap(df, color_col) # Make colormap robust to unknown keys colormap = defaultdict(lambda: UNKNOWN_KEY_COLOR, colormap) color_list = [colormap[key] for key in df[color_col]] marker = dict(color=color_list) return marker def trex_base_layout(fig, gridcolor=None): "White background with colored grid" gridcolor = gridcolor or GRID_COLOR fig.update_layout({ "xaxis": { "gridcolor": gridcolor }, "yaxis": { "gridcolor": gridcolor }, "plot_bgcolor": 'rgba(0, 0, 0, 0)', "paper_bgcolor": 'rgba(0, 0, 0, 0)', }) def create_layout(title: str, size: Tuple, x_title: str, y_title: str, orientation: str, show_axis_ticks: Tuple[bool] = (True, True)): y_grid = None if orientation == "h" else GRID_COLOR x_grid = None if orientation == "v" else GRID_COLOR if orientation == "h": x_title, y_title = y_title, x_title top_right = {"yanchor": "top", "y": 0.99, "xanchor": "right", "x": 0.99} layout = go.Layout( title={ "text": title, "y": 0.9, "x": 0.5, "xanchor": "center", "yanchor": "bottom" }, width=size[0], height=size[1], xaxis={ "visible": True, "showticklabels": show_axis_ticks[0], "title": x_title, "gridcolor": x_grid, }, yaxis={ "visible": True, "showticklabels": show_axis_ticks[1], "title": y_title, "gridcolor": y_grid, "tickformat": "%{y:$.2f}" }, plot_bgcolor='rgba(0,0,0,0)', legend=top_right, ) return layout def plotly_bar2( df: pd.DataFrame, title: str, values_col: str, names_col: str, orientation: str = "v", color: str = None, size: Tuple = (None, None), use_slider: bool = False, colormap: Dict = None, show_axis_ticks: Tuple = (False, True), showlegend: bool = False, xaxis_title: str = None, yaxis_title: str = None, ): def categorical_color(df, color) -> bool: if df[color].dtype in [float, int]: return False return True def add_bar(df, name, color, colormap, showlegend): if orientation == "v": x, y = (names_col, values_col) hover_txt = f"{x}: " + "%{x}" + f"<br>{y}: " + "%{y:.4f}" else: x, y = (values_col, names_col) hover_txt = f"{x}: " + "%{x:.4f}" + f"<br>{y}: " + "%{y}" is_categorical = False colorbar = None if color is not None: assert isinstance(color, str) if not categorical_color(df, color): colorbar = dict(title=color) color = df[color] else: is_categorical = True if not is_categorical: marker = dict(color=color, colorbar=colorbar) else: marker = _create_categorical_marker(df, color, colormap) texttemplate = "%{value:.4f}" if df[values_col].dtype == float else '%{value}' bar = go.Bar(x=df[x], y=df[y], orientation=orientation, marker=marker, text=df[values_col], texttemplate=texttemplate, hovertemplate=hover_txt, name=name, showlegend=showlegend) return bar layout = create_layout( title, size, x_title=xaxis_title or names_col, y_title=yaxis_title or values_col, orientation=orientation, show_axis_ticks=show_axis_ticks, ) fig = go.Figure(layout=layout) if not isinstance(df, Dict): df_dict = {None: df} else: df_dict = df for name, df in df_dict.items(): bar = add_bar(df, name, color, colormap, showlegend=showlegend) fig.add_traces(bar) if use_slider: fig.update_xaxes(rangeslider_visible=True) fig.show() def rotate_columns(df: pd.DataFrame): cols = df.columns.tolist() cols = cols[-1:] + cols[:-1] df = df[cols] return df def stacked_tabular_df( bar_names: List[str], df_list: List[pd.DataFrame], names_col: str, values_col: str, empty_symbol: object = 0, ): stacked = stack_dataframes(df_list, names_col, values_col, empty_symbol) df = pd.DataFrame.from_dict(stacked, orient="index", columns=bar_names) df[values_col] = stacked.keys() df = rotate_columns(df) return df def stacked_tabular(*args, **kwargs): df = stacked_tabular_df(*args, **kwargs) display_df(df) def stacked_bars( title: str, bar_names: List[str], df_list: List[pd.DataFrame], names_col: str, values_col: str, empty_symbol: object = 0, colormap: Dict = None, display_tbl: bool = True, fig: go.Figure = None, xaxis_title: str = None, yaxis_title: str = None, ): """Stack a list of dataframes. Each df in df_list has a `names` column and a 'values` column. This function returns a dictionary indexed by each name in the set of all names from all dfs in df_list. For each `name` key the dictionary value is a list of all values from all dfs. If a df[name] does not exist, we create an `empty_symbol` entry for it. """ stacked = stack_dataframes(df_list, names_col, values_col, empty_symbol) if colormap: bars = [go.Bar(name=k, x=bar_names, y=v, marker_color=colormap[k], text=v) for k, v in stacked.items()] else: bars = [go.Bar(name=k, x=bar_names, y=v, text=v) for k, v in stacked.items()] display_bars = True if fig is None: fig = go.Figure(data=bars) trex_base_layout(fig) else: fig.add_traces(bars) display_bars = False fig.update_layout( title=title, title_x=0.5, font_size=15, ) fig.update_layout(barmode="stack") fig.update_layout(showlegend=colormap is not None) fig.update_traces(texttemplate='%{text:.4f}') fig.update_layout(uniformtext_minsize=8, uniformtext_mode="hide") fig.update_layout({"yaxis_title": yaxis_title or values_col, "xaxis_title": xaxis_title}) if display_bars: fig.show() if display_tbl: stacked_tabular(bar_names, df_list, names_col, values_col, empty_symbol) return fig def plotly_hist(df: pd.DataFrame, title: str, values_col: str, xaxis_title: str, color: str, colormap=None): """Draw a histogram diagram.""" fig = px.histogram(df, x=values_col, title=title, nbins=len(df), histfunc="count", color=color, template="simple_white", color_discrete_map=colormap) fig.update_layout(xaxis={"title": xaxis_title}, bargap=0.05) fig.show() def plotly_pie(df: pd.DataFrame, title: str, values: str, names: str, colormap: Dict[str, str] = None): """Draw a pie diagram.""" fig = go.Figure(data=[go.Pie(labels=df[names], values=df[values], hole=.0)]) pie_pallette = default_pallete if colormap: pie_pallette = [colormap[key] for key in df[names]] marker = dict(colors=pie_pallette, line=dict(color=NVDA_GREEN, width=1)) fig.update_traces(marker=marker) fig.update_traces( hoverinfo='label+percent', textinfo="value", textfont_size=20, ) fig.update_layout( title=title, title_x=0.5, font_size=20, ) fig.show() def plotly_pie2(title: str, charts: list, max_cols: int = 3, colormap: Dict[str, str] = None): """Draw a pie diagram.""" main_title = title n_charts = len(charts) n_cols = min(max_cols, n_charts) n_rows = math.ceil(n_charts / n_cols) specs = [[{"type": "domain"}] * n_cols] * n_rows subtitles = [chart[1] for chart in charts] fig = make_subplots(rows=n_rows, cols=n_cols, specs=specs, subplot_titles=subtitles) pie_pallette = None for i, chart in enumerate(charts): df, title, values, names = chart row, col = i // n_cols, i % n_cols texttemplate = "%{value:.1f}" if df[values].dtype == float else '%{value}' if colormap is not None: pie_pallette = [colormap[key] for key in df[names]] marker = dict(colors=pie_pallette, line=dict(color=NVDA_GREEN, width=1)) fig.add_trace(go.Pie( labels=df[names], values=df[values], name=title, marker=marker, texttemplate=texttemplate, ), row + 1, col + 1) if pie_pallette is None: pie_pallette = default_pallete fig.update_traces( hoverinfo='label+percent', textinfo="value", textfont_size=20, hole=0.4, textposition="inside", ) fig.update_layout( title=main_title, title_x=0.5, font_size=20, ) fig.show()
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/plotting.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from trex.activations import * from trex.compare_engines import * from trex.df_preprocessing import * from trex.engine_plan import * from trex.graphing import * from trex.interactive import * from trex.lint import * from trex.misc import * from trex.notebook import * # The Jupyter notebook graphing and plotting are # not required in a terminal environment. from trex.plotting import * from trex.report_card import * __version__ = "0.1.2"
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/__init__.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # from typing import Dict, List, Tuple from .parser import * def __disambiguate_layer_names(raw_layers: List) -> List: """If a layer name appears twice we need to disabmiguate it""" names_cnt = {} for raw_layer in raw_layers: name = raw_layer["Name"] if name in names_cnt: names_cnt[name] += 1 name += "_" + str(names_cnt[name]) raw_layer["Name"] = name else: names_cnt[name] = 1 return raw_layers def __convert_deconv(raw_layers: List) -> List: for raw_layer in raw_layers: try: is_deconv = (raw_layer["ParameterType"] == "Convolution" and raw_layer["LayerType"] == "CaskDeconvolutionV2") if is_deconv: raw_layer["ParameterType"] = "Deconvolution" except KeyError: pass return raw_layers def import_graph_file(graph_file: str): raw_layers, bindings = read_graph_file(graph_file) raw_layers = __convert_deconv(raw_layers) raw_layers = __disambiguate_layer_names(raw_layers) return raw_layers, bindings
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/raw_preprocessing.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains code to generate graph diagrams for an engine-plan. """ import os import re #from ast import Call import warnings from typing import Callable, List, NamedTuple from graphviz import Digraph from .activations import Activation from .engine_plan import EnginePlan from .layer import Layer from .plotting import layer_colormap, precision_colormap class Region(NamedTuple): id: int tensor: Activation is_user: bool should_display: bool class Edge(NamedTuple): src: str dst: str tensor: Activation region_gen: int = None class RegionGenerations: """A memory region may have several generations, where each generation represents a consumable state of the region. """ def __init__(self, plan): """ A P event represents some layer writing to (producing part of) a memory region. A C event represents some layer reading from (consuming part of) a memory region. A region_story is a map from region name to the list of C/P events on that region. """ story = {} for layer in plan.layers: for inp in layer.inputs: story.setdefault(inp.name, []).append(("C", layer.name)) for outp in layer.outputs: story.setdefault(outp.name, []).append(("P", layer.name)) # Create region generations. # Each time we switch between C events and P events we create a new # Region generation. regions_gens = {} for region, region_evts in story.items(): # A List of region generations. # Each generation is a list of C/P events. generations = [list()] current_gen = 0 last = "P" for evt in region_evts: if evt[0] != last: last = evt[0] if evt[0] == "P": current_gen += 1 generations.append(list()) generations[current_gen].append(evt) regions_gens[region] = generations self.regions_gens = regions_gens def lookup_region_gen(self, layer_name: str, region_name: str): """Lookup the generation of a Region, given a layer name. If a layer produces or consumes the Region, we return the corresponding Region generation. """ try: region_gens = self.regions_gens[region_name] except KeyError: # A KeyError can happen if we have a disconneted graph. return -1 for gen_id, gen in enumerate(region_gens): for evt in gen: if evt[1] == layer_name: return gen_id # Assume for now that this is OK - it's probably a Constant # layer that produced this region. return 0 def nb_generations(self, region_name: str): region_gens = self.regions_gens[region_name] return len(region_gens) def debug_generation(self): for r, generations in self.regions_gens.items(): for g in generations: print(r, g) def create_id(self, region_id: int, region_generation: int): return region_id + 100000 * region_generation def render_dot(dot_graph: Digraph, engine_name: str, output_format: str): """Render dot graph to an external file using the specified format.""" dot_graph.format = output_format output_fname = os.path.abspath(f"{engine_name}." + output_format) dot_graph.render(outfile=output_fname, view=False, overwrite_source=False) print(f"Created file://{output_fname}") return output_fname def node_label_simple( layer: Layer, latency: float, display_layer_name: bool = True, expand_layer_details: bool = False, ) -> str: return f"{layer.name}\\n{layer.type}" def node_label_keras( layer: Layer, latency: float, display_layer_name: bool = True, expand_layer_details: bool = False, ) -> str: """Keras-style node label formatting.""" def add_io(tensors: List): io_desc_str = "" for t in tensors: io_desc_str += str(t.shape) return io_desc_str label = f"{layer.name}\\n" if display_layer_name else "" label += f"{layer.type}" label += "|{input:|output:}|{{" label += add_io(layer.inputs) label += "}|" label += add_io(layer.outputs) label += "}" return label def node_label_tbl( layer: Layer, latency: float, display_layer_name: bool = True, expand_layer_details: bool = False, ) -> str: def clean_layer_name(layer_name: str): layer_name = layer_name.replace("||", "\|\|") layer_name = layer_name.replace("{", "") layer_name = layer_name.replace("}", "") return layer_name def html_tbl(rows: List[str]): def html_tbl_row(row_content, bold: bool, color: str = None): row_content = row_content if not bold else f"<b>{row_content}</b>" if color: row = f"<TR><TD BGCOLOR=\"{color}\">{row_content}</TD></TR>" else: row = f"<TR><TD>{row_content}</TD></TR>" return row header = """< <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4" color="transparent">"""" footer = "</TABLE>>" tbl = header for i, row in enumerate(rows): tbl += html_tbl_row(row[0], i == 0, row[1] if len(row) > 1 else None) tbl += footer return tbl def handle_pwgen(layer: Layer, rows: List[str]): if layer.type != "PointWise": return try: subtype = layer.raw_dict["ParameterSubType"] if subtype == "PointWiseExpression": ops = layer.raw_dict["Operations"] for op in ops: prefix = "const auto" op_str = op[len(prefix):] HoneyDew = "#F0FFF0" rows.append((op_str, HoneyDew)) except KeyError: pass def handle_conv_deconv(layer: Layer, rows: List[str]): if layer.type not in ("Convolution", "Deconvolution"): return try: if len(layer.inputs) == 2: rows.append(("Incident Add", "lightblue")) act = layer.raw_dict["Activation"] if act is not None and act != "NONE": rows.append((act, "lightblue")) except KeyError: pass layer_name = clean_layer_name(layer.name) layer_type = f"{layer.type} ({latency} ms)" rows = [(layer_type, )] if display_layer_name: parts = layer_name.split("+") for p in parts: rows.append((p, )) if expand_layer_details: handle_pwgen(layer, rows) handle_conv_deconv(layer, rows) tbl = html_tbl(rows) return tbl def parse_operation(op): c = re.compile("\((.+\))") args = c.findall(op) args[0].split(",") args = args[0].split(",") c = re.compile("pwgen::.+\(") w = c.findall(op) opname = w[0][:-1] output = op.split(" ")[2] print(f"{opname}: {args} -> {output}") return opname, args, output class PlanGraph(object): """This is a base-class for representing TensorRT plans as renderable graphs""" def __init__(self, plan: EnginePlan, display_regions: bool = False): self.plan = plan self.display_regions = display_regions self.regions_dict = {} self.regions_generations = RegionGenerations(plan) self.edges_list = [] self.__create_graph(plan) def __create_graph(self, plan: EnginePlan): region_id = len(plan.all_layers) for layer_id, layer in enumerate(plan.all_layers): for inp in layer.inputs: region_id = self.handle_region(layer_id, layer, inp, region_id, is_input=True) for outp in layer.outputs: region_id = self.handle_region(layer_id, layer, outp, region_id, is_input=False) for edge in self.edges_list: self.add_edge(edge.src, edge.dst, edge.tensor, edge.region_gen) for layer_id, layer in enumerate(plan.all_layers): try: latency = plan.df[plan.df["Name"] == layer.name]["latency.avg_time"].iloc[0] except (KeyError, IndexError): # Constants layer latency = 0 self.add_layer_node(layer_id, layer, latency, node_labeler=node_label_tbl) for generations in self.regions_dict.values(): for r in generations: if r.should_display: self.add_region_node(r.id, r.tensor, r.is_user) self.check_consistency() def check_consistency(self): # Verify that every output is either an output binding, or an input # of another layer. for region_name, region in self.regions_dict.items(): nb_prods = self._nb_producers(self.plan.all_layers, region_name) nb_cons = self._nb_consumers(self.plan.all_layers, region_name) is_user = region_name in self.plan.bindings # or nb_cons==0 or nb_prod==0 if not is_user and nb_cons == 0: warnings.warn(f"Region {region_name} is neither a binding nor a layer input.") if not is_user and nb_prods == 0: warnings.warn(f"Region {region_name} is neither a binding nor a layer output.") def find_producers(self, layers, region_name): producers = [] for i, l in enumerate(self.plan.all_layers): for o in l.outputs: if o.name == region_name: producers.append((i, l.name)) return producers def _nb_producers(self, layers, inp_name): return len(self.find_producers(layers, inp_name)) def _nb_consumers(self, layers, region_name): consumers = [] for id, l in enumerate(self.plan.all_layers): for i in l.inputs: if i.name == region_name: consumers.append((i, region_name)) return len(consumers) def should_display_region(self, region_name: str, display_regions: bool) -> bool: nb_gens = self.regions_generations.nb_generations(region_name) nb_prod = self._nb_producers(self.plan.all_layers, region_name) nb_cons = self._nb_consumers(self.plan.all_layers, region_name) is_user = region_name in self.plan.bindings or nb_cons == 0 or nb_prod == 0 add = is_user or display_regions or nb_gens > 1 or nb_prod > 1 return add def new_region(self, tensor: Activation, region_id: int, is_user: bool, should_display: bool) -> int: self.regions_dict[tensor.name] = [Region(region_id, tensor, is_user, should_display)] region_id += 1 return region_id def handle_region(self, layer_id: int, layer: Layer, tensor: Activation, region_id: int, is_input: bool) -> int: region_gen = self.regions_generations.lookup_region_gen(layer.name, tensor.name) if region_gen == -1: should_display = True is_new_region = True else: should_display = self.should_display_region(tensor.name, self.display_regions) is_new_region = tensor.name not in self.regions_dict is_user = tensor.name in self.plan.bindings is_new_generation = (not is_new_region and (region_gen + 1) > len(self.regions_dict[tensor.name])) if is_new_region: region_id = self.new_region(tensor, region_id, is_user, should_display) elif is_new_generation: self.add_generation(tensor, region_gen, is_user, region_id) region = self.regions_dict[tensor.name][region_gen] if should_display: _from = str(region.id) if is_input else str(layer_id) _to = str(layer_id) if is_input else str(region.id) self.edges_list.append(Edge(_from, _to, tensor)) elif is_input: producers = self.find_producers(self.plan.all_layers, tensor.name) for producer in producers: self.edges_list.append(Edge(str(producer[0]), str(layer_id), tensor)) return region_id def add_region_node(self, id: int, tensor: Activation, is_user: bool): pass def add_layer_node(self, node_id: int, layer: Layer, latency: float, node_labeler: Callable): pass def add_edge(self, src, end, tensor, region_gen): pass def add_generation(self, tensor: Activation, region_gen: int, is_user: bool, region_id): new_region_id = self.regions_generations.create_id(region_id, region_gen + 1) self.regions_dict[tensor.name].append(Region(new_region_id, tensor, is_user, True)) # Add an edge between the previous and current region generations previous_gen_region = self.regions_dict[tensor.name][region_gen - 1] self.edges_list.append(Edge(str(previous_gen_region.id), str(new_region_id), tensor, region_gen=region_gen)) def precision_formatter(layer: Layer): """Format Dot nodes by layer precision""" formatting = {"style": "filled", "tooltip": layer.tooltip(), "fillcolor": precision_colormap[layer.precision]} return formatting def layer_type_formatter(layer: Layer): """Format Dot nodes by layer type""" def handle_reformat(layer: Layer): if layer.type != "Reformat": return None try: origin = layer.raw_dict["Origin"] if origin == "QDQ": return layer_colormap["Quantize"] except KeyError: return None try: layer_color = layer_colormap[layer.type] layer_color = handle_reformat(layer) or layer_color except KeyError: layer_color = "#E5E7E9" formatting = { "style": "filled", "tooltip": layer.tooltip(), "fillcolor": layer_color, "color": "white", } return formatting def tensor_precision_formatter(tensor: Activation): """Format Dot edges by tensor precision""" formatting = {"color": precision_colormap[tensor.precision], "tooltip": str(tensor.shape)} return formatting def region_precision_formatter(tensor: Activation): """Format Dot edges by region precision""" formatting = {"style": "filled" if tensor.is_user else "dashed", "tooltip": str(tensor.shape), "penwidth": "3", "color": precision_colormap[tensor.precision]} return formatting class DotGraph(PlanGraph): """This class converts TensorRT plans to Graphviz DOT graphs""" def __init__( self, plan: EnginePlan, node_formatter: Callable, region_formatter: Callable = region_precision_formatter, display_layer_names: bool = True, display_regions: bool = False, expand_layer_details: bool = False, ): self.dot = Digraph() self.node_formatter = node_formatter self.region_formatter = region_formatter self.expand_layer_details = expand_layer_details super().__init__(plan, display_regions) def add_region_node(self, id: int, tensor: Activation, is_user: bool): tensor.is_user = is_user formatter = self.region_formatter(tensor) self.dot.node(str(id), f"{tensor.name}\n{tensor.tooltip()}", shape="rectangle", fillcolor="gray" if is_user else None, fontname="Helvetica", **formatter) def add_layer_node(self, node_id: int, layer: Layer, latency: float, node_labeler: Callable): formatting = self.node_formatter(layer) self.dot.node(str(node_id), node_labeler(layer, latency, expand_layer_details=self.expand_layer_details), shape="Mrecord", fontname="Helvetica", **formatting) def add_edge(self, src, end, tensor, region_gen): def generation_color(gen: int, line_color: str) -> str: edge_color = "" for i in range(gen): edge_color += f"{line_color}:white:" edge_color += f"{line_color}" return edge_color edge_color = precision_colormap[tensor.precision] if region_gen: edge_color = generation_color(region_gen, edge_color) desc = tensor.tooltip() else: desc = tensor.tooltip() self.dot.edge(src, end, desc, color=edge_color) def to_dot(plan: EnginePlan, node_formatter: Callable, region_formatter: Callable = region_precision_formatter, display_layer_names: bool = True, display_regions: bool = False, display_constants: bool = False, expand_layer_details: bool = False) -> Digraph: """Convert plan-graph to dot format""" g = DotGraph(plan, node_formatter, region_formatter, display_layer_names, display_regions, expand_layer_details) return g.dot import onnx def make_onnx_tensor(tensor): def get_type(desc): desc = desc.lower() if "int8" in desc: return onnx.TensorProto.INT8 elif "fp32" in desc: return onnx.TensorProto.FLOAT elif "fp16" in desc: return onnx.TensorProto.FLOAT16 elif "int32" in desc: return onnx.TensorProto.INT32 else: raise ValueError(f"Uknown precision {desc}") t = onnx.helper.make_tensor_value_info(tensor.name, get_type(tensor.format), tensor.shape) return t class OnnxGraph(PlanGraph): def __init__( self, plan: EnginePlan, display_layer_names: bool = True, display_regions: bool = False, ): self.onnx_nodes = [] self.graph_inputs, self.graph_outputs = [], [] self.regions_inputs = dict() self.regions_outputs = dict() self.plan = plan for layer in plan.layers: for inp in layer.inputs: if inp.name in self.plan.bindings: self.graph_inputs.append(make_onnx_tensor(inp)) for outp in layer.outputs: if outp.name in self.plan.bindings: self.graph_outputs.append(make_onnx_tensor(outp)) super().__init__(plan, display_regions) graph_def = onnx.helper.make_graph(self.onnx_nodes, "test-model", self.graph_inputs, self.graph_outputs) self.model_def = onnx.helper.make_model(graph_def, producer_name="engine2onnx") def add_region_node(self, id: int, tensor: Activation, is_user: bool): if is_user: # In the ONNX programming model we create # bindings when we create the graph. return try: inputs = self.regions_inputs[tensor.name] except: print(f"Did not find input {id}") inputs = None try: outputs = self.regions_outputs[tensor.name] except: print(f"Did not find output {id}") outputs = None name = str(id) node_def = onnx.helper.make_node("Region", inputs, outputs, name) self.onnx_nodes.append(node_def) def add_layer_node(self, node_id: int, layer: Layer, node_labeler: Callable): def get_type(layer): op_type = layer.type # Convert Op Type to onnx.ai namepsace because # Netron assigns these nodes specific colors. if op_type == "Convolution": op_type = "Conv" if op_type == "Pooling": if layer.raw_dict["PoolingType"] == "AVERAGE": op_type = "AveragePool" if layer.raw_dict["PoolingType"] == "Max": op_type = "MaxPool" return op_type def add_attributes(layer, node_def): for key, value in sorted(layer.items()): if key not in ["InputRegions", "OutputRegions", "Inputs", "Outputs", "Name", "name", "ParameterType", "LayerName"]: node_def.attribute.extend([onnx.helper.make_attribute(key, value)]) op_type = get_type(layer) name = layer.name print(f"adding node {node_id} - {layer.name}") # Find layer id inputs, outputs = [], [] for edge in self.edges_list: if edge.src == str(node_id): outputs.append(edge.tensor.name) if edge.dst == str(node_id): inputs.append(edge.tensor.name) # Find inputs to layer id, outputs node_def = onnx.helper.make_node(op_type, inputs, outputs, name) add_attributes(layer.raw_dict, node_def) self.onnx_nodes.append(node_def) def add_edge(self, src, end, tensor, region_gen): if True: edge = f"{src}_to_{end}" edge = tensor.name try: self.regions_inputs[tensor.name].append(edge) except KeyError: self.regions_inputs[tensor.name] = [ edge, ] try: self.regions_outputs[tensor.name].append(end) except KeyError: self.regions_outputs[tensor.name] = [ end, ]
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/graphing.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ JSON file parsing """ import json from typing import BinaryIO, Dict, List, Tuple def read_json(json_file: str) -> BinaryIO: try: data = json.load(json_file) except: raise ValueError(f"Could not load JSON file {json_file}") return data def read_graph_file(graph_file: str) -> List: err_msg = f"File {graph_file} does not conform to the expected JSON format." with open(graph_file) as json_file: graph = read_json(json_file) if not isinstance(graph, dict): raise ValueError(err_msg) layers = graph["Layers"] try: bindings = graph["Bindings"] except KeyError: # Older TRT didn't include bindings bindings = list() if not isinstance(layers, list): raise ValueError(err_msg) if not isinstance(layers[0], dict): details_msg = "\nMake sure to enable detailed ProfilingVerbosity." details_msg += "\nSee https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#engine-inspector" raise ValueError(err_msg + details_msg) return layers, bindings def read_profiling_file(profiling_file: str) -> List[Dict[str, any]]: perf = None with open(profiling_file) as json_file: perf = read_json(json_file) # Clean data (remove records with short size) perf = [rec for rec in perf if len(rec) in (4, 5)] return perf def read_metadata_file(metadata_file: str, device: int = 0): with open(metadata_file) as json_file: metadata = read_json(json_file) return metadata[device] def read_timing_file(timing_json_file: str): with open(timing_json_file) as json_file: timing_recs = read_json(json_file) latencies_list = [rec["latencyMs"] for rec in timing_recs] return latencies_list def read_perf_metadata_file(metadata_file: str, section: str): with open(metadata_file) as json_file: metadata = read_json(json_file) return metadata[section] def get_device_properties(metadata_file: str) -> Dict: try: return read_perf_metadata_file(metadata_file, "device_information") except (FileNotFoundError, TypeError): return {} def get_performance_summary(metadata_file: str) -> Dict: try: return read_perf_metadata_file(metadata_file, "performance_summary") except (FileNotFoundError, TypeError): return {} def get_builder_config(metadata_file: str) -> Dict: try: d = read_perf_metadata_file(metadata_file, "model_options") d.update(read_perf_metadata_file(metadata_file, "build_options")) return d except (FileNotFoundError, TypeError): return {} def import_graph_file(graph_file: str): def disambiguate_layer_names(raw_layers: List) -> List: """If a layer name appears twice we need to disabmiguate it""" names_cnt = {} for raw_layer in raw_layers: name = raw_layer["Name"] if name in names_cnt: names_cnt[name] += 1 name += "_" + str(names_cnt[name]) raw_layer["Name"] = name else: names_cnt[name] = 1 return raw_layers def convert_deconv(raw_layers: List) -> List: """Distinguish between convolution and convolution-transpose (deconvolution)""" for raw_layer in raw_layers: try: is_deconv = (raw_layer["ParameterType"] == "Convolution" and raw_layer["LayerType"] == "CaskDeconvolutionV2") if is_deconv: raw_layer["ParameterType"] = "Deconvolution" except KeyError: pass return raw_layers raw_layers, bindings = read_graph_file(graph_file) raw_layers = convert_deconv(raw_layers) raw_layers = disambiguate_layer_names(raw_layers) return raw_layers, bindings
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/parser.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains configurable interactive widget wrappers. """ from typing import List import IPython from IPython.core.display import display from ipywidgets import widgets class InteractiveDiagram: """A dropdown widget wrapper""" def __init__(self, diagram_renderer, choices, description): def get_default_choice_key(): return list(self.choices.keys())[0] def get_default_choice_value(): val = list(self.choices.values())[0] if not isinstance(val, list) and not isinstance(val, tuple): return (val, ) return val self.diagram_renderer = diagram_renderer self.choices = choices display(get_default_choice_key()) self.choice_widget = widgets.Dropdown( options=self.choices.keys(), value=get_default_choice_key(), description=description, disabled=False, ) dropdown_state_eventhandler = lambda change: self.dropdown_state_eventhandler(change) self.choice_widget.observe(dropdown_state_eventhandler, names="value") self._render(get_default_choice_key(), get_default_choice_value()) def _render(self, choice, values): IPython.display.clear_output(wait=True) display(self.choice_widget) self.diagram_renderer(choice, *values) def dropdown_state_eventhandler(self, change): state_choice = change.new values = self.choices[state_choice] if not isinstance(values, list) and not isinstance(values, tuple): values = (values, ) self._render(state_choice, values) class InteractiveDiagram_2: """A dropdown widget wrapper""" def __init__(self, choices: List, description: str): def get_default_choice(): return list(self.choices.keys())[0] def get_default_renderer(): val = list(self.choices.values())[0] return val self.choices = choices display(get_default_choice()) self.choice_widget = widgets.Dropdown( options=self.choices.keys(), value=get_default_choice(), description=description, disabled=False, ) dropdown_state_eventhandler = lambda change: self.dropdown_state_eventhandler(change) self.choice_widget.observe(dropdown_state_eventhandler, names="value") self._render(get_default_choice(), get_default_renderer()) def _render(self, title, renderer): IPython.display.clear_output(wait=True) display(self.choice_widget) renderer(title=title) def dropdown_state_eventhandler(self, change): state_choice = change.new renderer = self.choices[state_choice] self._render(state_choice, renderer)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/interactive.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ TensorRT Engine Exploration API - Layer """ from typing import Dict, List import numpy as np from .activations import * class Layer: def __init__(self, raw_dict: Dict): self.raw_dict = raw_dict self.name = raw_dict["Name"] try: self.type = raw_dict["ParameterType"] except: self.type = raw_dict["LayerType"] self.subtype = raw_dict["LayerType"] self.inputs = [Activation(tensor) for tensor in raw_dict["Inputs"]] self.outputs = [Activation(tensor) for tensor in raw_dict["Outputs"]] self.outputs_size_bytes = np.sum([i.size_bytes for i in self.outputs]) if self.inputs: self.precision = self.inputs[0].precision self.inputs_size_bytes = np.sum([i.size_bytes for i in self.inputs]) else: self.inputs_size_bytes = 0 self.precision = None self.total_io_size_bytes = self.inputs_size_bytes + self.outputs_size_bytes self._parse_weights() self.total_footprint_bytes = self.total_io_size_bytes + self.weights_size def _parse_constant(const): cnt = const["Count"] data_type = const["Type"] try: data_size = dict({"Int8": 1, "Half": 2, "Float": 4, "Int32": 4})[data_type] except KeyError: # Backward compatbility. data_size = dict({"Int8": 1, "FP16": 2, "FP32": 4, "Int32": 4})[data_type] return cnt, data_type, cnt * data_size def _parse_weights(self): try: self.weights_cnt, self.weights_type, self.weights_size = \ Layer._parse_constant(self.raw_dict["Weights"]) except KeyError: self.weights_cnt = 0 self.weights_type = None self.weights_size = 0 try: self.bias_cnt, self.bias_type, self.bias_size = \ Layer._parse_constant(self.raw_dict["Bias"]) except KeyError: self.bias_cnt = 0 self.bias_type = None self.bias_size = 0 def tooltip(self): tip = "" for key, value in sorted(self.raw_dict.items()): if key not in ["InputRegions", "OutputRegions", "Inputs", "Outputs", "ParameterType", "LayerName"]: tip += f"{key}:{value}\\n" return tip def __repr__(self): rep = f"Layer({self.name})" return rep def fold_no_ops(layers: List, bindings: List) -> List: """Remove layers of type No-Op""" def consumers_producers_dict(layers) -> Dict[Activation, List[Layer]]: """Return a dictionary of consumer-layers per activation tensor""" consumers, producers = {}, {} for layer in layers: for loc, input in enumerate(layer.inputs): try: consumers[input.name].append((layer.name, loc)) except: consumers[input.name] = [(layer.name, loc)] for loc, output in enumerate(layer.outputs): try: producers[output.name].append((layer.name, loc)) except: producers[output.name] = [(layer.name, loc)] return consumers, producers def move_input(src: Layer, dst: Layer, loc: int = 0): # Can safely assume src input port #0 because NoOp has only a single input. dst.inputs[loc] = src.inputs[0] def move_output(src: Layer, dst: Layer, loc: int = 0): # Can safely assume src output port #0 because NoOp has only a single output. dst.outputs[loc] = src.outputs[0] def fold(no_op: Layer): try: successors = activation_consumers[no_op.outputs[0].name] for successor in successors: successor_name, successor_in_port = successor move_input(src=no_op, dst=ret[successor_name], loc=successor_in_port) except KeyError: # A leaf NoOp layer: it's output is a binding so we need to move the # NoOp output to the output of the previous layer. if no_op.outputs[0].name in bindings: predecessors = activation_producers[no_op.inputs[0].name] for predecessor in predecessors: predecessor_name, predecessor_out_port = predecessor move_output(src=no_op, dst=ret[predecessor_name], loc=predecessor_out_port) pass ret = {layer.name: layer for layer in layers} activation_consumers, activation_producers = consumers_producers_dict(layers) for layer in layers: if layer.type == "NoOp": fold(layer) # Remove the No-Op layers from the final list. ret = [layer for layer in ret.values() if layer.type != "NoOp"] return ret
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/layer.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains raw JSON dataframes preprocessing functions. """ import pandas as pd from .activations import * layer_attributes = { "Convolution": { "subtype": "subtype", "Groups": "attr.groups", "OutMaps": "attr.out_maps", "Stride": "attr.stride", "Kernel": "attr.kernel", "HasBias": "attr.has_bias", "Activation": "attr.activation", "HasReLU": "attr.has_relu", "PaddingMode": None, # "attr.padding_mode", "PrePadding": None, # "attr.pre_padding", "PostPadding": None, # "attr.post_padding", "Dilation": "attr.dilation", "AllowSparse": None, "Weights": "Weights", "Bias": None, "Dimensions": None, "ConvolutionTacticIndex": None, "Operations": "attr.operations", "NbOperations": "attr.n_operations", }, "PointWiseV2": { "Operations": "attr.operations", "NbOperations": "attr.n_operations", "NbInputArgs": "attr.n_input_args", "InputArgs": None, "NbOutputVars": None, "OutputVars": None, "NbLiterals": None, "Literals": None, "NbParams": None, "Params": None, }, "PointWise": { "Instructions": "attr.operations", "NbInstructions": "attr.n_operations", "NbInputs": "attr.n_input_args", "InputArgs": None, "NbOutputVars": None, "OutputVars": None, "NbLiterals": None, "Literals": None, "NbParams": None, "Params": None, }, "Reformat": { "Origin": "attr.origin", }, "Pooling": { "PoolingType": "attr.pooling_type", "WindowSize": "attr.window_size", "AverageCountExcludesPadding": None, "PaddingMode": "attr.padding_mode", "Stride": "attr.stride", "PrePadding": None, "PostPadding": None, "BlendFactor": None, }, "Scale": { "Mode": "attr.mode", "Shift": "attr.shift", "Scale": "attr.scale", "Power": "attr.power", "Activation": "attr.activation", "ChannelAxis": "attr.ch_axis", }, "Shuffle": { "FirstTranspose": "attr.first_transpose", "SecondTranspose": "attr.second_transpose", "Reshape": "attr.reshape", "ZeroIsPlaceholder": None, "ParameterSubType": None, }, "Resize": { "ResizeMode": "attr.mode", "ResizeScales": "attr.scales", "NNRounding": "attr.scale", "Start": None, "CoordTransform": None, "ResizeSelector": None, }, "Slice": { "Start": "attr.start", "Stride": "attr.stride", "Size": "attr.size", "Mode": "attr.mode", "negativeInfinityPadding": None, }, "Common": { "ParameterType": None, "weights": None, "dimensions": None, "TacticValue": None, }, } def __fix_type(df: pd.DataFrame): df.rename(columns={"LayerType": "subtype"}, inplace=True) try: df["type"] = df.ParameterType.fillna(value=df.subtype) df.drop(["ParameterType"], axis=1, inplace=True) except AttributeError: pass def __fix_tactic(df: pd.DataFrame): df.rename(columns={"TacticName": "tactic"}, inplace=True) try: df["tactic"] = df.tactic.fillna(value="TensorRT") except AttributeError: df["tactic"] = "TensorRT" def __fix_columns_types(df: pd.DataFrame): int_cols = [ "Groups", "OutMaps", "HasBias", "HasReLU", "AllowSparse", "NbInputArgs", "NbOutputVars", "NbParams", "NbLiterals", ] for col in int_cols: try: df[col] = df[col].fillna(value=0) df[col] = df[col].astype("int32") except KeyError: pass df.fillna("", inplace=True) def __fix_output_precision(df: pd.DataFrame): df["output_precision"] = [Activation(outputs[0]).precision for outputs in df["Outputs"]] def fix_df(df: pd.DataFrame): """One-time preprocessing of the DF. Performed only on DF construction. """ __fix_type(df) __fix_tactic(df) __fix_columns_types(df) __fix_output_precision(df) return df def clean_io(df: pd.DataFrame): for index, layer in df.iterrows(): inputs, outputs = create_activations(layer) if len(inputs) > 0: inp_str = ", ".join([inp.format for inp in inputs]) df.loc[index, "Inputs"] = inp_str df.loc[index, "Outputs"] = outputs[0].format def filter_by_layer(df: pd.DataFrame, layer_type: str): copy_cols = ["Name", "type", "precision", "tactic", "latency.pct_time", "latency.avg_time", "total_io_size_bytes", "total_footprint_bytes", "Inputs", "Outputs", "subtype"] try: attrs = layer_attributes[layer_type] copy_cols += [k for k, v in attrs.items() if v is not None] # Pointwise and Pointwise V2 layers have the same layer type. if layer_type == "PointWise": attrs = layer_attributes["PointWiseV2"] copy_cols += [k for k, v in attrs.items() if v is not None] except KeyError: pass layers = df.query(f"type == \"{layer_type}\"").copy() if len(layers) == 0: return layers copy_cols = set(copy_cols) & set(layers.columns) layers = layers[copy_cols] if layer_type == "Convolution": layers.rename(columns=layer_attributes[layer_type], inplace=True) layers["attr.kernel"] = tuple(layers["attr.kernel"]) annotate_convolutions(layers) if layer_type == "PointWise": # The original JSON file handle PointWise and PointWise V2 as two subtypes. pw = layers[layers["subtype"] == "PointWise"].copy() pw.rename(columns=layer_attributes["PointWise"], inplace=True) pw_v2 = layers[layers["subtype"] == "PointWiseV2"].copy() pw_v2.rename(columns=layer_attributes["PointWiseV2"], inplace=True) layers = pd.concat((pw, pw_v2)) else: try: layers.rename(columns=layer_attributes[layer_type], inplace=True) except: pass return layers def change_col_order(df: pd.DataFrame): """Change the dataframe columns-order (place common fields earlier)""" cols = df.columns.to_list() common_cols = list(("Name", "type", "Inputs", "Outputs", "latency.avg_time", "latency.pct_time", "total_footprint_bytes", "tactic")) common_cols = [col for col in common_cols if col in cols] cols = common_cols + [col for col in cols if col not in common_cols] df = df[cols] return df def drop_columns(df: pd.DataFrame, columns: list): for col in columns: try: df.drop([col], axis=1, inplace=True) except KeyError: pass def clean_df(df: pd.DataFrame, inplace=True): clean_io(df) columns = set([col for col_list in layer_attributes.keys() for col in col_list]) drop_columns(df, columns) df.fillna(0, inplace=inplace) return df def clean_for_display(df: pd.DataFrame): """Prepare the dataframe for display""" df = clean_df(df.copy(), inplace=True) df = change_col_order(df) drop_columns(df, columns=["subtype", "TacticValue", "precision", "total_io_size_bytes"]) return df def annotate_convolutions(convs: pd.DataFrame): """Convolutions as implicit GEMM""" for index, conv in convs.iterrows(): inputs, outputs = create_activations(conv) assert len(inputs) > 0 N, C, H, W = inputs[0].shape # K: number of channels; P: Height; Q: Width _, K, P, Q = outputs[0].shape R, S = convs.loc[index, "attr.kernel"] G = convs.loc[index, "attr.groups"] weights_vol = (K * C * R * S) / G input_vol = N * C * H * W output_vol = N * K * P * Q input_bytes = input_vol * inputs[0].data_size output_bytes = output_vol * outputs[0].data_size weights_bytes = weights_vol * inputs[0].data_size nb_bytes = input_bytes + weights_bytes + output_bytes nb_macs = N * K * P * Q * C * R * S / G convs.loc[index, "attr.macs"] = nb_macs # Arithmetic intensity: ops/bytes convs.loc[index, "attr.arithmetic_intensity"] = nb_macs / nb_bytes latency = convs.loc[index, "latency.avg_time"] convs.loc[index, "attr.compute_efficiency"] = nb_macs / latency convs.loc[index, "attr.memory_efficiency"] = nb_bytes / latency # Conversion to matrices (M, K) * (K, N) M = N * P * Q N = K K = C * R * S convs.loc[index, "attr.M"] = M convs.loc[index, "attr.N"] = N convs.loc[index, "attr.K"] = K convs["attr.macs"] = convs["attr.macs"].astype("int64") convs["attr.M"] = convs["attr.M"].astype("int64") convs["attr.N"] = convs["attr.N"].astype("int64") convs["attr.K"] = convs["attr.K"].astype("int64")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/df_preprocessing.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ Miscellanous functions used in Jupyter notebooks """ import dtale import pandas as pd import qgrid from ipyfilechooser import FileChooser from IPython.core.display import HTML, display dtale.global_state.set_app_settings(dict(max_column_width=600)) # pixels def section_header(title): style = "text-align:center;background:#76b900;padding:20px;color:#ffffff;font-size:2em;" return HTML('<div style="{}">{}</div>'.format(style, title)) def set_wide_display(width_pct: int = 90): """Configure a wider rendering of the notebook (for easier viewing of wide tables and graphs). """ display(HTML(f"<style>.container {{width:{width_pct}% !important;}}</style>")) def display_df_qgrid(df: pd.DataFrame): """Display a Pandas dataframe using a qgrid widget""" grid = qgrid.show_grid(df, grid_options={ "forceFitColumns": False, "fullWidthRows": True }, column_options={ "resizable": True, }, column_definitions={ "index": { "maxWidth": 0, "minWidth": 0, "width": 0 }, "Name": { "maxwidth": 400 } }) display(grid) def display_df_dtale(df: pd.DataFrame, range_highlights: dict = None, nan_display: str = "...", precision: int = 4): """Display a Pandas dataframe using a dtale widget""" d = dtale.show(df, drop_index=True, allow_cell_edits=False, precision=precision, nan_display=nan_display) if range_highlights is not None: d.update_settings(range_highlights=range_highlights, background_mode="range") display(d) def display_df(df: pd.DataFrame, **kwargs): display_df_dtale(df, **kwargs) def display_filechooser(rootdir: str) -> FileChooser: """Create and display a FileChooser widget""" fc = FileChooser(rootdir) fc.filter_pattern = '*.engine' fc.title = 'Press Select to choose an engine file' display(fc) return fc
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/notebook.py
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed 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. # """ This file contains layer linting functions. """ from collections import OrderedDict from typing import Dict import pandas as pd from .activations import create_activations from .engine_plan import EnginePlan class ConvLinter(): """Convolution layer linter.""" def __init__(self, plan: EnginePlan): self.plan = plan self.convs = plan.get_layers_by_type("Convolution") def tc_lint(self): """Search for Convolutions which are not accelerated by TensorCode""" def is_small_conv(conv): inputs, _ = create_activations(conv) if len(inputs[0].shape) != 4: return False n, c, h, w = inputs[0].shape return c < 32 report = OrderedDict() # Look for kernels that are not scheduled for TensorCore acceleration tc_candidates = self.convs.query(f"precision != \"FP32\"").copy() # Identify acceleration from tactic name df = tc_candidates df = df[df["tactic"].str.contains("imma|hmma|xmma|i88|884", na=False) == False] for _, conv in df.iterrows(): mitigation = "" if is_small_conv(conv): mitigation = "This Convolution has a small number " \ "of input channels so acceleration may not be possible." report[conv.Name] = OrderedDict({"name": conv.Name, "tactic": conv.tactic, "subtype": conv.subtype, "hazard": "Convolution is not accelerated.", "mitigation": mitigation, "help": "TensorCores accelerate large Convolution and GEMM operations."}) return report def mixed_precision_lint(self): """Search for Convolutions with Int8 inputs and Float outputs""" report = OrderedDict() df = self.convs df = df.loc[df["precision"] == "INT8"].copy() for index, conv in df.iterrows(): inputs, outputs = create_activations(conv) inf = inputs[0].format[:4] outf = outputs[0].format[:4] found = inf == "Int8" and outf != "Int8" if found: report[conv.Name] = OrderedDict({ "name": conv.Name, "tactic": conv.tactic, "subtype": conv.subtype, "hazard": "Quantized Convolution has float outputs.", "mitigation": "Consider adding quantization after the convolution.", "help": "Quantized Convolution with float outputs is ill advised " "for memory-limited convolutions." }) return report def alignment_lint(self): def alignment_ok(conv): inputs, outputs = create_activations(conv) prec = conv["precision"] if len(inputs[0].shape) != 4 or len(outputs[0].shape) != 4: return True N, C, H, W = inputs[0].shape _, K, P, Q = outputs[0].shape if prec == "INT8": ok = (C % 16 == 0) and (K % 16 == 0) else: ok = (C % 8 == 0) and (K % 8 == 0) return ok report = OrderedDict() for _, conv in self.convs.iterrows(): if not alignment_ok(conv): report[conv.Name] = { "name": conv.Name, "tactic": conv.tactic, "subtype": conv.subtype, "hazard": "Convolution channels are not optimally aligned.", "mitigation": "Consider changing the alignment of the convolution's channels.", "help": "For best performance, the input and outputs channels of a Tensor Core" "accelerated convolution should be aligned to 8 (FP32/FP16) or 16 (INT8)" } return report def lint(self): report = self.tc_lint() report.update(self.mixed_precision_lint()) report.update(self.alignment_lint()) df = pd.DataFrame.from_dict(report, orient="index") return df class ReformatLinter(): """Reformat layer linter.""" def __init__(self, plan: EnginePlan): self.plan = plan self.reformats = plan.get_layers_by_type("Reformat") def lint(self): """Search for conversions between types. Conversions between layouts are assumed to be optimized.""" report = OrderedDict() for index, reformat in self.reformats.iterrows(): inputs, outputs = create_activations(reformat) inf = inputs[0].format[:4] outf = outputs[0].format[:4] if inf != outf: mitigation = "" if "INT8" in [inf, outf]: mitigation = "Consider adding quantization around float operations." report[reformat.Name] = OrderedDict({ "name": reformat.Name, "origin": reformat["attr.origin"], 'type conversion': f"{inf} -> {outf}", 'shape conversion': f"{inputs[0].shape} -> {outputs[0].shape}", "hazard": "Reformat layer is converting operand data type.", "mitigation": mitigation, "help": "Conversions between float32 and float16 are a red " "flag, as are conversions between float32/16 and INT8." }) df = pd.DataFrame.from_dict(report, orient="index") return df class SliceLinter(): """Slice layer linter.""" def __init__(self, plan: EnginePlan): self.plan = plan self.slices = plan.get_layers_by_type("Slice") def lint(self): """Search for conversions between types. Conversions between layouts are assumed to be optimized.""" report = OrderedDict() for index, slice in self.slices.iterrows(): inputs, outputs = create_activations(slice) inf = inputs[0].format[:4] outf = outputs[0].format[:4] if inf != outf: mitigation = "" if "INT8" in [inf, outf]: mitigation = "Consider adding quantization around float operations." report[slice.Name] = OrderedDict({ "name": slice.Name, 'type conversion': f"{inf} -> {outf}", 'shape conversion': f"{inputs[0].shape} -> {outputs[0].shape}", "hazard": "Slice layer is converting operand data type.", "mitigation": mitigation, "help": "Conversions between float32 and float16 are a red " "flag, as are conversions between float32/16 <=> INT8." }) df = pd.DataFrame.from_dict(report, orient="index") return df class QDQLinter(): """Q/DQ layer linter.""" def __init__(self, plan: EnginePlan): self.plan = plan self.scales = plan.get_layers_by_type("Scale") def lint(self): """Search for dangling Q/DQ layers.""" report = OrderedDict() for index, scale in self.scales.iterrows(): inputs, outputs = create_activations(scale) inf = inputs[0].format[:4] outf = outputs[0].format[:4] is_qdq = ("Int8" in inputs[0].format) ^ ("Int8" in outputs[0].format) if is_qdq: dq = "Int8" in inputs[0].format role = "Quantize" if not dq else "Dequanitize" report[scale.Name] = OrderedDict({ "name": scale.Name, 'type conversion': f"{inf} -> {outf}", "hazard": f"Unfused {role} layer", "mitigation": f"Check why the {role} layer is not fused", "help": f"Unfused Quantize/Dequantize nodes are wasteful and " "should be avoided. Quantize nodes may be necessary " "for quantizing inputs." }) df = pd.DataFrame.from_dict(report, orient="index") return df
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trex/trex/lint.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "AddScalar", scopeName, n, [tensorX], OrderedDict([["scalar", 1.0]]), "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor1] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-API/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import polygraphy.backend.trt as p import tensorrt as trt onnxFile = "./modelA.onnx" trtFile = "./modelA.plan" cacheFile = "./modelA.cache" builder, network, parser = p.network_from_onnx_path(onnxFile) profileList = [p.Profile().add("tensorX", [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28])] builderConfig = p.CreateConfig( \ tf32=False, fp16=True, int8=False, profiles=profileList, calibrator=None, precision_constraints=None, strict_types=False, load_timing_cache=None, algorithm_selector=None, sparse_weights=False, tactic_sources=None, restricted=False, use_dla=False, allow_gpu_fallback=False, profiling_verbosity=None, memory_pool_limits={trt.MemoryPoolType.WORKSPACE:1<<30}, refittable=False, preview_features=None, engine_capability=None, direct_io=False, builder_optimization_level=None, fp8=False, hardware_compatibility_level=None, max_aux_streams=4, version_compatible=False, exclude_lean_runtime=False) engineString = p.engine_from_network([builder, network], config=builderConfig, save_timing_cache=cacheFile) p.save_engine(engineString, path=trtFile) runner = p.TrtRunner(engineString, name=None, optimization_profile=0) runner.activate() output = runner.infer(OrderedDict([("tensorX", np.ascontiguousarray(np.random.rand(4, 1, 28, 28).astype(np.float32) * 2 - 1))]), check_inputs=True) runner.deactivate() print(output) """ methods of polygraphy.backend.trt: 'Algorithm' 'BytesFromEngine' 'Calibrator' 'CreateConfig' 'CreateNetwork' 'EngineBytesFromNetwork' 'EngineFromBytes' 'EngineFromNetwork' 'LoadPlugins' 'ModifyNetworkOutputs' 'NetworkFromOnnxBytes' 'NetworkFromOnnxPath' 'OnnxLikeFromNetwork' 'Profile' 'SaveEngine' 'ShapeTuple' 'TacticRecorder' 'TacticReplayData' 'TacticReplayer' 'TrtRunner' '__builtins__' '__cached__' '__doc__' '__file__' '__loader__' '__name__' '__package__' '__path__' '__spec__' 'algorithm_selector' 'bytes_from_engine' 'calibrator' 'create_config' 'create_network' 'engine_bytes_from_network' 'engine_from_bytes' 'engine_from_network' 'get_trt_logger' 'load_plugins' 'loader' 'modify_network_outputs' 'network_from_onnx_bytes' 'network_from_onnx_path' 'onnx_like_from_network' 'profile' 'register_logger_callback' 'runner' 'save_engine' 'util' """
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-API/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs np.random.seed(31193) def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Onnxruntime/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import onnxruntime np.random.seed(31193) data = np.random.rand(1, 1, 28, 28).astype(np.float32) * 2 - 1 onnxFile = "modelA.onnx" # Run the model in Onnx Runtime ------------------------------------------------ print("Onnxruntime using device: %s" % onnxruntime.get_device()) session = onnxruntime.InferenceSession(onnxFile, providers=["CPUExecutionProvider"]) for i, inputTensor in enumerate(session.get_inputs()): print("Input %2d: %s, %s, %s" % (i, inputTensor.name, inputTensor.shape, inputTensor.type)) for i, outputTensor in enumerate(session.get_outputs()): print("Output%2d: %s, %s, %s" % (i, outputTensor.name, outputTensor.shape, outputTensor.type)) inputDict = {} inputDict[session.get_inputs()[0].name] = data outputList = session.run(None, inputDict) for i, outputTensor in enumerate(outputList): print("Output%2d:\n%s" % (i, outputTensor)) print("Succeeding running model in OnnxRuntime!")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Onnxruntime/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import json from copy import deepcopy import numpy as np import tensorrt as trt def rebuildNetwork(logger, bPrintInformation=True, jsonFile="./model.json", paraFile="./model.npz"): with open(jsonFile, "r") as f: js = json.loads(f.read()) if paraFile is not None: para = np.load(paraFile) else: print("Using fake weight!") np.random.seed(31193) para = None # Builder if bPrintInformation: print("\nJSON Information:") for key in js["Builder"].keys(): print("js[\"Builder\"][\"%s\"] = %s" % (key, js["Builder"][key])) builder = trt.Builder(logger) builder.max_threads = js["Builder"]["nMaxThread"] if int(trt.__version__.split(".")[0]) < 8: # deprecated since TensorRT 8 builder.max_batch_size = js["builder"]["nMaxBatchSize"] builder.max_workspace_size = js["builder"]["nMaxWorkspaceSize"] # Network if bPrintInformation: for key in js["Network"].keys(): print("js[\"Network\"][\"%s\"] = %s" % (key, js["Network"][key])) networkFlag = 0 if not js["Network"]["bImplicitBatchMode"]: networkFlag |= 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) if js["Network"]["bExplicitPrecision"]: # deprecated since TensorRT 8.4 networkFlag |= 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION) network = builder.create_network(networkFlag) network.name = js["Network"]["sName"] for i in range(js["Network"]["nInput"]): tensorName = js["Network"]["Binding"][i]["sName"] inputTensor = js["Tensor"][tensorName] network.add_input(tensorName, trt.DataType(inputTensor["kDataType"]), inputTensor["lShape"]) dTensor = {} # Dictionary of tensors in new network for i in range(js["Network"]["nInput"]): tensor = network.get_input(i) dTensor[tensor.name] = tensor dIfCondition = {} # Dictionary of IfCondition structure in new network dLoop = {} # Dictionary of Loop structure in new network dLateLayerTensor = {} # In some cases, the shape tensor comsumed in early layer is produced in later layer, so we mark and set them later. # Constant layer for Range Node from ONNX file constantLayer0 = network.add_constant([], trt.Weights(np.ascontiguousarray(np.array([0], dtype=np.int32)))) constantLayer0.name = "ConstantLayer0ForRangeNoe" constantLayer0.get_output(0).name = "ConstantTensor0ForRangeNoe" constantLayer1 = network.add_constant([1], trt.Weights(np.ascontiguousarray(np.array([1], dtype=np.int32)))) constantLayer1.name = "ConstantLayer1ForRangeNoe" constantLayer1.get_output(0).name = "ConstantTensor1ForRangeNoe" # rebuild network layer by layer ------------------------------------------- for i in range(js["Network"]["nLayer"]): layerInfo = js["Layer"][i] if bPrintInformation: print("%4d->%-15s,%s" % (i, str(trt.LayerType(layerInfo["kType"]))[10:], layerInfo["sName"])) for key in layerInfo.keys(): print(" Layer[\"%s\"] = %s" % (key, layerInfo[key])) # Specialization part of each layer # 0 LayerType.CONVOLUTION # 1 LayerType.FULLY_CONNECTED # 2 LayerType.ACTIVATION # 3 LayerType.POOLING # 4 LayerType.LRN # 5 LayerType.SCALE # 6 LayerType.SOFTMAX # 7 LayerType.DECONVOLUTION # 8 LayerType.CONCATENATION # 9 LayerType.ELEMENTWISE # 10 LayerType.PLUGIN # 11 LayerType.UNARY # 12 LayerType.PADDING # 13 LayerType.SHUFFLE # 14 LayerType.REDUCE # 15 LayerType.TOPK # 16 LayerType.GATHER # 17 LayerType.MATRIX_MULTIPLY # 18 LayerType.RAGGED_SOFTMAX # 19 LayerType.CONSTANT # 20 LayerType.RNN_V2 # 21 LayerType.IDENTITY # 22 LayerType.PLUGIN_V2 # 23 LayerType.SLICE # 24 LayerType.SHAPE # 25 LayerType.PARAMETRIC_RELU # 26 LayerType.RESIZE # 27 LayerType.TRIP_LIMIT # 28 LayerType.RECURRENCE # 29 LayerType.ITERATOR # 30 LayerType.LOOP_OUTPUT # 31 LayerType.SELECT # 32 LayerType.FILL # 33 LayerType.QUANTIZE # 34 LayerType.DEQUANTIZE # 35 LayerType.CONDITION # 36 LayerType.CONDITIONAL_INPUT # 37 LayerType.CONDITIONAL_OUTPUT # 38 LayerType.SCATTER # 39 LayerType.EINSUM # 40 LayerType.ASSERTION if layerInfo["kType"] == int(trt.LayerType.CONVOLUTION): # 0 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] if para is not None: kernel = para[layerInfo["sName"] + "-kernel"] bias = para[layerInfo["sName"] + "-bias"] else: kernelShape = layerInfo["lKernelShape"] biasShape = layerInfo["lBiasShape"] kernel = np.random.rand(np.prod(kernelShape)).astype(np.float32).reshape(kernelShape) * 2 - 1 bias = np.random.rand(np.prod(biasShape)).astype(np.float32).reshape(biasShape) * 2 - 1 if np.prod(kernel.shape) != 0: # Normal if np.prod(bias.shape) != 0: layer = network.add_convolution_nd(inputTensor, layerInfo["num_output_maps"], layerInfo["kernel_size_nd"], trt.Weights(kernel), trt.Weights(bias)) else: layer = network.add_convolution_nd(inputTensor, layerInfo["num_output_maps"], layerInfo["kernel_size_nd"], trt.Weights(kernel)) else: # INT8-QDQ assert (layerInfo["nInput"] == 2) if np.prod(bias.shape) != 0: layer = network.add_convolution_nd(inputTensor, layerInfo["num_output_maps"], layerInfo["kernel_size_nd"], trt.Weights(), trt.Weights(bias)) else: layer = network.add_convolution_nd(inputTensor, layerInfo["num_output_maps"], layerInfo["kernel_size_nd"], trt.Weights()) tensorName1 = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName1] layer.set_input(1, inputTensor1) layer.kernel_size_nd = layerInfo["kernel_size_nd"] layer.num_output_maps = layerInfo["num_output_maps"] layer.stride_nd = layerInfo["stride_nd"] layer.dilation_nd = layerInfo["dilation_nd"] layer.num_groups = layerInfo["num_groups"] layer.padding_nd = layerInfo["padding_nd"] layer.padding_mode = trt.PaddingMode(layerInfo["padding_mode"]) layer.pre_padding = layerInfo["pre_padding"] layer.post_padding = layerInfo["post_padding"] elif layerInfo["kType"] == int(trt.LayerType.FULLY_CONNECTED): # 1 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] if para is not None: kernel = para[layerInfo["sName"] + "-kernel"] bias = para[layerInfo["sName"] + "-bias"] else: kernelShape = layerInfo["lKernelShape"] biasShape = layerInfo["lBiasShape"] kernel = np.random.rand(np.prod(kernelShape)).astype(np.float32).reshape(kernelShape) * 2 - 1 bias = np.random.rand(np.prod(biasShape)).astype(np.float32).reshape(biasShape) * 2 - 1 if np.prod(kernel.shape) != 0: # Normal if np.prod(bias.shape) != 0: layer = network.add_fully_connected(inputTensor, layerInfo["num_output_channels"], trt.Weights(kernel), trt.Weights(bias)) else: layer = network.add_fully_connected(inputTensor, layerInfo["num_output_channels"], trt.Weights(kernel)) else: # INT8-QDQ assert (layerInfo["nInput"] == 2) if np.prod(bias.shape) != 0: layer = network.add_fully_connected(inputTensor, layerInfo["num_output_channels"], trt.Weights(), trt.Weights(bias)) else: layer = network.add_fully_connected(inputTensor, layerInfo["num_output_channels"], trt.Weights()) tensorName = layerInfo["lInputTensorName"][1] inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) layer.num_output_channels = layerInfo["num_output_channels"] elif layerInfo["kType"] == int(trt.LayerType.ACTIVATION): # 2 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_activation(inputTensor, trt.ActivationType.RELU) layer.alpha = layerInfo["alpha"] layer.beta = layerInfo["beta"] layer.type = trt.ActivationType(layerInfo["type"]) elif layerInfo["kType"] == int(trt.LayerType.POOLING): # 3 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_pooling_nd(inputTensor, trt.PoolingType.MAX, [1, 1]) layer.average_count_excludes_padding = layerInfo["average_count_excludes_padding"] layer.blend_factor = layerInfo["blend_factor"] layer.stride_nd = layerInfo["stride_nd"] layer.padding_nd = layerInfo["padding_nd"] layer.padding_mode = trt.PaddingMode(layerInfo["padding_mode"]) layer.pre_padding = layerInfo["pre_padding"] layer.post_padding = layerInfo["post_padding"] layer.type = trt.PoolingType(layerInfo["type"]) layer.window_size_nd = layerInfo["window_size_nd"] elif layerInfo["kType"] == int(trt.LayerType.LRN): # 4 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_lrn(inputTensor, 1, 0.0, 1.0, 1.0) layer.alpha = layerInfo["alpha"] layer.beta = layerInfo["beta"] layer.k = layerInfo["k"] layer.window_size = layerInfo["window_size"] elif layerInfo["kType"] == int(trt.LayerType.SCALE): # 5 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] if para is not None: scale = para[layerInfo["sName"] + "-scale"] shift = para[layerInfo["sName"] + "-shift"] power = para[layerInfo["sName"] + "-power"] else: scaleShape = layerInfo["lScaleShape"] shiftShape = layerInfo["lShiftShape"] powerShape = layerInfo["lPowerShape"] scale = np.random.rand(np.prod(scaleShape)).astype(np.float32).reshape(scaleShape) * 2 - 1 shift = np.random.rand(np.prod(shiftShape)).astype(np.float32).reshape(shiftShape) * 2 - 1 power = np.ones(np.prod(powerShape)).astype(np.float32).reshape(powerShape) layer = network.add_scale_nd(inputTensor, trt.ScaleMode(layerInfo["mode"]), shift, scale, power, layerInfo["channel_axis"]) layer.channel_axis = layerInfo["channel_axis"] layer.mode = trt.ScaleMode(layerInfo["mode"]) layer.shift = shift layer.scale = scale layer.power = power elif layerInfo["kType"] == int(trt.LayerType.SOFTMAX): # 6 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_softmax(inputTensor) layer.axes = layerInfo["axes"] elif layerInfo["kType"] == int(trt.LayerType.DECONVOLUTION): # 7 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] if para is not None: kernel = para[layerInfo["sName"] + "-kernel"] bias = para[layerInfo["sName"] + "-bias"] else: kernelShape = layerInfo["lKernelShape"] biasShape = layerInfo["lBiasShape"] kernel = np.random.rand(np.prod(kernelShape)).astype(np.float32).reshape(kernelShape) * 2 - 1 bias = np.random.rand(np.prod(biasShape)).astype(np.float32).reshape(biasShape) * 2 - 1 if np.prod(kernel.shape) != 0: # Normal if np.prod(bias.shape) != 0: layer = network.add_deconvolution_nd(inputTensor, 1, [1, 1], trt.Weights(kernel), trt.Weights(bias)) else: layer = network.add_deconvolution_nd(inputTensor, 1, [1, 1], trt.Weights(kernel)) else: # INT8-QDQ assert (layerInfo["nInput"] == 2) if np.prod(bias.shape) != 0: layer = network.add_deconvolution_nd(inputTensor, 1, [1, 1], trt.Weights(), trt.Weights(bias)) else: layer = network.add_deconvolution_nd(inputTensor, 1, [1, 1], trt.Weights()) layer.kernel_size_nd = layerInfo["kernel_size_nd"] layer.num_output_maps = layerInfo["num_output_maps"] layer.stride_nd = layerInfo["stride_nd"] layer.dilation_nd = layerInfo["dilation_nd"] layer.num_groups = layerInfo["num_groups"] layer.padding_nd = layerInfo["padding_nd"] layer.padding_mode = trt.PaddingMode(layerInfo["padding_mode"]) layer.pre_padding = layerInfo["pre_padding"] layer.post_padding = layerInfo["post_padding"] elif layerInfo["kType"] == int(trt.LayerType.CONCATENATION): # 8 inputTensorList = [] for j in range(layerInfo["nInput"]): tensorName = layerInfo["lInputTensorName"][j] inputTensorList.append(dTensor[tensorName]) layer = network.add_concatenation(inputTensorList) layer.axis = layerInfo["axis"] elif layerInfo["kType"] == int(trt.LayerType.ELEMENTWISE): # 9 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_elementwise(inputTensor0, inputTensor1, trt.ElementWiseOperation.SUM) layer.op = trt.ElementWiseOperation(layerInfo["op"]) elif layerInfo["kType"] == int(trt.LayerType.PLUGIN): # 10 print("IPlugin Layer not supported!") break elif layerInfo["kType"] == int(trt.LayerType.UNARY): # 11 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_unary(inputTensor, trt.UnaryOperation.ABS) layer.op = trt.UnaryOperation(layerInfo["op"]) elif layerInfo["kType"] == int(trt.LayerType.PADDING): # 12 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_padding_nd(inputTensor, (0, 0), (0, 0)) layer.pre_padding_nd = layerInfo["pre_padding_nd"] layer.post_padding_nd = layerInfo["post_padding_nd"] elif layerInfo["kType"] == int(trt.LayerType.SHUFFLE): # 13 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_shuffle(inputTensor) if layerInfo["bDynamicShuffle"]: tensorName = layerInfo["lInputTensorName"][1] if tensorName in dTensor.keys(): # In some cases, the shape tensor comsumed in early layer is produced in later layer, so we mark and set them later. inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) else: dLateLayerTensor[layerInfo["kIndex"]] = tensorName else: if layerInfo["reshape_dims"] is not None: layer.reshape_dims = layerInfo["reshape_dims"] layer.first_transpose = layerInfo["first_transpose"] layer.second_transpose = layerInfo["second_transpose"] layer.zero_is_placeholder = layerInfo["zero_is_placeholder"] elif layerInfo["kType"] == int(trt.LayerType.REDUCE): # 14 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_reduce(inputTensor, trt.ReduceOperation.SUM, 1 << 1, False) layer.axes = layerInfo["axes"] layer.op = trt.ReduceOperation(layerInfo["op"]) layer.keep_dims = layerInfo["keep_dims"] elif layerInfo["kType"] == int(trt.LayerType.TOPK): # 15 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_topk(inputTensor, trt.TopKOperation.MAX, 2, 1 << 1) layer.axes = layerInfo["axes"] layer.op = trt.TopKOperation(layerInfo["op"]) layer.k = layerInfo["k"] elif layerInfo["kType"] == int(trt.LayerType.GATHER): # 16 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_gather(inputTensor0, inputTensor1, 1) layer.axis = layerInfo["axis"] layer.mode = trt.GatherMode(layerInfo["mode"]) elif layerInfo["kType"] == int(trt.LayerType.MATRIX_MULTIPLY): # 17 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_matrix_multiply(inputTensor0, trt.MatrixOperation.NONE, inputTensor1, trt.MatrixOperation.NONE) layer.op0 = trt.MatrixOperation(layerInfo["op0"]) layer.op1 = trt.MatrixOperation(layerInfo["op1"]) elif layerInfo["kType"] == int(trt.LayerType.RAGGED_SOFTMAX): # 18 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_ragged_softmax(inputTensor0, inputTensor1) elif layerInfo["kType"] == int(trt.LayerType.CONSTANT): # 19 weightShape = layerInfo["shape"] if weightShape == [0]: layer = network.add_constant([0], trt.Weights()) else: if para is not None: weight = para[layerInfo["sName"] + "-weights"] else: weight = np.random.rand(np.prod(weightShape)).astype(np.float32).reshape(weightShape) layer = network.add_constant(weightShape, trt.Weights(weight)) elif layerInfo["kType"] == int(trt.LayerType.RNN_V2): # 20 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_rnn_v2(inputTensor, layerInfo["num_layers"], layerInfo["hidden_size"], layerInfo["max_seq_length"], trt.RNNOperation(layerInfo["op"])) #layer.num_layers = layerInfo["num_layers"] # read only #layer.hidden_size = layerInfo["hidden_size"] # read only #layer.max_seq_length = layerInfo["max_seq_length"] # read only layer.op = trt.RNNOperation(layerInfo["op"]) #layer.data_length = layerInfo["data_length"] # read only layer.input_mode = trt.RNNInputMode(layerInfo["input_mode"]) layer.direction = trt.RNNDirection(layerInfo["direction"]) tensorName = layerInfo["lInputTensorName"][1] if tensorName is not None: inputTensor = dTensor[tensorName] layer.hidden_state = inputTensor tensorName = layerInfo["lInputTensorName"][2] if tensorName is not None: inputTensor = dTensor[tensorName] layer.cell_state = inputTensor tensorName = layerInfo["lInputTensorName"][3] if tensorName is not None: inputTensor = dTensor[tensorName] layer.seq_lengths = inputTensor nRealLayer = layer.num_layers * (2 if layer.direction == trt.RNNDirection.BIDIRECTION else 1) if layer.op == trt.RNNOperation.RELU or layer.op == trt.RNNOperation.TANH: lGateKind = [trt.RNNGateType.INPUT] elif layer.op == trt.RNNOperation.LSTM: lGateKind = [trt.RNNGateType.INPUT, trt.RNNGateType.CELL, trt.RNNGateType.FORGET, trt.RNNGateType.OUTPUT] elif layer.op == trt.RNNOperation.GRU: lGateKind = [trt.RNNGateType.UPDATE, trt.RNNGateType.RESET] else: lGateKind = [] for j in range(nRealLayer): for gateKind in lGateKind: if layer.input_mode == trt.RNNInputMode.LINEAR: layer.set_weights_for_gate(j, gateKind, True, para[layerInfo["sName"] + "-" + str(j) + "-" + str(int(gateKind)) + "-weightX"]) layer.set_bias_for_gate(j, gateKind, True, para[layerInfo["sName"] + "-" + str(j) + "-" + str(int(gateKind)) + "-biasX"]) layer.set_weights_for_gate(j, gateKind, False, para[layerInfo["sName"] + "-" + str(j) + "-weightH"]) layer.set_bias_for_gate(j, gateKind, False, para[layerInfo["sName"] + "-" + str(j) + "-biasH"]) elif layerInfo["kType"] == int(trt.LayerType.IDENTITY): # 21 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_identity(inputTensor) elif layerInfo["kType"] == int(trt.LayerType.PLUGIN_V2): # 22 print("IPlugin Layer not supported!") break elif layerInfo["kType"] == int(trt.LayerType.SLICE): # 23 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_slice(inputTensor, [0], [1], [1]) layer.mode = trt.SliceMode(layerInfo["mode"]) if layerInfo["start"] == None: tensorName = layerInfo["lInputTensorName"][1] inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) else: layer.start = layerInfo["start"] if layerInfo["shape"] == None: tensorName = layerInfo["lInputTensorName"][2] inputTensor = dTensor[tensorName] layer.set_input(2, inputTensor) else: layer.shape = layerInfo["shape"] if layerInfo["stride"] == None: tensorName = layerInfo["lInputTensorName"][3] inputTensor = dTensor[tensorName] layer.set_input(3, inputTensor) else: layer.stride = layerInfo["stride"] if trt.SliceMode(layerInfo["mode"]) == trt.SliceMode.FILL and layerInfo["fill"] == True: tensorName = layerInfo["lInputTensorName"][4] inputTensor = dTensor[tensorName] layer.set_input(4, inputTensor) elif layerInfo["kType"] == int(trt.LayerType.SHAPE): # 24 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_shape(inputTensor) elif layerInfo["kType"] == int(trt.LayerType.PARAMETRIC_RELU): # 25 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_parametric_relu(inputTensor0, inputTensor1) elif layerInfo["kType"] == int(trt.LayerType.RESIZE): # 26 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_resize(inputTensor) if layerInfo["bDynamicResize"]: tensorName = layerInfo["lInputTensorName"][1] inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) elif layerInfo["bShapeMode"]: layer.shape = layerInfo["shape"] else: layer.scales = layerInfo["scales"] layer.resize_mode = trt.ResizeMode(layerInfo["resize_mode"]) layer.coordinate_transformation = trt.ResizeCoordinateTransformation(layerInfo["coordinate_transformation"]) layer.selector_for_single_pixel = trt.ResizeSelector(layerInfo["selector_for_single_pixel"]) layer.nearest_rounding = trt.ResizeRoundMode(layerInfo["nearest_rounding"]) elif layerInfo["kType"] == int(trt.LayerType.TRIP_LIMIT): # 27 bExist = False for key, value in dLoop.items(): # find if the Loop already exists in the new network if value["TripLimitLayerName"] == layerInfo["sName"]: bExist = True sLoopName = key if not bExist: # not exist, add a new Loop structure for key, value in js["Loop"].items(): if value["TripLimitLayerName"] == layerInfo["sName"]: dLoop[key] = {} dLoop[key]["TripLimitLayerName"] = layerInfo["sName"] dLoop[key]["RecurrenceLayerName"] = value["RecurrenceLayerName"] dLoop[key]["LoopOutputLayerName"] = value["LoopOutputLayerName"] dLoop[key]["IteratorLayerName"] = value["IteratorLayerName"] dLoop[key]["RecurrenceLayer"] = [] dLoop[key]["LoopOutputLayer"] = [] dLoop[key]["IteratorLayer"] = [] dLoop[key]["Loop"] = network.add_loop() sLoopName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dLoop[sLoopName]["Loop"].add_trip_limit(inputTensor, trt.TripLimit(layerInfo["kind"])) dLoop[sLoopName]["TripLimitLayer"] = layer elif layerInfo["kType"] == int(trt.LayerType.RECURRENCE): # 28 bExist = False for key, value in dLoop.items(): # find if the Loop already exists in the new network if layerInfo["sName"] in value["RecurrenceLayerName"]: bExist = True sLoopName = key if not bExist: # not exist, add a new Loop structure for key, value in js["Loop"].items(): if layerInfo["sName"] in value["RecurrenceLayerName"]: dLoop[key] = {} dLoop[key]["TripLimitLayerName"] = value["TripLimitLayerName"] dLoop[key]["RecurrenceLayerName"] = value["RecurrenceLayerName"] dLoop[key]["LoopOutputLayerName"] = value["LoopOutputLayerName"] dLoop[key]["IteratorLayerName"] = value["IteratorLayerName"] dLoop[key]["RecurrenceLayer"] = [] dLoop[key]["LoopOutputLayer"] = [] dLoop[key]["IteratorLayer"] = [] dLoop[key]["Loop"] = network.add_loop() sLoopName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dLoop[sLoopName]["Loop"].add_recurrence(inputTensor) # the second input tensor is recycled in the later additional scan dLoop[sLoopName]["RecurrenceLayer"].append(layer) # append rather than assign elif layerInfo["kType"] == int(trt.LayerType.ITERATOR): # 29 bExist = False for key, value in dLoop.items(): # find if the Loop already exists in the new network if layerInfo["sName"] in value["IteratorLayerName"]: bExist = True sLoopName = key if not bExist: # not exist, add a new Loop structure for key, value in js["Loop"].items(): if layerInfo["sName"] in value["IteratorLayerName"]: dLoop[key] = {} dLoop[key]["TripLimitLayerName"] = value["TripLimitLayerName"] dLoop[key]["RecurrenceLayerName"] = value["RecurrenceLayerName"] dLoop[key]["LoopOutputLayerName"] = value["LoopOutputLayerName"] dLoop[key]["IteratorLayerName"] = value["IteratorLayerName"] dLoop[key]["RecurrenceLayer"] = [] dLoop[key]["LoopOutputLayer"] = [] dLoop[key]["IteratorLayer"] = [] dLoop[key]["Loop"] = network.add_loop() sLoopName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dLoop[sLoopName]["Loop"].add_iterator(inputTensor, layerInfo["axis"], layerInfo["reverse"]) layer.axis = layerInfo["axis"] #layer.reverse = layerInfo["reverse"] # read only dLoop[sLoopName]["IteratorLayer"].append(layer) # append rather than assign elif layerInfo["kType"] == int(trt.LayerType.LOOP_OUTPUT): # 30 bExist = False for key, value in dLoop.items(): # find if the Loop already exists in the new network if layerInfo["sName"] in value["LoopOutputLayerName"]: bExist = True sLoopName = key if not bExist: # not exist, add a new Loop structure for key, value in js["Loop"].items(): if layerInfo["sName"] in value["LoopOutputLayerName"]: dLoop[key] = {} dLoop[key]["TripLimitLayerName"] = value["TripLimitLayerName"] dLoop[key]["RecurrenceLayerName"] = value["RecurrenceLayerName"] dLoop[key]["LoopOutputLayerName"] = value["LoopOutputLayerName"] dLoop[key]["IteratorLayerName"] = value["IteratorLayerName"] dLoop[key]["RecurrenceLayer"] = [] dLoop[key]["LoopOutputLayer"] = [] dLoop[key]["IteratorLayer"] = [] dLoop[key]["Loop"] = network.add_loop() sLoopName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dLoop[sLoopName]["Loop"].add_loop_output(inputTensor, trt.LoopOutput(layerInfo["kind"]), layerInfo["axis"]) # the optinal second input tensor is recycled in the later additional scan layer.axis = layerInfo["axis"] #layer.kind = trt.LoopOutput(layerInfo["kind"]) # read only dLoop[sLoopName]["LoopOutputLayer"].append(layer) # append rather than assign elif layerInfo["kType"] == int(trt.LayerType.SELECT): # 31 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][2] inputTensor2 = dTensor[tensorName] layer = network.add_select(inputTensor0, inputTensor1, inputTensor2) elif layerInfo["kType"] == int(trt.LayerType.FILL): # 32 layer = network.add_fill([1], trt.FillOperation(layerInfo["operation"])) layer.operation = trt.FillOperation(layerInfo["operation"]) if layerInfo["bDynamicShapeFill"]: tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer.set_input(0, inputTensor) else: layer.shape = layerInfo["shape"] if layerInfo["nInput"] >= 2: tensorName = layerInfo["lInputTensorName"][1] inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) tensorName = layerInfo["lInputTensorName"][2] inputTensor = dTensor[tensorName] layer.set_input(2, inputTensor) if "Range" in layerInfo["sName"]: # The special case: parse Range node from ONNX layer.set_input(1, constantLayer0.get_output(0)) layer.set_input(2, constantLayer1.get_output(0)) elif layerInfo["kType"] == int(trt.LayerType.QUANTIZE): # 33 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_quantize(inputTensor0, inputTensor1) if layerInfo["nInput"] == 3: tensorName = layerInfo["lInputTensorName"][2] inputTensor2 = dTensor[tensorName] layer.set_input(2, inputTensor2) #layer.axis = layerInfo["axis"] # TODO: layerInfo["axis"] is always "-1", but not supported by TensorRT if layerInfo["axis"] != -1: layer.axis = layerInfo["axis"] else: layer.axis = 0 # change it into 0, per-tensor Quantization/Dequantization elif layerInfo["kType"] == int(trt.LayerType.DEQUANTIZE): # 34 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = network.add_dequantize(inputTensor0, inputTensor1) #layer.axis = layerInfo["axis"] # TODO: layerInfo["axis"] is always "-1", but not supported by TensorRT if layerInfo["axis"] != -1: layer.axis = layerInfo["axis"] else: layer.axis = 0 # change it into 0, per-tensor Quantization/Dequantization elif layerInfo["kType"] == int(trt.LayerType.CONDITION): # 35 bExist = False for key, value in dIfCondition.items(): # find if the IfCondition already exists in the new network if value["ConditionLayerIndex"] == i: bExist = True sIfConditionName = key if not bExist: # not exist, add a new IfCondition structure for key, value in js["IfCondition"].items(): if value["InputLayerIndex"] == i: dIfCondition[key] = {} dIfCondition[key]["ConditionLayerIndex"] = i dIfCondition[key]["InputLayerIndex"] = value["InputLayerIndex"] dIfCondition[key]["OutputLayerIndex"] = value["OutputLayerIndex"] dIfCondition[key]["IfCondition"] = network.add_if_conditional() sIfConditionName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dIfCondition[sIfConditionName]["IfCondition"].set_condition(inputTensor) dIfCondition[sIfConditionName]["ConditionLayer"] = layer elif layerInfo["kType"] == int(trt.LayerType.CONDITIONAL_INPUT): # 36 bExist = False for key, value in dIfCondition.items(): # find if the IfCondition already exists in the new network if value["InputLayerIndex"] == i: bExist = True sIfConditionName = key if not bExist: # not exist, add a new IfCondition structure for key, value in js["IfCondition"].items(): if value["InputLayerIndex"] == i: dIfCondition[key] = {} dIfCondition[key]["ConditionLayerIndex"] = value["ConditionLayerIndex"] dIfCondition[key]["InputLayerIndex"] = i dIfCondition[key]["OutputLayerIndex"] = value["OutputLayerIndex"] dIfCondition[key]["IfCondition"] = network.add_if_conditional() sIfConditionName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = dIfCondition[sIfConditionName]["IfCondition"].add_input(inputTensor) dIfCondition[sIfConditionName]["InputLayer"] = layer elif layerInfo["kType"] == int(trt.LayerType.CONDITIONAL_OUTPUT): # 37 bExist = False for key, value in dIfCondition.items(): # find if the IfCondition already exists in the new network if value["OutputLayerIndex"] == i: bExist = True sIfConditionName = key if not bExist: # not exist, add a new IfCondition structure for key, value in js["IfCondiftion"].items(): if value["InputLayerIndex"] == i: dIfCondition[key] = {} dIfCondition[key]["ConditionLayerIndex"] = value["ConditionLayerIndex"] dIfCondition[key]["InputLayerIndex"] = value["InputLayerIndex"] dIfCondition[key]["OutputLayerIndex"] = i dIfCondition[key]["IfCondition"] = network.add_if_conditional() sIfConditionName = key break tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] layer = dIfCondition[sIfConditionName]["IfCondition"].add_output(inputTensor0, inputTensor1) dIfCondition[sIfConditionName]["InputLayer"] = layer elif layerInfo["kType"] == int(trt.LayerType.SCATTER): # 38 tensorName = layerInfo["lInputTensorName"][0] inputTensor0 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][1] inputTensor1 = dTensor[tensorName] tensorName = layerInfo["lInputTensorName"][2] inputTensor2 = dTensor[tensorName] layer = network.add_scatter(inputTensor0, inputTensor1, inputTensor2, trt.ScatterMode.ELEMENT) layer.axis = layerInfo["axis"] layer.mode = trt.ScatterMode(layerInfo["mode"]) elif layerInfo["kType"] == int(trt.LayerType.EINSUM): # 39 inputTensorList = [] for j in range(layerInfo["nInput"]): tensorName = layerInfo["lInputTensorName"][j] inputTensorList.append(dTensor[tensorName]) layer = network.add_einsum(inputTensorList, layerInfo["equation"]) layer.equation = layerInfo["equation"] elif layerInfo["kType"] == int(trt.LayerType.ASSERTION): # 40 tensorName = layerInfo["lInputTensorName"][0] inputTensor = dTensor[tensorName] layer = network.add_assertion(inputTensor, "Error message") layer.message = layerInfo["message"] # Common part of each layer layer.name = layerInfo["sName"] if layerInfo["bPrecisionIsSet"]: layer.precision = trt.DataType(layerInfo["kPrecision"]) for j in range(layerInfo["nOutput"]): #layer.set_output_type(j, trt.DataType(layerInfo["lOutputTensorDataType"][j])) # remove the use of set_output_type outputTensor = layer.get_output(j) referenceTensor = js["Tensor"][layerInfo["lOutputTensorName"][j]] outputTensor.name = layerInfo["lOutputTensorName"][j] outputTensor.dtype = trt.DataType(referenceTensor["kDataType"]) layer.set_output_type(j, trt.DataType(trt.DataType(referenceTensor["kDataType"]))) # Use data type of referenceTensor as standard outputTensor.location = trt.TensorLocation(referenceTensor["kLocation"]) if outputTensor.dtype == trt.DataType.FLOAT and referenceTensor["nAllowedFormat"] != 8191: # The default value of a tensor's allowed_formats is 8191, meaning no more constraint is set formatBitMask = referenceTensor["nAllowedFormat"] & \ (1 << int(trt.TensorFormat.LINEAR) | 1 << int(trt.TensorFormat.CHW32) | 1 << int(trt.TensorFormat.HWC)) elif outputTensor.dtype == trt.DataType.HALF and referenceTensor["nAllowedFormat"] != 8191: formatBitMask = referenceTensor["nAllowedFormat"] & \ (1 << int(trt.TensorFormat.LINEAR) | 1 << int(trt.TensorFormat.CHW2) | 1 << int(trt.TensorFormat.HWC8) | \ 1 << int(trt.TensorFormat.CHW4) | 1 << int(trt.TensorFormat.CHW16) | 1 << int(trt.TensorFormat.CHW32) | \ 1 << int(trt.TensorFormat.DHWC8) | 1 << int(trt.TensorFormat.CDHW32) | 1 << int(trt.TensorFormat.HWC16)) elif outputTensor.dtype == trt.DataType.INT32 and referenceTensor["nAllowedFormat"] != 8191: formatBitMask = referenceTensor["nAllowedFormat"] & \ (1 << int(trt.TensorFormat.LINEAR) | 1 << int(trt.TensorFormat.CHW32)) elif outputTensor.dtype == trt.DataType.INT8 and referenceTensor["nAllowedFormat"] != 8191: formatBitMask = referenceTensor["nAllowedFormat"] & \ (1 << int(trt.TensorFormat.LINEAR) | 1 << int(trt.TensorFormat.CHW4) | 1 << int(trt.TensorFormat.CHW32) | 1 << int(trt.TensorFormat.CDHW32)) else: # bool formatBitMask = referenceTensor["nAllowedFormat"] & \ (1 << int(trt.TensorFormat.LINEAR)) outputTensor.allowed_formats = formatBitMask if referenceTensor["lDynamicRange"] is not None: outputTensor.dynamic_range = referenceTensor["lDynamicRange"] dTensor[outputTensor.name] = outputTensor # Addition scan, recycle the second input tensor of Shuffle layer for key, value in dLateLayerTensor.items(): layer = network.get_layer(i) if tensorName in dTensor.keys(): inputTensor = dTensor[tensorName] layer.set_input(1, inputTensor) else: print("Error finding tensor %s" % tensorName) # Addition scan, recycle the second input tensor of recurrence layer or output lauer in Loop structure for key, value in dLoop.items(): for recurrenceLayer in dLoop[key]["RecurrenceLayer"]: for i in range(js["Network"]["nLayer"]): if js["Layer"][i]["sName"] == recurrenceLayer.name: tensorName = js["Layer"][i]["lInputTensorName"][1] break inputTensor = dTensor[tensorName] recurrenceLayer.set_input(1, inputTensor) for outputLayer in dLoop[key]["LoopOutputLayer"]: if outputLayer.kind == trt.LoopOutput.LAST_VALUE: # only CONCATENTE and REVERSE mode need the second input tensor continue for i in range(js["Network"]["nLayer"]): if js["Layer"][i]["sName"] == outputLayer.name: tensorName = js["Layer"][i]["lInputTensorName"][1] break inputTensor = dTensor[tensorName] outputLayer.set_input(1, inputTensor) # mark output tensor for i in range(js["Network"]["nInput"], js["Network"]["nInput"] + js["Network"]["nOutput"]): tensorName = js["Network"]["Binding"][i]["sName"] outputTensor = dTensor[tensorName] assert (outputTensor.name in js["Tensor"]) network.mark_output(outputTensor) # BuilderConfig if bPrintInformation: for key in js["BuilderConfig"].keys(): print("js[\"BuilderConfig\"][\"%s\"] = %s" % (key, js["BuilderConfig"][key])) config = builder.create_builder_config() if int(trt.__version__.split(".")[0]) < 8: # deprecated since TensorRT 8 config.max_workspace_size = js["BuilderConfig"]["nMaxWorkspaceSize"] else: config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, js["BuilderConfig"]["nMemoryPoolLimit"]["WORKSPACE"]) config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, js["BuilderConfig"]["nMemoryPoolLimit"]["DLA_MANAGED_SRAM"]) config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, js["BuilderConfig"]["nMemoryPoolLimit"]["DLA_LOCAL_DRAM"]) config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, js["BuilderConfig"]["nMemoryPoolLimit"]["DLA_GLOBAL_DRAM"]) config.flags = js["BuilderConfig"]["nFlag"] config.quantization_flags = js["BuilderConfig"]["nQuantizationFlag"] config.engine_capability = trt.EngineCapability(js["BuilderConfig"]["kEngineCapability"]) config.profile_stream = js["BuilderConfig"]["nProfileStream"] config.profiling_verbosity = trt.ProfilingVerbosity(js["BuilderConfig"]["kProfilingVerbosity"]) config.avg_timing_iterations = js["BuilderConfig"]["nAverageTimingIteration"] config.set_tactic_sources(js["BuilderConfig"]["nTacticSource"]) for i in range(js["BuilderConfig"]["nOptimizationProfile"]): op = js["BuilderConfig"]["lOptimizationProfile"][i] optimizationProfile = builder.create_optimization_profile() for j in range(network.num_inputs): if op[j] == {}: continue elif op[j]["bShapeTensor"]: optimizationProfile.set_shape_input(op[j]["name"], op[j]["min"], op[j]["opt"], op[j]["max"]) else: optimizationProfile.set_shape(op[j]["name"], op[j]["min"], op[j]["opt"], op[j]["max"]) config.add_optimization_profile(optimizationProfile) # print network before building if bPrintInformation: print("\nFinal network:") for i in range(network.num_layers): layer = network.get_layer(i) print("%4d->%s,in=%d,out=%d,%s" % (i, str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name)) for j in range(layer.num_inputs): tensor = layer.get_input(j) if tensor == None: print("\tInput %2d:" % j, "None") else: print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) for j in range(layer.num_outputs): tensor = layer.get_output(j) if tensor == None: print("\tOutput %2d:" % j, "None") else: print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) return builder.build_serialized_network(network, config)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkInspector/NetworkRebuilder.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkInspector/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import numpy as np import tensorrt as trt trtFile = "./model.plan" shape = [1, 1, 28, 28] os.system("rm -rf ./*.plan") logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED # use profiling_verbosity to get more information inputTensor = network.add_input("inputT0", trt.float32, [-1] + shape[1:]) profile.set_shape(inputTensor.name, [1] + shape[1:], [2] + shape[1:], [4] + shape[1:]) config.add_optimization_profile(profile) w = np.ascontiguousarray(np.random.rand(32, 1, 5, 5).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(32, 1, 1).astype(np.float32)) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(np.random.rand(64, 32, 5, 5).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(64, 1, 1).astype(np.float32)) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(np.random.rand(64 * 7 * 7, 1024).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(1, 1024).astype(np.float32)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(np.random.rand(1024, 10).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(1, 10).astype(np.float32)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) #------------------------------------------------------------------------------- print("Succeeded building network!") #del engineString, engine, context from NetworkInspector import inspectNetwork from NetworkRebuilder import rebuildNetwork if "profile" not in locals().keys(): inspectNetwork(builder, config, network) else: inspectNetwork(builder, config, network, [profile]) # seems ugly if we can not get optimization profile from BuilderConfig engineString = rebuildNetwork(logger) with open(trtFile, "wb") as f: f.write(engineString) print("Succeeded saving .plan file!") engine = trt.Runtime(logger).deserialize_cuda_engine(engineString)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkInspector/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import ctypes import os import numpy as np import tensorrt as trt from cuda import cudart soFile = "./AddScalarPlugin.so" np.random.seed(31193) def printArrayInformation(x, info="", n=5): if 0 in x.shape: print('%s:%s' % (info, str(x.shape))) print() return print( '%s:%s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \ info,str(x.shape),np.sum(abs(x)),np.var(x),np.max(x),np.min(x),np.sum(np.abs(np.diff(x.reshape(-1)))) )) print('\t', x.reshape(-1)[:n], x.reshape(-1)[-n:]) def check(a, b, weak=False, checkEpsilon=1e-5): if weak: a = a.astype(np.float32) b = b.astype(np.float32) res = np.all(np.abs(a - b) < checkEpsilon) else: res = np.all(a == b) diff0 = np.max(np.abs(a - b)) diff1 = np.max(np.abs(a - b) / (np.abs(b) + checkEpsilon)) print("check:%s, absDiff=%f, relDiff=%f" % (res, diff0, diff1)) def addScalarCPU(inputH, scalar): return [inputH[0] + scalar] def getAddScalarPlugin(scalar): for c in trt.get_plugin_registry().plugin_creator_list: #print(c.name) if c.name == "AddScalar": parameterList = [] parameterList.append(trt.PluginField("scalar", np.float32(scalar), trt.PluginFieldType.FLOAT32)) return c.create_plugin(c.name, trt.PluginFieldCollection(parameterList)) return None shape = [32, 32] scalar = 3 testCase = "<shape=%s,scalar=%f>" % (shape, scalar) trtFile = "./model-Dim%s.plan" % str(len(shape)) print("Test %s" % testCase) logger = trt.Logger(trt.Logger.ERROR) trt.init_libnvinfer_plugins(logger, '') ctypes.cdll.LoadLibrary(soFile) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, [-1 for i in shape]) profile.set_shape(inputT0.name, [1 for i in shape], [8 for i in shape], [32 for i in shape]) config.add_optimization_profile(profile) pluginLayer = network.add_plugin_v2([inputT0], getAddScalarPlugin(scalar)) network.mark_output(pluginLayer.get_output(0)) #------------------------------------------------------------------------------- print("Succeeded building network!") #del engineString, engine, context from NetworkInspector import inspectNetwork from NetworkRebuilder import rebuildNetwork if "profile" not in locals().keys(): inspectNetwork(builder, config, network) else: inspectNetwork(builder, config, network, [profile]) # seems ugly if we can not get optimization profile from BuilderConfig engineString = rebuildNetwork(logger) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() #context.set_input_shape(lTensorName[0], data.shape) #context.set_binding_shape(0, data.shape) #context.set_shape_input(0, data) data = np.ones([8] + shape, dtype=np.float32) bufferH = [] for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkInspector/UnitTestTemplate.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import json import numpy as np import tensorrt as trt def extractBuilder(builder, builderConfig, network): dBuilder = {} # Dictionary of Builder dBuilder["nMaxThread"] = builder.max_threads dBuilder["bPlatformHasTF32"] = builder.platform_has_tf32 dBuilder["bPlatformHasFastFP16"] = builder.platform_has_fast_fp16 dBuilder["bPlatformHasFastINT8"] = builder.platform_has_fast_int8 dBuilder["nMaxDLABatchSize"] = builder.max_DLA_batch_size dBuilder["nDLACore"] = builder.num_DLA_cores dBuilder["bNetworkSupported"] = builder.is_network_supported(network, builderConfig) if int(trt.__version__.split(".")[0]) < 8: # deprecated since TensorRT 8 dBuilder["nMaxBatchSize"] = builder.max_batch_size dBuilder["nMaxWorkspaceSize"] = builder.max_workspace_size return dBuilder def extractBuilderConfig(builderConfig, network, lOptimizationProfile): dBuilderConfig = {} # Dictionary of BuilderConfig if int(trt.__version__.split(".")[0]) < 8: # deprecated since TensorRT 8 dBuilderConfig["nMaxWorkspaceSize"] = builderConfig.max_workspace_size else: dMemory = {} # Dictionary of Memory management dMemory["WORKSPACE"] = builderConfig.get_memory_pool_limit(trt.MemoryPoolType.WORKSPACE) dMemory["DLA_MANAGED_SRAM"] = builderConfig.get_memory_pool_limit(trt.MemoryPoolType.DLA_MANAGED_SRAM) dMemory["DLA_LOCAL_DRAM"] = builderConfig.get_memory_pool_limit(trt.MemoryPoolType.DLA_LOCAL_DRAM) dMemory["DLA_GLOBAL_DRAM"] = builderConfig.get_memory_pool_limit(trt.MemoryPoolType.DLA_GLOBAL_DRAM) dBuilderConfig["nMemoryPoolLimit"] = dMemory dBuilderConfig["kDefaultDeviceType"] = int(builderConfig.default_device_type) # save as int dBuilderConfig["nDLACore"] = builderConfig.DLA_core dBuilderConfig["kEngineCapability"] = int(builderConfig.engine_capability) # save as int dBuilderConfig["nFlag"] = builderConfig.flags # save as bit mask dBuilderConfig["nQuantizationFlag"] = int(builderConfig.quantization_flags) # save as int dBuilderConfig["nOptimizationProfile"] = builderConfig.num_optimization_profiles dBuilderConfig["nProfileStream"] = builderConfig.profile_stream dBuilderConfig["kProfilingVerbosity"] = int(builderConfig.profiling_verbosity) # save as int dBuilderConfig["nAverageTimingIteration"] = builderConfig.avg_timing_iterations dBuilderConfig["nTacticSource"] = builderConfig.get_tactic_sources() # save as bit mask #dBuilderConfig["int8_calibrator"] = builderConfig.int8_calibrator # TODO #dBuilderConfig["algorithmSelector"] = builderConfig.algorithm_selector # TODO #dBuilderConfig["get_device_type"] = builderConfig.get_device_type() # TODO, layer related #dBuilderConfig["bCanRunOnDLA"] = builderConfig.can_run_on_DLA # TODO, layer related lAllOP = [] # List of All set of Optimization Profile if lOptimizationProfile is not None: assert (len(lOptimizationProfile) == builderConfig.num_optimization_profiles) for i in range(builderConfig.num_optimization_profiles): optimizationProfile = lOptimizationProfile[i] lOP = [] # List of one set of Optimization Profile for j in range(network.num_inputs): tensor = network.get_input(j) if tensor.is_shape_tensor: shapeList = optimizationProfile.get_shape_input(tensor.name) else: shapeList = optimizationProfile.get_shape(tensor.name) if shapeList == []: print("[INFO from NetowrkInspector]: No profile for input tensor %d, continue" % j) lOP.append({}) # place holder for input tensor j else: dOP = {} # Dictionary of Optimization Profile for one input tensor dOP["name"] = tensor.name dOP["bShapeTensor"] = tensor.is_shape_tensor dOP["nDimension"] = len(tensor.shape) dOP["min"] = list(shapeList[0]) dOP["opt"] = list(shapeList[1]) dOP["max"] = list(shapeList[2]) lOP.append(dOP) lAllOP.append(lOP) dBuilderConfig["lOptimizationProfile"] = lAllOP lOP = [] # List of whole sets of CalibrationProfile calibrationProfile = builderConfig.get_calibration_profile() if calibrationProfile is not None: for j in range(network.num_inputs): name = network.get_input(j).name shapeList = calibrationProfile.get_shape(name) dOP = {} # Dictionary of CalibrationProfile for only one single input tensor dOP["name"] = name dOP["min"] = list(shapeList[0]) dOP["opt"] = list(shapeList[1]) dOP["max"] = list(shapeList[2]) lOP.append(dOP) dBuilderConfig["lCalibrationProfile"] = lOP return dBuilderConfig def extractNetwork(network): dNetwork = {} # Dictionary of Network dNetwork["sName"] = network.name dNetwork["nLayer"] = network.num_layers dNetwork["nInput"] = network.num_inputs dNetwork["nOutput"] = network.num_outputs dNetwork["bImplicitBatchMode"] = network.has_implicit_batch_dimension dNetwork["bExplicitPrecision"] = network.has_explicit_precision lBinding = [] # List of Binding for i in range(network.num_inputs): tensor = network.get_input(i) dBinding = {} # Dictionary of Binding dBinding["sName"] = tensor.name dBinding["bInput"] = tensor.is_network_input dBinding["bShapeTensor"] = tensor.is_shape_tensor lBinding.append(dBinding) for i in range(network.num_outputs): tensor = network.get_output(i) dBinding = {} dBinding["sName"] = tensor.name dBinding["bInput"] = tensor.is_network_input dBinding["bShapeTensor"] = tensor.is_shape_tensor lBinding.append(dBinding) dNetwork["Binding"] = lBinding return dNetwork def exactTensor(tensor): dTensor = {} # Dicitonary of TEnsor dTensor["lShape"] = list(tensor.shape) # save as list dTensor["kLocation"] = int(tensor.location) # save as int dTensor["bBroadcastAcrossBatch"] = tensor.broadcast_across_batch # useless in Explicit Batch mode dTensor["kDataType"] = int(tensor.dtype) # save as int dTensor["nAllowedFormat"] = tensor.allowed_formats # save as bit mask dTensor["lDynamicRange"] = None if tensor.dynamic_range is None else list(tensor.dynamic_range) # save as list dTensor["bExecutionTensor"] = tensor.is_execution_tensor dTensor["bShapeTensor"] = tensor.is_shape_tensor dTensor["bNetworkInput"] = tensor.is_network_input dTensor["bNetworkOutput"] = tensor.is_network_output return dTensor def exactLayerAndTensor(network): lLayer = [] # List of Layer, layers are indexed by serial number dTensor = {} # Dictionary of Tensor, tensors are indexed by name, not by serial number dIfCondition = {} # Dictionary of IfCondition structure dLoop = {} # Dictionary of Loop structure parameter = {} # weight of each layer for i in range(network.num_layers): layer = network.get_layer(i) dLayer = {} # Dictionary of one layer dLayer["kIndex"] = i dLayer["sName"] = layer.name dLayer["kType"] = int(layer.type) dLayer["nInput"] = layer.num_inputs dLayer["nOutput"] = layer.num_outputs dLayer["kPrecision"] = int(layer.precision) # save as int dLayer["bPrecisionIsSet"] = layer.precision_is_set lInputTensor = [] # List of Input Tensor for j in range(layer.num_inputs): tensor = layer.get_input(j) if layer.type == trt.LayerType.FILL and j == 0 and tensor is None: # for linspace fill mode of Fill layer, inputTensor 0 could be None lInputTensor.append(None) elif layer.type == trt.LayerType.SLICE and j < layer.num_inputs - 1 and tensor is None: # for Slice layer, input tensors before the last one could be None lInputTensor.append(None) elif layer.type == trt.LayerType.RNN_V2 and j >= 1 and tensor == None: # for RNNV2 layer, seq_lengths / hidden_state / cell_state tensor could be None lInputTensor.append(None) else: lInputTensor.append(tensor.name) if not tensor.name in dTensor.keys(): dTensor[tensor.name] = exactTensor(tensor) dLayer["lInputTensorName"] = lInputTensor lOutputTensor = [] # List of Output Tensor lOutputTensorDataType = [] # List of Output Tensor Data Type for j in range(layer.num_outputs): tensor = layer.get_output(j) lOutputTensor.append(tensor.name) lOutputTensorDataType.append(int(layer.get_output_type(j))) if not tensor.name in dTensor.keys(): dTensor[tensor.name] = exactTensor(tensor) dLayer["lOutputTensorName"] = lOutputTensor dLayer["lOutputTensorDataType"] = lOutputTensorDataType # Specialization of each layer # 0 LayerType.CONVOLUTION # 1 LayerType.FULLY_CONNECTED # 2 LayerType.ACTIVATION # 3 LayerType.POOLING # 4 LayerType.LRN # 5 LayerType.SCALE # 6 LayerType.SOFTMAX # 7 LayerType.DECONVOLUTION # 8 LayerType.CONCATENATION # 9 LayerType.ELEMENTWISE # 10 LayerType.PLUGIN # 11 LayerType.UNARY # 12 LayerType.PADDING # 13 LayerType.SHUFFLE # 14 LayerType.REDUCE # 15 LayerType.TOPK # 16 LayerType.GATHER # 17 LayerType.MATRIX_MULTIPLY # 18 LayerType.RAGGED_SOFTMAX # 19 LayerType.CONSTANT # 20 LayerType.RNN_V2 # 21 LayerType.IDENTITY # 22 LayerType.PLUGIN_V2 # 23 LayerType.SLICE # 24 LayerType.SHAPE # 25 LayerType.PARAMETRIC_RELU # 26 LayerType.RESIZE # 27 LayerType.TRIP_LIMIT # 28 LayerType.RECURRENCE # 29 LayerType.ITERATOR # 30 LayerType.LOOP_OUTPUT # 31 LayerType.SELECT # 32 LayerType.FILL # 33 LayerType.QUANTIZE # 34 LayerType.DEQUANTIZE # 35 LayerType.CONDITION # 36 LayerType.CONDITIONAL_INPUT # 37 LayerType.CONDITIONAL_OUTPUT # 38 LayerType.SCATTER # 39 LayerType.EINSUM # 40 LayerType.ASSERTION if layer.type == trt.LayerType.CONVOLUTION: # 0 layer.__class__ = trt.IConvolutionLayer dLayer["kernel"] = layer.name + "-kernel" dLayer["lKernelShape"] = [layer.num_output_maps, layer.get_input(0).shape[1], *list(layer.kernel_size_nd)] parameter[layer.name + "-kernel"] = layer.kernel dLayer["bias"] = layer.name + "-bias" dLayer["lBiasShape"] = list(layer.bias.shape) parameter[layer.name + "-bias"] = layer.bias #dLayer["kernel_size"] = list(layer.kernel_size) # deprecated since TensorRT 8 dLayer["kernel_size_nd"] = list(layer.kernel_size_nd) # save as list dLayer["num_output_maps"] = layer.num_output_maps #dLayer["stride"] = list(layer.stride) # deprecated since TensorRT 8 dLayer["stride_nd"] = list(layer.stride_nd) # save as list #dLayer["dilation"] = list(layer.dilation) # deprecated since TensorRT 8 dLayer["dilation_nd"] = list(layer.dilation_nd) # save as list dLayer["num_groups"] = layer.num_groups #dLayer["padding"] = layer.padding # deprecated since TensorRT 8 dLayer["padding_nd"] = list(layer.padding_nd) # save as list dLayer["padding_mode"] = int(layer.padding_mode) # save as int dLayer["pre_padding"] = list(layer.pre_padding) # save as list dLayer["post_padding"] = list(layer.post_padding) # save as list elif layer.type == trt.LayerType.FULLY_CONNECTED: # 1 layer.__class__ = trt.IFullyConnectedLayer dLayer["kernel"] = layer.name + "-kernel" dLayer["lKernelShape"] = [layer.num_output_channels, layer.kernel.shape[0] // layer.num_output_channels] parameter[layer.name + "-kernel"] = layer.kernel dLayer["bias"] = layer.name + "-bias" dLayer["lBiasShape"] = list(layer.bias.shape) parameter[layer.name + "-bias"] = layer.bias dLayer["num_output_channels"] = layer.num_output_channels elif layer.type == trt.LayerType.ACTIVATION: # 2 layer.__class__ = trt.IActivationLayer dLayer["alpha"] = layer.alpha dLayer["beta"] = layer.beta dLayer["type"] = int(layer.type) # save as int elif layer.type == trt.LayerType.POOLING: # 3 layer.__class__ = trt.IPoolingLayer dLayer["average_count_excludes_padding"] = layer.average_count_excludes_padding dLayer["blend_factor"] = layer.blend_factor #dLayer["stride"] = list(layer.stride) # deprecated since TensorRT 8 dLayer["stride_nd"] = list(layer.stride_nd) # save as list #dLayer["padding"] = layer.padding # deprecated since TensorRT 8 dLayer["padding_nd"] = list(layer.padding_nd) # save as list dLayer["padding_mode"] = int(layer.padding_mode) # save as int dLayer["pre_padding"] = list(layer.pre_padding) # save as list dLayer["post_padding"] = list(layer.post_padding) # save as list dLayer["type"] = int(layer.type) # save as int #dLayer["window_size"] = list(layer.window_size) # deprecated since TensorRT 8 dLayer["window_size_nd"] = list(layer.window_size_nd) # save as list elif layer.type == trt.LayerType.LRN: # 4 layer.__class__ = trt.ILRNLayer dLayer["alpha"] = layer.alpha dLayer["beta"] = layer.beta dLayer["k"] = layer.k dLayer["window_size"] = layer.window_size elif layer.type == trt.LayerType.SCALE: # 5 layer.__class__ = trt.IScaleLayer dLayer["channel_axis"] = layer.channel_axis dLayer["mode"] = int(layer.mode) # save as int dLayer["scale"] = layer.name + "-scale" dLayer["lScaleShape"] = layer.scale.shape parameter[layer.name + "-scale"] = layer.scale dLayer["shift"] = layer.name + "-shift" dLayer["lShiftShape"] = layer.shift.shape parameter[layer.name + "-shift"] = layer.shift dLayer["power"] = layer.name + "-power" dLayer["lPowerShape"] = layer.power.shape parameter[layer.name + "-power"] = layer.power elif layer.type == trt.LayerType.SOFTMAX: # 6 layer.__class__ = trt.ISoftMaxLayer dLayer["axes"] = layer.axes elif layer.type == trt.LayerType.DECONVOLUTION: # 7 layer.__class__ = trt.IDeconvolutionLayer dLayer["kernel"] = layer.name + "-kernel" dLayer["lKernelShape"] = [layer.num_output_maps, layer.get_input(0).shape[1], *list(layer.kernel_size_nd)] parameter[layer.name + "-kernel"] = layer.kernel dLayer["bias"] = layer.name + "-bias" dLayer["lBiasShape"] = list(layer.bias.shape) parameter[layer.name + "-bias"] = layer.bias #dLayer["kernel_size"] = list(layer.kernel_size) # deprecated since TensorRT 8 dLayer["kernel_size_nd"] = list(layer.kernel_size_nd) # save as list dLayer["num_output_maps"] = layer.num_output_maps #dLayer["stride"] = list(layer.stride) # deprecated since TensorRT 8 dLayer["stride_nd"] = list(layer.stride_nd) # save as list #dLayer["dilation"] = list(layer.dilation) # deprecated since TensorRT 8 dLayer["dilation_nd"] = list(layer.dilation_nd) # save as list dLayer["num_groups"] = layer.num_groups #dLayer["padding"] = list(layer.padding) # deprecated since TensorRT 8 dLayer["padding_nd"] = list(layer.padding_nd) # save as list dLayer["padding_mode"] = int(layer.padding_mode) # save as int dLayer["pre_padding"] = list(layer.pre_padding) # save as list dLayer["post_padding"] = list(layer.post_padding) # save as list elif layer.type == trt.LayerType.CONCATENATION: # 8 layer.__class__ = trt.IConcatenationLayer dLayer["axis"] = layer.axis elif layer.type == trt.LayerType.ELEMENTWISE: # 9 layer.__class__ = trt.IElementWiseLayer dLayer["op"] = int(layer.op) # save as int elif layer.type == trt.LayerType.PLUGIN: # 10 print("IPlugin Layer not supported!") # layer.__class__ = trt.IPluginLayer #break elif layer.type == trt.LayerType.UNARY: # 11 layer.__class__ = trt.IUnaryLayer dLayer["op"] = int(layer.op) # save as int elif layer.type == trt.LayerType.PADDING: # 12 layer.__class__ = trt.IPaddingLayer #dLayer["pre_padding"] = list(layer.pre_padding) # deprecated since TensorRT 8 dLayer["pre_padding_nd"] = list(layer.pre_padding_nd) # save as list, different from Convolution / Deconvolution Layer #dLayer["post_padding"] = layer.post_padding # deprecated since TensorRT 8 # different from Convolution / Deconvolution Layer dLayer["post_padding_nd"] = list(layer.post_padding_nd) # save as list elif layer.type == trt.LayerType.SHUFFLE: # 13 layer.__class__ = trt.IShuffleLayer if layer.num_inputs == 2: # dynamic shuffle mode dLayer["bDynamicShuffle"] = True else: dLayer["bDynamicShuffle"] = False try: dLayer["reshape_dims"] = list(layer.reshape_dims) # save as list except ValueError: dLayer["reshape_dims"] = None # no reshape operation if ValueError raised dLayer["first_transpose"] = list(layer.first_transpose) # save as list dLayer["second_transpose"] = list(layer.second_transpose) # save as list dLayer["zero_is_placeholder"] = layer.zero_is_placeholder elif layer.type == trt.LayerType.REDUCE: # 14 layer.__class__ = trt.IReduceLayer dLayer["axes"] = layer.axes dLayer["op"] = int(layer.op) # save as int dLayer["keep_dims"] = layer.keep_dims elif layer.type == trt.LayerType.TOPK: # 15 layer.__class__ = trt.ITopKLayer dLayer["axes"] = layer.axes dLayer["op"] = int(layer.op) # save as int dLayer["k"] = layer.k elif layer.type == trt.LayerType.GATHER: # 16 layer.__class__ = trt.IGatherLayer dLayer["axis"] = layer.axis dLayer["mode"] = int(layer.mode) # save as int elif layer.type == trt.LayerType.MATRIX_MULTIPLY: # 17 layer.__class__ = trt.IMatrixMultiplyLayer dLayer["op0"] = int(layer.op0) # save as int dLayer["op1"] = int(layer.op1) # save as int elif layer.type == trt.LayerType.RAGGED_SOFTMAX: # 18 layer.__class__ = trt.IRaggedSoftMaxLayer elif layer.type == trt.LayerType.CONSTANT: # 19 layer.__class__ = trt.IConstantLayer dLayer["weights"] = layer.name + "-weights" dLayer["lWeightShape"] = list(layer.shape) parameter[layer.name + "-weights"] = layer.weights dLayer["shape"] = list(layer.shape) elif layer.type == trt.LayerType.RNN_V2: # 20 layer.__class__ = trt.IRNNv2Layer dLayer["num_layers"] = layer.num_layers dLayer["hidden_size"] = layer.hidden_size dLayer["max_seq_length"] = layer.max_seq_length dLayer["data_length"] = layer.data_length dLayer["op"] = int(layer.op) # save as int dLayer["input_mode"] = int(layer.input_mode) # save as int dLayer["direction"] = int(layer.direction) # save as int nRealLayer = layer.num_layers * (2 if layer.direction == trt.RNNDirection.BIDIRECTION else 1) if layer.op == trt.RNNOperation.RELU or layer.op == trt.RNNOperation.TANH: lGateKind = [trt.RNNGateType.INPUT] elif layer.op == trt.RNNOperation.LSTM: lGateKind = [trt.RNNGateType.INPUT, trt.RNNGateType.CELL, trt.RNNGateType.FORGET, trt.RNNGateType.OUTPUT] elif layer.op == trt.RNNOperation.GRU: lGateKind = [trt.RNNGateType.UPDATE, trt.RNNGateType.RESET] else: lGateKind = [] for j in range(nRealLayer): for gateKind in lGateKind: if layer.input_mode == trt.RNNInputMode.LINEAR: parameter[layer.name + "-" + str(j) + "-" + str(int(gateKind)) + "-weightX"] = layer.get_weights_for_gate(j, gateKind, True) parameter[layer.name + "-" + str(j) + "-" + str(int(gateKind)) + "-biasX"] = layer.get_bias_for_gate(j, gateKind, True) # bias for X is always needed parameter[layer.name + "-" + str(j) + "-weightH"] = layer.get_weights_for_gate(j, gateKind, False) parameter[layer.name + "-" + str(j) + "-biasH"] = layer.get_bias_for_gate(j, gateKind, False) elif layer.type == trt.LayerType.IDENTITY: # 21 layer.__class__ = trt.IIdentityLayer elif layer.type == trt.LayerType.PLUGIN_V2: # 22 layer.__class__ = trt.IPluginV2Layer print("PluginV2 Layer not support!") #dLayer["plugin_namespace"] = layer.plugin_namespace #dLayer["plugin_type"] = layer.plugin_type #dLayer["plugin_version"] = layer.plugin_version #dLayer["tensorrt_version"] = layer.tensorrt_version elif layer.type == trt.LayerType.SLICE: # 23 layer.__class__ = trt.ISliceLayer dLayer["mode"] = int(layer.mode) # save as int try: dLayer["start"] = list(layer.start) # save as list except ValueError: dLayer["start"] = None try: dLayer["shape"] = list(layer.shape) # save as list except ValueError: dLayer["shape"] = None try: dLayer["stride"] = list(layer.stride) # save as list except ValueError: dLayer["stride"] = None if layer.mode == trt.SliceMode.FILL and layer.num_inputs == 5: dLayer["fill"] = True else: dLayer["fill"] = False elif layer.type == trt.LayerType.SHAPE: # 24 layer.__class__ = trt.IShapeLayer elif layer.type == trt.LayerType.PARAMETRIC_RELU: # 25 layer.__class__ = trt.IParametricReLULayer elif layer.type == trt.LayerType.RESIZE: # 26 layer.__class__ = trt.IResizeLayer if layer.num_inputs == 2: # dynamic resize mode dLayer["bDynamicResize"] = True else: dLayer["bDynamicResize"] = False if layer.scales == []: # static resize mode + use shape mode dLayer["bShapeMode"] = True dLayer["shape"] = list(layer.shape) # save as list else: # static resize mode + use scale mode, TODO: how to check layer.shape? such as "layer.shape == [0] == [0]" dLayer["bShapeMode"] = False dLayer["scales"] = list(layer.scales) # save as list dLayer["resize_mode"] = int(layer.resize_mode) # save as int if layer.resize_mode == trt.ResizeMode.LINEAR and layer.coordinate_transformation == trt.ResizeCoordinateTransformation.ASYMMETRIC: print("[Warning from NetworkInspector]: ResizeCoordinateTransformation of Resize Layer %s is set as HALF_PIXEL though default behaviour or your explicit set is ASYMMETRIC mode, please refer to the source code of NetworkInspector if you insist to use ASYMMETRIC mode!" % layer.name) layer.coordinate_transformation = trt.ResizeCoordinateTransformation.HALF_PIXEL #layer.coordinate_transformation = trt.ResizeCoordinateTransformation.ASYMMETRIC # uncomment this line if you want to use ASYMMETRIC mode dLayer["coordinate_transformation"] = int(layer.coordinate_transformation) # save as int dLayer["selector_for_single_pixel"] = int(layer.selector_for_single_pixel) # save as int dLayer["nearest_rounding"] = int(layer.nearest_rounding) # save as int elif layer.type == trt.LayerType.TRIP_LIMIT: # 27 layer.__class__ = trt.ITripLimitLayer if layer.loop.name not in dLoop.keys(): # search every time because the appearance order of layers in loop is uncertain dLoop[layer.loop.name] = {} dLoop[layer.loop.name]["RecurrenceLayerName"] = [] dLoop[layer.loop.name]["LoopOutputLayerName"] = [] dLoop[layer.loop.name]["IteratorLayerName"] = [] dLoop[layer.loop.name]["TripLimitLayerName"] = layer.name dLayer["kind"] = int(layer.kind) # save as int elif layer.type == trt.LayerType.RECURRENCE: # 28 layer.__class__ = trt.IRecurrenceLayer if layer.loop.name not in dLoop.keys(): # search every time because the appearance order of layers in loop is uncertain dLoop[layer.loop.name] = {} dLoop[layer.loop.name]["RecurrenceLayerName"] = [] dLoop[layer.loop.name]["LoopOutputLayerName"] = [] dLoop[layer.loop.name]["IteratorLayerName"] = [] dLoop[layer.loop.name]["RecurrenceLayerName"].append(layer.name) # a Loop structure could have more than one recurrence layer elif layer.type == trt.LayerType.ITERATOR: # 29 layer.__class__ = trt.IIteratorLayer if layer.loop.name not in dLoop.keys(): # search every time because the appearance order of layers in loop is uncertain dLoop[layer.loop.name] = {} dLoop[layer.loop.name]["RecurrenceLayerName"] = [] dLoop[layer.loop.name]["LoopOutputLayerName"] = [] dLoop[layer.loop.name]["IteratorLayerName"] = [] dLoop[layer.loop.name]["IteratorLayerName"].append(layer.name) # a Loop structure could have more than one iterator layer dLayer["axis"] = layer.axis dLayer["reverse"] = layer.reverse elif layer.type == trt.LayerType.LOOP_OUTPUT: # 30 layer.__class__ = trt.ILoopOutputLayer if layer.loop.name not in dLoop.keys(): # search every time because the appearance order of layers in loop is uncertain dLoop[layer.loop.name] = {} dLoop[layer.loop.name]["RecurrenceLayerName"] = [] dLoop[layer.loop.name]["LoopOutputLayerName"] = [] dLoop[layer.loop.name]["IteratorLayerName"] = [] dLoop[layer.loop.name]["LoopOutputLayerName"].append(layer.name) # a Loop structure could have more than one output layer dLayer["axis"] = layer.axis dLayer["kind"] = int(layer.kind) # save as int elif layer.type == trt.LayerType.SELECT: # 31 layer.__class__ = trt.ISelectLayer elif layer.type == trt.LayerType.FILL: # 32 layer.__class__ = trt.IFillLayer dLayer["operation"] = int(layer.operation) # save as int if layer.get_input(0) is not None: # dynamic fill mode, the shape of output tensor depends on input tenor 0 dLayer["bDynamicShapeFill"] = True dLayer["shape"] = None else: # static fill mode, the shape of output tensor is given by input parameter dLayer["bDynamicShapeFill"] = False dLayer["shape"] = list(layer.shape) # save as list elif layer.type == trt.LayerType.QUANTIZE: # 33 layer.__class__ = trt.IQuantizeLayer dLayer["axis"] = layer.axis elif layer.type == trt.LayerType.DEQUANTIZE: # 34 layer.__class__ = trt.IDequantizeLayer dLayer["axis"] = layer.axis elif layer.type == trt.LayerType.CONDITION: # 35 layer.__class__ = trt.IConditionLayer if layer.conditional.name not in dIfCondition.keys(): # search every time because the appearance order of layers in IfCondition is uncertain dIfCondition[layer.conditional.name] = {} dIfCondition[layer.conditional.name]["ConditionLayerIndex"] = i elif layer.type == trt.LayerType.CONDITIONAL_INPUT: # 36 layer.__class__ = trt.IIfConditionalInputLayer if layer.conditional.name not in dIfCondition.keys(): # search every time because the appearance order of layers in IfCondition is uncertain dIfCondition[layer.conditional.name] = {} dIfCondition[layer.conditional.name]["InputLayerIndex"] = i elif layer.type == trt.LayerType.CONDITIONAL_OUTPUT: # 37 layer.__class__ = trt.IIfConditionalOutputLayer if layer.conditional.name not in dIfCondition.keys(): # search every time because the appearance order of layers in IfCondition is uncertain dIfCondition[layer.conditional.name] = {} dIfCondition[layer.conditional.name]["OutputLayerIndex"] = i elif layer.type == trt.LayerType.SCATTER: # 38 layer.__class__ = trt.IScatterLayer dLayer["axis"] = layer.axis dLayer["mode"] = int(layer.mode) # save as int elif layer.type == trt.LayerType.EINSUM: # 39 layer.__class__ = trt.IEinsumLayer dLayer["equation"] = layer.equation elif layer.type == trt.LayerType.ASSERTION: # 40 layer.__class__ = trt.IAssertionLayer dLayer["message"] = layer.message else: print("Layer not supported!") break lLayer.append(dLayer) return lLayer, dTensor, dIfCondition, dLoop, parameter def inspectNetwork(builder, builderConfig, network, lOptimizationProfile=[], calibrationProfile=None, bPrintInformation=True, jsonFile="./model.json", paraFile="./model.npz"): # print network before parsing if bPrintInformation: print("\nOriginal network:") for i in range(network.num_layers): layer = network.get_layer(i) print("%4d->%s,in=%d,out=%d,%s" % (i, str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name)) for j in range(layer.num_inputs): tensor = layer.get_input(j) if tensor == None: print("\tInput %2d:" % j, "None") else: print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) for j in range(layer.num_outputs): tensor = layer.get_output(j) if tensor == None: print("\tOutput %2d:" % j, "None") else: print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) bigDictionary = {} # Builder, almost useless especially since TensorRT 8 bigDictionary["Builder"] = extractBuilder(builder, builderConfig, network) # BuilderConfig bigDictionary["BuilderConfig"] = extractBuilderConfig(builderConfig, network, lOptimizationProfile) # Network bigDictionary["Network"] = extractNetwork(network) # Layer and Tensor bigDictionary["Layer"], bigDictionary["Tensor"], bigDictionary["IfCondition"], bigDictionary["Loop"], parameter = exactLayerAndTensor(network) # Save result as file with open(jsonFile, "w") as f: f.write(json.dumps(bigDictionary)) np.savez(paraFile, **parameter) return
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkInspector/NetworkInspector.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import cv2 import numpy as np import tensorrt as trt from cuda import cudart np.random.seed(31193) nHeight = 28 nWidth = 28 trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" inferenceImage = dataPath + "8.png" np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() logger = trt.Logger(trt.Logger.ERROR) if os.path.isfile(trtFile): with open(trtFile, "rb") as f: engine = trt.Runtime(logger).deserialize_cuda_engine(f.read()) if engine == None: print("Failed loading engine!") exit() print("Succeeded loading engine!") else: builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, nHeight, nWidth]) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) w = np.ascontiguousarray(np.random.rand(32, 1, 5, 5).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(32, 1, 1).astype(np.float32)) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(np.random.rand(64, 32, 5, 5).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(64, 1, 1).astype(np.float32)) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(np.random.rand(64 * 7 * 7, 1024).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(1, 1024).astype(np.float32)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(np.random.rand(1024, 10).astype(np.float32)) b = np.ascontiguousarray(np.random.rand(1, 10).astype(np.float32)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NsightSystems/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import onnx import onnx_graphsurgeon as gs # Create nodes # use onnx_graphsurgeon.Graph.register() to register a function as a ndoe @gs.Graph.register() def add(self, a, b): return self.layer(op="Add", inputs=[a, b], outputs=["myAdd"]) @gs.Graph.register() def mul(self, a, b): return self.layer(op="Mul", inputs=[a, b], outputs=["myMul"]) @gs.Graph.register() def gemm(self, a, b, isTransposeA=False, isTransposeB=False): attrs = {"transA": int(isTransposeA), "transB": int(isTransposeB)} return self.layer(op="Gemm", inputs=[a, b], outputs=["myGgemm"], attrs=attrs) @gs.Graph.register() def min(self, *args): return self.layer(op="Min", inputs=args, outputs=["myMin"]) @gs.Graph.register() def max(self, *args): return self.layer(op="Max", inputs=args, outputs=["myMax"]) # mark version during register a function as a ndoe @gs.Graph.register(opsets=[11]) def relu(self, a): return self.layer(op="Relu", inputs=[a], outputs=["myReLU"]) # register node with the same name but different version @gs.Graph.register(opsets=[1]) def relu(self, a): raise NotImplementedError("This function has not been implemented!") # Create graph graph = gs.Graph(opset=11) tensor0 = gs.Variable(name="tensor0", shape=[64, 64], dtype=np.float32) tensor1 = gs.Constant(name="tensor1", values=np.ones(shape=(64, 64), dtype=np.float32)) #tensor1 = np.ones(shape=(64, 64), dtype=np.float32) # np.array can also be used but the name of the tensor will be created automatically by ONNX if so tensor2 = gs.Constant(name="tensor2", values=np.ones((64, 64), dtype=np.float32) * 0.5) tensor3 = gs.Constant(name="tensor3", values=np.ones(shape=[64, 64], dtype=np.float32)) tensor4 = gs.Constant(name="tensor4", values=np.array([3], dtype=np.float32)) tensor5 = gs.Constant(name="tensor5", values=np.array([-3], dtype=np.float32)) node0 = graph.gemm(tensor1, tensor0, isTransposeB=True) node1 = graph.add(*node0, tensor2) node2 = graph.relu(*node1) node3 = graph.mul(*node2, tensor3) node4 = graph.min(*node3, tensor4) node5 = graph.max(*node4, tensor5) graph.inputs = [tensor0] graph.outputs = [node5[0]] graph.inputs[0].dtype = np.dtype(np.float32) graph.outputs[0].dtype = np.dtype(np.float32) onnx.save(gs.export_onnx(graph), "model-09-01.onnx") @gs.Graph.register() def replaceWithClip(self, inputs, outputs): # remove the output tensor of the tail node and the input tensor of the head node for inp in inputs: inp.outputs.clear() for out in outputs: out.inputs.clear() # inset new node return self.layer(op="Clip", inputs=inputs, outputs=outputs) temp = graph.tensors() # find the input / outpu tensor that we want to remove, and pass them to function replaceWithClip inputs = [temp["myMul_6"], temp["tensor5"], temp["tensor4"]] outputs = [temp["myMax_10"]] graph.replaceWithClip(inputs, outputs) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-09-02.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/09-BuildModelWithAPI.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, None) tensor2 = gs.Variable("tensor2", np.float32, None) tensor3 = gs.Variable("tensor3", np.float32, None) tensor4 = gs.Variable("tensor4", np.float32, None) node0 = gs.Node("Identity", "Node0", inputs=[tensor0], outputs=[tensor1]) node1 = gs.Node("TrashNode", "Node1", inputs=[tensor1], outputs=[tensor2]) node2 = gs.Node("Identity", "Node2", inputs=[tensor2], outputs=[tensor3]) node3 = gs.Node("Identity", "Node3", inputs=[tensor2], outputs=[tensor4]) graph = gs.Graph(nodes=[node0, node1, node2, node3], inputs=[tensor0], outputs=[tensor3, tensor4]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-03-01.onnx") del graph graph = gs.import_onnx(onnx.load("model-03-01.onnx")) for node in graph.nodes: if node.op == "TrashNode" and node.name == "Node1": inputTensor = node.inputs[0] outputTensor = node.outputs[0] for subNode in graph.nodes: # search all nodes in case of the output tensor is used by multiple nodes if outputTensor in subNode.inputs: index = subNode.inputs.index(outputTensor) subNode.inputs[index] = inputTensor graph.cleanup().toposort() # the TrashNode node will be removed during graph clean onnx.save(gs.export_onnx(graph), "model-03-02.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/03-RemoveNode.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, None) tensor2 = gs.Variable("tensor2", np.float32, None) tensor3 = gs.Variable("tensor3", np.float32, None) constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 1, 1, 1], dtype=np.float32)) node0 = gs.Node("Identity", "myIdentity0", inputs=[tensor0], outputs=[tensor1]) node1 = gs.Node("Add", "myAdd", inputs=[tensor1, constant0], outputs=[tensor2]) node2 = gs.Node("Identity", "myIdentity1", inputs=[tensor2], outputs=[tensor3]) graph = gs.Graph(nodes=[node0, node1, node2], inputs=[tensor0], outputs=[tensor3]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-04-01.onnx") del graph # replace node by edit the operator type graph = gs.import_onnx(onnx.load("model-04-01.onnx")) # load the graph from ONNX file for node in graph.nodes: if node.op == "Add" and node.name == "myAdd": node.op = "Sub" node.name = "mySub" # it's OK to change the name of the node or not graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-04-02.onnx") del graph # repalce node by inserting new node graph = gs.import_onnx(onnx.load("model-04-01.onnx")) # load the graph from ONNX file for node in graph.nodes: if node.op == "Add" and node.name == "myAdd": newNode = gs.Node("Sub", "mySub", inputs=node.inputs, outputs=node.outputs) graph.nodes.append(newNode) node.outputs = [] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-04-03.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/04-ReplaceNode.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) # 3 necessary tensors tensor1 = gs.Variable("tensor1", np.float32, ["B", 3, 64, 64]) tensor2 = gs.Variable("tensor2", np.float32, ["B", 3, 64, 64]) tensor3 = gs.Variable("tensor3", np.float32, ["B", 3, 64, 64]) # 1 fake input tensor tensor4 = gs.Variable("tensor4", np.float32, ["B", 1, 64, 64]) # 1 fake output tensor tensor5 = gs.Variable("tensor5", np.float32, ["B", 1, 64, 64]) # 2 useless tensors tensor6 = gs.Variable("tensor6", np.float32, ["B", 1, 64, 64]) tensor7 = gs.Variable("tensor7", np.float32, None) # 2 intermediate tensors tensor8 = gs.Variable("tensor8", np.float32, None) constant0 = gs.Constant(name="w", values=np.ones(shape=[1, 1, 1, 1], dtype=np.float32)) node0 = gs.Node("Add", "myAdd0", inputs=[constant0, constant0], outputs=[tensor7]) node1 = gs.Node("Add", "myAdd1", inputs=[tensor7, constant0], outputs=[tensor8]) node2 = gs.Node("Add", "myAdd2", inputs=[tensor0, tensor8], outputs=[tensor1]) # necessary node node3 = gs.Node("Add", "myAdd3", inputs=[tensor1, constant0], outputs=[tensor2]) # necessary node node4 = gs.Node("Add", "myAdd4", inputs=[tensor5, constant0], outputs=[tensor6]) # useless node graph = gs.Graph(nodes=[node4, node3, node2, node1, node0], inputs=[tensor0, tensor3], outputs=[tensor2, tensor4]) # reverse the order of the node on purpose onnx.save(gs.export_onnx(graph), "model-06-01.onnx") # original graph, containing 4 tensors without node, 1 node without edge and 1 chain subgraph with constant expresssion onnx.save(gs.export_onnx(graph.fold_constants()), "model-06-02.onnx") # graph after constant folding, the subgraph with constant expression is fused, but the two more Add node are left without edge # notice that constant folding will not remove any nodes onnx.save(gs.export_onnx(graph.fold_constants().cleanup()), "model-06-03.onnx") # graph after clean, the 3 Add nodes without edge are removed print("Before toposort:") # The order of the original graph for index, node in enumerate(graph.nodes): print("No.%d->%s" % (index, node.name)) print("After toposort:") # The order of the last graph graph.toposort() for index, node in enumerate(graph.nodes): print("No.%d->%s" % (index, node.name)) graph.inputs = [tensor0] # remove redundant input / output manually graph.outputs = [tensor2] onnx.save(gs.export_onnx(graph), "model-06-04.onnx") # Notice # + In TensorRT<8.0, redundant input / output tensors in netowrk (maybe from ONNX file) will be removed, so the count of input / output tensor of a TensorRT engine may be different from that in ONNX file # + In TensorRT>=8.0, redundant input / output tensors in network will be retained as useless placeholders in the network
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/06-Fold.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, None) tensor2 = gs.Variable("tensor2", np.float32, None) node0 = gs.Node("Identity", "myIdentity0", inputs=[tensor0], outputs=[tensor1]) node1 = gs.Node("Identity", "myIdentity1", inputs=[tensor1], outputs=[tensor2]) graph = gs.Graph(nodes=[node0, node1], inputs=[tensor0], outputs=[tensor2]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-02-01.onnx") del graph graph = gs.import_onnx(onnx.load("model-02-01.onnx")) # load the graph from ONNX file for node in graph.nodes: if node.op == "Identity" and node.name == "myIdentity0": # find the place we want to add ndoe constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 1, 1, 1], dtype=np.float32)) # construct the new variable and node tensor3 = gs.Variable("tensor3", np.float32, None) newNode = gs.Node("Add", "myAdd", inputs=[node.outputs[0], constant0], outputs=[tensor3]) graph.nodes.append(newNode) # REMEMBER to add the new node into the grap index = node.o().inputs.index(node.outputs[0]) # find the next node node.o().inputs[index] = tensor3 # replace the input tensor of next node as the new tensor graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-02-02.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/02-AddNode.py
#!/usr/bin/env python3 # # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["A", 3, "B", 5]) tensor1 = gs.Variable("tensor1", np.int64, None) tensor2 = gs.Variable("tensor2", np.int64, None) tensor3 = gs.Variable("tensor3", np.float32, None) tensor4 = gs.Variable("tensor4", np.int64, None) tensor5 = gs.Variable("tensor5", np.int64, None) tensor6 = gs.Variable("tensor6", np.int64, None) tensor7 = gs.Variable("tensor7", np.int64, None) tensor8 = gs.Variable("tensor8", np.float32, None) constant0 = gs.Constant("constant0", values=np.array([0, 1], dtype=np.int32)) constant1 = gs.Constant("constant1", values=np.array([2, 3], dtype=np.int32)) node0 = gs.Node("Shape", "myShape", inputs=[tensor0], outputs=[tensor1]) # value=(A,3,B,5), shape=(4,) node1 = gs.Node("ReduceProd", "myReduceProd0", inputs=[tensor1], attrs={"axes": [0], "keepdims": int(True)}, outputs=[tensor2]) # value=(A*3*B*5), shape=() node2 = gs.Node("Reshape", "myReshape0", inputs=[tensor0, tensor2], outputs=[tensor3]) # shape=(A*3*B*5,) node3 = gs.Node("Gather", "myGather0", inputs=[tensor1, constant0], outputs=[tensor4]) # value=(A,3), shape=(2,) node4 = gs.Node("Gather", "myGather1", inputs=[tensor1, constant1], outputs=[tensor5]) # value=(B,5), shape=(2,) node5 = gs.Node("ReduceProd", "myReduceProd1", inputs=[tensor5], attrs={"axes": [0], "keepdims": int(True)}, outputs=[tensor6]) # value=(B*5), shape=() node6 = gs.Node("Concat", "myConcat", inputs=[tensor4, tensor6], attrs={"axis": 0}, outputs=[tensor7]) # value=(A,3,B*5), shape=() node7 = gs.Node("Reshape", "myReshape1", inputs=[tensor0, tensor7], outputs=[tensor8]) # shape=(A*3*B*5,) graph = gs.Graph(nodes=[node0, node1, node2, node3, node4, node5, node6, node7], inputs=[tensor0], outputs=[tensor3, tensor8]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-07-01.onnx") # using Dynamic Shape mode, there are many shape operators in the graph graph.inputs[0].shape = [2, 3, 4, 5] # shape operators can be simplified if the shape is static graph.fold_constants().cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-07-02.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/07-ShapeOperationAndSimplify.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs onnxFile = "./model-05.onnx" nMaxAdjustNode = 256 # Create a ONNX graph with Onnx Graphsurgeon ----------------------------------- tensor0 = gs.Variable("tensor-0", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) graphNodeList = [] tensor1 = gs.Variable("tensor-1", np.float32, None) node1 = gs.Node("Conv", "Conv-1", inputs=[tensor0, constant32x1, constant32], outputs=[tensor1]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor2 = gs.Variable("tensor-2", np.float32, None) node2 = gs.Node("Relu", "ReLU-2", inputs=[tensor1], outputs=[tensor2]) graphNodeList.append(node2) tensor3 = gs.Variable("tensor-3", np.float32, None) node3 = gs.Node("MaxPool", "MaxPool-3", inputs=[tensor2], outputs=[tensor3]) node3.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node3) tensor4 = gs.Variable("tensor-4", np.float32, None) node1 = gs.Node("Conv", "Conv-4", inputs=[tensor3, constant64x32, constant64], outputs=[tensor4]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor5 = gs.Variable("tensor-5", np.float32, None) node5 = gs.Node("Relu", "ReLU-5", inputs=[tensor4], outputs=[tensor5]) graphNodeList.append(node5) tensor6 = gs.Variable("tensor-6", np.float32, None) node6 = gs.Node("MaxPool", "MaxPool-6", inputs=[tensor5], outputs=[tensor6]) node6.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node6) tensor7 = gs.Variable("tensor-7", np.float32, None) node7 = gs.Node("Transpose", "Transpose-7", inputs=[tensor6], outputs=[tensor7], attrs=OrderedDict([("perm", [0, 2, 3, 1])])) graphNodeList.append(node7) tensor8 = gs.Variable("tensor-8", np.float32, None) node8 = gs.Node("Reshape", "Reshape-7", inputs=[tensor7, constantM1Comma3136], outputs=[tensor8]) graphNodeList.append(node8) tensor9 = gs.Variable("tensor-9", np.float32, None) node9 = gs.Node("MatMul", "MatMul-9", inputs=[tensor8, constant3136x1024], outputs=[tensor9]) graphNodeList.append(node9) tensor10 = gs.Variable("tensor-10", np.float32, None) node10 = gs.Node("Add", "Add-10", inputs=[tensor9, constant1024], outputs=[tensor10]) graphNodeList.append(node10) tensor11 = gs.Variable("tensor-11", np.float32, None) node11 = gs.Node("Relu", "ReLU-11", inputs=[tensor10], outputs=[tensor11]) graphNodeList.append(node11) tensor12 = gs.Variable("tensor-12", np.float32, None) node12 = gs.Node("MatMul", "MatMul-12", inputs=[tensor11, constant1024x10], outputs=[tensor12]) graphNodeList.append(node12) tensor13 = gs.Variable("tensor-13", np.float32, None) node13 = gs.Node("Add", "Add-13", inputs=[tensor12, constant10], outputs=[tensor13]) graphNodeList.append(node13) tensor14 = gs.Variable("tensor-14", np.float32, None) node14 = gs.Node("Softmax", "Softmax-14", inputs=[tensor13], outputs=[tensor14], attrs=OrderedDict([("axis", 1)])) graphNodeList.append(node14) tensor15 = gs.Variable("tensor-15", np.int32, None) node15 = gs.Node("ArgMax", "ArgMax-15", inputs=[tensor14], outputs=[tensor15], attrs=OrderedDict([("axis", 1), ("keepdims", 0)])) graphNodeList.append(node15) graph = gs.Graph(nodes=graphNodeList, inputs=[tensor0], outputs=[tensor15]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), onnxFile) print("# Traverse the node: ----------------------------------------------------") # traverser by nodes and print information of node, input / output tensor, name of father / son node for index, node in enumerate(graph.nodes): print("Node%4d: op=%s, name=%s, attrs=%s" % (index, node.op, node.name, "".join(["{"] + [str(key) + ":" + str(value) + ", " for key, value in node.attrs.items()] + ["}"]))) for jndex, inputTensor in enumerate(node.inputs): print("\tInTensor %d: %s" % (jndex, inputTensor)) for jndex, outputTensor in enumerate(node.outputs): print("\tOutTensor %d: %s" % (jndex, outputTensor)) fatherNodeList = [] for i in range(nMaxAdjustNode): try: newNode = node.i(i) fatherNodeList.append(newNode) except: break for jndex, newNode in enumerate(fatherNodeList): print("\tFatherNode%d: %s" % (jndex, newNode.name)) sonNodeList = [] for i in range(nMaxAdjustNode): try: newNode = node.o(i) sonNodeList.append(newNode) except: break for jndex, newNode in enumerate(sonNodeList): print("\tSonNode %d: %s" % (jndex, newNode.name)) print("# Traverse the tensor: --------------------------------------------------") # traverser by tensors and print information of tensor, name of producer / consumer node, name of father / son tensor for index, (name, tensor) in enumerate(graph.tensors().items()): print("Tensor%4d: name=%s, desc=%s" % (index, name, tensor)) for jndex, inputNode in enumerate(tensor.inputs): print("\tInNode %d: %s" % (jndex, inputNode.name)) for jndex, outputNode in enumerate(tensor.outputs): print("\tOutNode %d: %s" % (jndex, outputNode.name)) fatherTensorList = [] for i in range(nMaxAdjustNode): try: newTensor = tensor.i(i) fatherTensorList.append(newTensor) except: break for jndex, newTensor in enumerate(fatherTensorList): print("\tFatherTensor%d: %s" % (jndex, newTensor)) sonTensorList = [] for i in range(nMaxAdjustNode): try: newTensor = tensor.o(i) sonTensorList.append(newTensor) except: break for jndex, newTensor in enumerate(sonTensorList): print("\tSonTensor %d: %s" % (jndex, newTensor))
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/05-PrintGraphInformation.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) # define tensor (variable in ONNX) tensor1 = gs.Variable("tensor1", np.float32, None) # type or shape of the intermediate tensors can be None tensor2 = gs.Variable("tensor2", np.float32, None) tensor3 = gs.Variable("tensor3", np.float32, None) constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 3, 3, 3], dtype=np.float32)) # define constant tensor constant1 = gs.Constant(name="constant1", values=np.ones(shape=[1], dtype=np.float32)) node0 = gs.Node("Conv", "myConv", inputs=[tensor0, constant0], outputs=[tensor1]) # defione node node0.attrs = OrderedDict([["dilations", [1, 1]], ["kernel_shape", [3, 3]], ["pads", [1, 1, 1, 1]], ["strides", [1, 1]]]) # attribution of the node node1 = gs.Node("Add", "myAdd", inputs=[tensor1, constant1], outputs=[tensor2]) node2 = gs.Node("Relu", "myRelu", inputs=[tensor2], outputs=[tensor3]) graph = gs.Graph(nodes=[node0, node1, node2], inputs=[tensor0], outputs=[tensor3]) # define graph graph.cleanup().toposort() # clean the graph before saving as ONNX file onnx.save(gs.export_onnx(graph), "model-01.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/01-CreateModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, ["B", 3, 64, 64]) tensor2 = gs.Variable("tensor2", np.float32, ["B", 3, 64, 64]) tensor3 = gs.Variable("tensor3", np.float32, ["B", 3, 64, 64]) constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 1, 1, 1], dtype=np.float32)) node0 = gs.Node("Identity", "myIdentity0", inputs=[tensor0], outputs=[tensor1]) node1 = gs.Node("Add", "myAdd", inputs=[tensor1, constant0], outputs=[tensor2]) node2 = gs.Node("Identity", "myIdentity1", inputs=[tensor2], outputs=[tensor3]) graph = gs.Graph(nodes=[node0, node1, node2], inputs=[tensor0], outputs=[tensor3]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-08-01.onnx") del graph # mark some tensors in original graph as input / output tensors so that isolate a subgraph graph = gs.import_onnx(onnx.load("model-08-01.onnx")) for node in graph.nodes: if node.op == "Add" and node.name == "myAdd": graph.inputs = [node.inputs[0]] graph.outputs = [node.outputs[0]] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "model-08-02.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/08-IsolateSubgraph.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import sys from collections import OrderedDict from copy import deepcopy import numpy as np import onnx import onnx_graphsurgeon as gs from polygraphy.backend.onnx.loader import fold_constants np.random.seed(31193) onnxFile0 = "model-10.onnx" onnxFile1 = "model-10-01.onnx" onnxFile2 = "model-10-02.onnx" # Constant of 0 dimension constantS0 = gs.Constant("constantS0", np.array(0, dtype=np.int64)) constantS2 = gs.Constant("constantS2", np.array(2, dtype=np.int64)) constantS3 = gs.Constant("constantS3", np.array(3, dtype=np.int64)) # Constant of 1 dimension integer value, MUST use np.ascontiguousarray, or TensorRT will regard the shape of this Constant as (0) !!! constant0 = gs.Constant("constant0", np.ascontiguousarray(np.array([0], dtype=np.int64))) constant1 = gs.Constant("constant1", np.ascontiguousarray(np.array([1], dtype=np.int64))) # Constant of >1 dimension constantWeight = gs.Constant("constantWeight", np.ascontiguousarray(np.random.rand(1 * 1 * 3 * 3).astype(np.float32).reshape([1, 1, 3, 3]))) constantBias = gs.Constant("constantBias", np.ascontiguousarray(np.random.rand(1 * 1 * 1 * 1).astype(np.float32).reshape([1, 1, 1, 1]))) constant307200x64 = gs.Constant("constant307200x256", np.ascontiguousarray(np.random.rand(307200 * 64).astype(np.float32).reshape([307200, 64]))) # Tool function def markGraphOutput(graph, lNode, bMarkOutput=True, bMarkInput=False, lMarkOutput=None, lMarkInput=None, bRemoveOldOutput=True): # graph: The ONNX graph for edition # lNode: The list of nodes we want to mark as output # bMarkOutput: Whether to mark the output tensor(s) of the nodes in the lNode # bMarkInput: Whether to mark the input tensor(s) of the nodes in the lNode # lMarkOutput: The index of output tensor(s) of the node are marked as output, only available when len(lNode) == 1 # lMarkInput: The index of input tensor(s) of the node are marked as output, only available when len(lNode) == 1 # bRemoveOldOutput: Whether to remove the original output of the network (cutting the graph to the node we want to mark to save ytime of building) # In most cases, using the first 4 parameters is enough, for example: #markGraphOutput(graph, ["/Conv"]) # mark output tensor of the node "/Conv" as output #markGraphOutput(graph, ["/Conv"], False, True) # mark input tensors of the node "/Conv" (input tensor + weight + bias) as output #markGraphOutput(graph, ["/TopK"], lMarkOutput=[1]) # mark the second output tensor of the node "/TopK" as output #markGraphOutput(graph, ["/Conv"], bRemoveOldOutput=False) # mark output tensor of the node "/Conv" as output, and keep the original output of the network if bRemoveOldOutput: graph.outputs = [] for node in graph.nodes: if node.name in lNode: if bMarkOutput: if lMarkOutput is None or len(lNode) > 1: lMarkOutput = range(len(node.outputs)) for index in lMarkOutput: graph.outputs.append(node.outputs[index]) node.outputs[index].dtype = np.dtype(np.float32) print("[M] Mark node [%s] output tensor [%s]" % (node.name, node.outputs[index].name)) if bMarkInput: if lMarkInput is None or len(lNode) > 1: lMarkInput = range(len(node.inputs)) for index in lMarkInput: graph.outputs.append(node.inputs[index]) print("[M] Mark node [%s] input tensor [%s]" % (node.name, node.inputs[index].name)) graph.cleanup().toposort() return len(lNode) def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor!! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) nodeName = prefix + "-N-" + str(number) + "-" + nodeType tensorName = prefix + "-V-" + str(number) + "-" + nodeType + (("-" + suffix) if len(suffix) > 0 else "") tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=(OrderedDict() if attribution is None else attribution)) graph.nodes.append(node) return tensor, number + 1 def addNodeMultipleOutput(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtypeList=None, shapeList=None): # ONLY for the node with multiple tensor!! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtypeList: The list of the data type of the output tensor (optional) # shapeList: The list of the shape of the output tensor (optional) nodeName = prefix + "-N-" + str(number) + "-" + nodeType assert len(dtypeList) == len(shapeList) outputList = [] for i in range(len(dtypeList)): tensorName = prefix + "-V-" + str(number) + "-" + nodeType + "-" + str(i) + (("-" + suffix) if len(suffix) > 0 else "") tensor = gs.Variable(tensorName, dtypeList[i], shapeList[i]) outputList.append(tensor) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=outputList, attrs=(OrderedDict() if attribution is None else attribution)) graph.nodes.append(node) return outputList, number + 1 # A example of surgery function def removeAddSub(graph): scopeName = sys._getframe().f_code.co_name n = 0 for node in graph.nodes: if node.op == "Add" and node.o().op == "Sub" and node.inputs[1].values == node.o().inputs[1].values: index = node.o().o().inputs.index(node.o().outputs[0]) tensor, n = addNode(graph, "Identity", scopeName, n, [node.inputs[0]], None, "", np.dtype(np.float32), node.inputs[0].shape) node.o().o().inputs[index] = tensor n += 1 return n # Create a ONNX file as beginning graph = gs.Graph() scopeName = "WILI" # whatever something n = 0 # a counter to differentiate the names of the nodes tensorInput = gs.Variable("tensorInput", np.dtype(np.float32), ["B", 1, 480, 640]) attribution = OrderedDict([["dilations", [1, 1]], ["kernel_shape", [3, 3]], ["pads", [1, 1, 1, 1]], ["strides", [1, 1]]]) tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorInput, constantWeight], attribution, "", np.dtype(np.float32), ['B', 1, 480, 640]) tensor2, n = addNode(graph, "Add", scopeName, n, [tensor1, constantBias], None, "", np.dtype(np.float32), ['B', 1, 480, 640]) tensor3, n = addNode(graph, "Relu", scopeName, n, [tensor2], None, "", np.dtype(np.float32), ['B', 1, 480, 640]) tensor4, n = addNode(graph, "Add", scopeName, n, [tensor3, constant1], None, "", np.dtype(np.float32), ['B', 1, 480, 640]) tensor5, n = addNode(graph, "Sub", scopeName, n, [tensor4, constant1], None, "", np.dtype(np.float32), ['B', 1, 480, 640]) tensor6, n = addNode(graph, "Shape", scopeName, n, [tensorInput], None, "", np.dtype(np.int64), [4]) # value:(B,1,480, 640) tensorBScalar, n = addNode(graph, "Gather", scopeName, n, [tensor6, constantS0], OrderedDict([('axis', 0)]), "tensorBScalar", np.dtype(np.int64), []) # value: (B) tensorB, n = addNode(graph, "Unsqueeze", scopeName, n, [tensorBScalar, constant0], None, "tensorB", np.dtype(np.int64), [1]) # value: (B) tensorHScalar, n = addNode(graph, "Gather", scopeName, n, [tensor6, constantS2], OrderedDict([('axis', 0)]), "tensorHScalar", np.dtype(np.int64), []) # value: (480) tensorH, n = addNode(graph, "Unsqueeze", scopeName, n, [tensorHScalar, constant0], None, "tensorH", np.dtype(np.int64), [1]) # value: (480) tensorWScalar, n = addNode(graph, "Gather", scopeName, n, [tensor6, constantS3], OrderedDict([('axis', 0)]), "tensorWScalar", np.dtype(np.int64), []) # value: (640) tensorW, n = addNode(graph, "Unsqueeze", scopeName, n, [tensorWScalar, constant0], None, "tensorW", np.dtype(np.int64), [1]) # value: (640) tensorHW, n = addNode(graph, "Mul", scopeName, n, [tensorH, tensorW], None, "tensorHW", np.dtype(np.int64), [1]) # value: (480*640) tensorBC1CHW, n = addNode(graph, "Concat", scopeName, n, [tensorB, constant1, tensorHW], OrderedDict([('axis', 0)]), "tensorBC1CHW", np.dtype(np.int64), [3]) # value: (B, 1, 480*640) tensor7, n = addNode(graph, "Reshape", scopeName, n, [tensor5, tensorBC1CHW], None, "", np.dtype(np.float32), ["B", 1, 480 * 640]) tensor8, n = addNode(graph, "Squeeze", scopeName, n, [tensor7, constant1], None, "", np.dtype(np.float32), ["B", 480 * 640]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant307200x64], None, "", np.dtype(np.float32), ["B", 64]) graph.inputs = [tensorInput] graph.outputs = [tensor9] graph.cleanup().toposort() graph.opset = 17 # node might not be supported by some old opset. For example, the shape inference of onnxruntime in polygraphy will fail if we use opset==11 # Save the model as ONNX file # + "save_as_external_data" is used to seperate the weight and structure of the model, making it easier to copy if we are just interested in the structure. The saving process will fail without the switch if size of the model is larger than 2GiB. # + If the model is small, "onnx.save(gs.export_onnx(graph), onnxFile0)" is enough # + "all_tensors_to_one_file" is used to reduce the number of weight files # + There must no directory prefix in "location" parameter # + Clean the target weight files before saving, or the weight files will be appended to the old ones os.system("rm -rf " + onnxFile0 + ".weight") onnx.save(gs.export_onnx(graph), onnxFile0, save_as_external_data=True, all_tensors_to_one_file=True, location=onnxFile0.split('/')[-1] + ".weight") # Load the model # + If the size of the model is larger than 2GiB, laoding process must be divided into two steps: loading the structure firstly and then the weight # + If the model is small, "onnxModel = onnx.load(onnxFile0)" is enough onnxModel = onnx.load(onnxFile0, load_external_data=False) onnx.load_external_data_for_model(onnxModel, ".") # Do constant folding by polygraphy (and save it as visualization in this example) # Sometimes this step should be skiped because some graph is not originally supported by polygraphy and TensorRT, so some manual graph surgery must be done before polygraphy take the model in this occasion onnxModel = fold_constants(onnxModel, allow_onnxruntime_shape_inference=True) onnx.save(onnxModel, onnxFile1, save_as_external_data=True, all_tensors_to_one_file=True, location=onnxFile1.split('/')[-1] + ".weight") # Continue to do graph surgery by onnx-graphsurgeon graph = gs.import_onnx(onnxModel) #graph = gs.import_onnx(onnx.shape_inference.infer_shapes(onnxModel)) # This API can be used to infer the shape of each tensor if size of the model is less than 2GiB and polygraphy is not used before # Print information of ONNX file before graph surgery print("[M] %-16s: %5d Nodes, %5d tensors" % (onnxFile0, len(graph.nodes), len(graph.tensors().keys()))) # Do graph surgery and print how many subgraph is edited print("[M] %4d RemoveAddSub" % removeAddSub(graph)) graph.cleanup().toposort() # Print information of ONNX file after graph surgery print("[M] %-16s: %5d Nodes, %5d tensors" % (onnxFile2, len(graph.nodes), len(graph.tensors().keys()))) # Print information of input / output tensor for i, tensor in enumerate(graph.inputs): print("[M] Input [%2d]: %s, %s, %s" % (i, tensor.shape, tensor.dtype, tensor.name)) for i, tensor in enumerate(graph.outputs): print("[M] Output[%2d]: %s, %s, %s" % (i, tensor.shape, tensor.dtype, tensor.name)) # Do another constant folding by polygraphy and save it to ensure the model is supported by TensorRT onnxModel = fold_constants(gs.export_onnx(graph), allow_onnxruntime_shape_inference=True) onnx.save(onnxModel, onnxFile2, save_as_external_data=True, all_tensors_to_one_file=True, location=onnxFile2.split('/')[-1] + ".weight") print("Finish graph surgery!")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/10-AdvanceAPI.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict from copy import deepcopy import numpy as np import onnx import onnx_graphsurgeon as gs def markGraphOutput(graph, lNode, bMarkOutput=True, bMarkInput=False, lMarkOutput=None, lMarkInput=None, bRemoveOldOutput=True): # graph: The ONNX graph for edition # lNode: The list of nodes we want to mark as output # bMarkOutput: Whether to mark the output tensor(s) of the nodes in the lNode # bMarkInput: Whether to mark the input tensor(s) of the nodes in the lNode # lMarkOutput: The index of output tensor(s) of the node are marked as output, only available when len(lNode) == 1 # lMarkInput: The index of input tensor(s) of the node are marked as output, only available when len(lNode) == 1 # bRemoveOldOutput: Whether to remove the original output of the network (cutting the graph to the node we want to mark to save ytime of building) # In most cases, using the first 4 parameters is enough, for example: #markGraphOutput(graph, ["/Conv"]) # mark output tensor of the node "/Conv" as output #markGraphOutput(graph, ["/Conv"], False, True) # mark input tensors of the node "/Conv" (input tensor + weight + bias) as output #markGraphOutput(graph, ["/TopK"], lMarkOutput=[1]) # mark the second output tensor of the node "/TopK" as output #markGraphOutput(graph, ["/Conv"], bRemoveOldOutput=False) # mark output tensor of the node "/Conv" as output, and keep the original output of the network if bRemoveOldOutput: graph.outputs = [] for node in graph.nodes: if node.name in lNode: if bMarkOutput: if lMarkOutput is None or len(lNode) > 1: lMarkOutput = range(len(node.outputs)) for index in lMarkOutput: graph.outputs.append(node.outputs[index]) print("Mark node [%s] output tensor [%s]" % (node.name, node.outputs[index].name)) if bMarkInput: if lMarkInput is None or len(lNode) > 1: lMarkInput = range(len(node.inputs)) for index in lMarkInput: graph.outputs.append(node.inputs[index]) print("Mark node [%s] input tensor [%s]" % (node.name, node.inputs[index].name)) graph.cleanup().toposort() return len(lNode) def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor!! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/surgeryCommon.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx_graphsurgeon as gs # the same model as 08-Tool/OnnxGraphSurgeon/01-CreateModel tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, ["B", 1, 64, 64]) tensor2 = gs.Variable("tensor2", np.float32, None) tensor3 = gs.Variable("tensor3", np.float32, None) constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 3, 3, 3], dtype=np.float32)) constant1 = gs.Constant(name="constant1", values=np.ones(shape=[1], dtype=np.float32)) node0 = gs.Node("Conv", "myConv", inputs=[tensor0, constant0], outputs=[tensor1]) node0.attrs = OrderedDict([ ["dilations", [1, 1]], ["kernel_shape", [3, 3]], ["pads", [1, 1, 1, 1]], ["strides", [1, 1]], ]) node1 = gs.Node("Add", "myAdd", inputs=[tensor1, constant1], outputs=[tensor2]) node2 = gs.Node("Relu", "myRelu", inputs=[tensor2], outputs=[tensor3]) graph = gs.Graph(nodes=[node0, node1, node2], inputs=[tensor0], outputs=[tensor3]) print("graph.DEFAULT_OPSET = %s" % graph.DEFAULT_OPSET) # equivalent to graph.opset print("graph.GLOBAL_FUNC_MAP = %s" % graph.GLOBAL_FUNC_MAP) print("graph.OPSET_FUNC_MAP = %s" % graph.OPSET_FUNC_MAP) print("graph._generate_name('myGraph') = %s" % graph._generate_name("myGraph")) print("graph._local_tensors() = %s" % graph._local_tensors()) # equivalent to dict(graph.tensors()) print("graph._foreign_tensors() = %s" % graph._foreign_tensors()) #print("graph._get_node_id() = %s" % graph._get_node_id(node0)) #print("graph._get_used_node_ids() = %s" % graph._get_used_node_ids(node0)) print(graph.name) print(graph.opset) print(graph.doc_string) print(graph.import_domains) print(graph.producer_name) print(graph.producer_version) print(graph.inputs) print(graph.outputs) print(graph.nodes) print(graph.tensors()) print(graph.graph.name_idx) print(graph.node_ids()) graph2 = graph.copy graph.layer(inputs=[tensor0, constant0], outputs=[tensor1], op='MyOp') # add nodes into graph """ Member of IBuilder: ++++ shown above ---- not shown above [no prefix] others ++++DEFAULT_OPSET ++++GLOBAL_FUNC_MAP ++++OPSET_FUNC_MAP ----__class__ __delattr__ __dict__ __dir__ __doc__ __eq__ __format__ __ge__ __getattr__ __getattribute__ __gt__ __hash__ __init__ __init_subclass__ __le__ __lt__ __module__ __name__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ __weakref__ ++++_foreign_tensors ++++_generate_name ++++_get_node_id ++++_get_used_node_ids ++++_local_tensors ----cleanup refer to 08-Tool/OnnxGraphSurgeon/06-Fold.py ++++copy ++++doc_string ----fold_constants refer to 08-Tool/OnnxGraphSurgeon/06-Fold.py ++++import_domains ++++inputs ++++layer ++++name ++++name_idx ++++node_ids ++++nodes ++++opset ++++outputs ++++producer_name ++++producer_version ----register refer to 08-Tool/OnnxGraphSurgeon/09-BuildModelWithAPI.py ++++tensors ----toposort refer to 08-Tool/OnnxGraphSurgeon/06-Fold.py """
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/API/graphAPI.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx_graphsurgeon as gs # the same model as 08-Tool/OnnxGraphSurgeon/01-CreateModel tensor0 = gs.Variable("tensor0", np.float32, ["B", 3, 64, 64]) tensor1 = gs.Variable("tensor1", np.float32, ["B", 1, 64, 64]) tensor2 = gs.Variable("tensor2", np.float32, None) tensor3 = gs.Variable("tensor3", np.float32, None) constant0 = gs.Constant(name="constant0", values=np.ones(shape=[1, 3, 3, 3], dtype=np.float32)) constant1 = gs.Constant(name="constant1", values=np.ones(shape=[1], dtype=np.float32)) node0 = gs.Node("Conv", "myConv", inputs=[tensor0, constant0], outputs=[tensor1]) node0.attrs = OrderedDict([ ["dilations", [1, 1]], ["kernel_shape", [3, 3]], ["pads", [1, 1, 1, 1]], ["strides", [1, 1]], ]) node1 = gs.Node("Add", "myAdd", inputs=[tensor1, constant1], outputs=[tensor2]) node2 = gs.Node("Relu", "myRelu", inputs=[tensor2], outputs=[tensor3]) graph = gs.Graph(nodes=[node0, node1, node2], inputs=[tensor0], outputs=[tensor3]) """ Member of IBuilder: ++++ shown above ---- not shown above [no prefix] others Constant ++++Graph ++++Node OnnxGraphSurgeonException Tensor ++++Variable __builtins__ __cached__ __doc__ __file__ __loader__ __name__ __package__ __path__ __spec__ __version__ export_onnx exporters import_onnx importers ir logger util'] """
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/OnnxGraphSurgeon/API/gsAPI-TODO.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs onnxFile = "./model.onnx" tensor0 = gs.Variable("tensor-0", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) graphNodeList = [] tensor1 = gs.Variable("tensor-1", np.float32, None) node1 = gs.Node("Conv", "Conv-1", inputs=[tensor0, constant32x1, constant32], outputs=[tensor1]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor2 = gs.Variable("tensor-2", np.float32, None) node2 = gs.Node("Relu", "ReLU-2", inputs=[tensor1], outputs=[tensor2]) graphNodeList.append(node2) tensor3 = gs.Variable("tensor-3", np.float32, None) node3 = gs.Node("MaxPool", "MaxPool-3", inputs=[tensor2], outputs=[tensor3]) node3.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node3) tensor4 = gs.Variable("tensor-4", np.float32, None) node1 = gs.Node("Conv", "Conv-4", inputs=[tensor3, constant64x32, constant64], outputs=[tensor4]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor5 = gs.Variable("tensor-5", np.float32, None) node5 = gs.Node("Relu", "ReLU-5", inputs=[tensor4], outputs=[tensor5]) graphNodeList.append(node5) tensor6 = gs.Variable("tensor-6", np.float32, None) node6 = gs.Node("MaxPool", "MaxPool-6", inputs=[tensor5], outputs=[tensor6]) node6.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node6) tensor7 = gs.Variable("tensor-7", np.float32, None) node7 = gs.Node("Transpose", "Transpose-7", inputs=[tensor6], outputs=[tensor7], attrs=OrderedDict([("perm", [0, 2, 3, 1])])) graphNodeList.append(node7) tensor8 = gs.Variable("tensor-8", np.float32, None) node8 = gs.Node("Reshape", "Reshape-7", inputs=[tensor7, constantM1Comma3136], outputs=[tensor8]) graphNodeList.append(node8) tensor9 = gs.Variable("tensor-9", np.float32, None) node9 = gs.Node("MatMul", "MatMul-9", inputs=[tensor8, constant3136x1024], outputs=[tensor9]) graphNodeList.append(node9) tensor10 = gs.Variable("tensor-10", np.float32, None) node10 = gs.Node("Add", "Add-10", inputs=[tensor9, constant1024], outputs=[tensor10]) graphNodeList.append(node10) tensor11 = gs.Variable("tensor-11", np.float32, None) node11 = gs.Node("Relu", "ReLU-11", inputs=[tensor10], outputs=[tensor11]) graphNodeList.append(node11) tensor12 = gs.Variable("tensor-12", np.float32, None) node12 = gs.Node("MatMul", "MatMul-12", inputs=[tensor11, constant1024x10], outputs=[tensor12]) graphNodeList.append(node12) tensor13 = gs.Variable("tensor-13", np.float32, None) node13 = gs.Node("Add", "Add-13", inputs=[tensor12, constant10], outputs=[tensor13]) graphNodeList.append(node13) """ # we do not need Softmax or ArgMax here because we want output tensor of data type float32 tensor14 = gs.Variable("tensor-14", np.float32, None) node14 = gs.Node("Softmax", "Softmax-14", inputs=[tensor13], outputs=[tensor14], attrs=OrderedDict([("axis", 1)])) graphNodeList.append(node14) tensor15 = gs.Variable("tensor-15", np.int64, None) node15 = gs.Node("ArgMax", "ArgMax-15", inputs=[tensor14], outputs=[tensor15], attrs=OrderedDict([("axis", 1), ("keepdims", 0)])) graphNodeList.append(node15) """ graph = gs.Graph(nodes=graphNodeList, inputs=[tensor0], outputs=[tensor13]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), onnxFile) print("Succeeded create %s" % onnxFile)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/FP16FineTuning/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os os.chdir("/w/gitlab/tensorrt-cookbook/08-Tool/FP16FineTuning") import numpy as np import onnx import onnxruntime onnxFile = "model.onnx" np.random.seed(31193) shape = [2,1,28,28] print("Onnxruntime using device: %s" % onnxruntime.get_device()) session = onnxruntime.InferenceSession(onnxFile) ioData = {} for i, inputTensor in enumerate(session.get_inputs()): print("Input %2d: %s, %s, %s" % (i, inputTensor.name, inputTensor.shape, inputTensor.type)) if inputTensor.type == "tensor(float)": dataType = np.float32 if inputTensor.type == "tensor(int32)": dataType = np.int32 data = np.random.rand(np.prod(shape)).astype(dataType).reshape(shape) ioData[inputTensor.name] = data for i, outputTensor in enumerate(session.get_outputs()): print("Output%2d: %s, %s, %s" % (i, outputTensor.name, outputTensor.shape, outputTensor.type)) outputList = session.run(None, ioData) for i, outputTensor in enumerate(session.get_outputs()): print(outputList[i]) ioData[outputTensor.name] = outputList[i] np.savez("IOData.npz", **ioData)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/FP16FineTuning/getReferenceInputOutput.py
import ctypes import os from copy import deepcopy from datetime import datetime as dt import numpy as np import tensorrt as trt from cuda import cudart from tqdm import tqdm os.chdir("/w/gitlab/tensorrt-cookbook/08-Tool/FP16FineTuning") # fro debug # Customized variable ---------------------------------------------------------- onnxFile = "model.onnx" # required pluginFileList = [] # optional ioDataFile = "IOData.npz" # optional targetAccuracy = 5 # optional reportFile = "report.txt" # Other cariable --------------------------------------------------------------- trtFile = "model.plan" timingCacheFile = "model.timingCache" bPrintNetwork = False bUseOnnxruntime = False bDrawPlot = False excludeList = {"SHAPE", "PLUGIN", "PLUGIN_V2", "CONSTANT", "ASSERTION", "SHUFFLE", "IDENTITY", "CONCATENATION", "GATHER", "SLICE", "RESIZE", "UNARY", "CONDITION", "CONDITIONAL_INPUT", "CONDITIONAL_OUTPUT", "FILL", "NON_ZERO", "ONE_HOT"} resultList = [] np.random.seed(31193) np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() # preparation work ------------------------------------------------------------- logger = trt.Logger(trt.Logger.ERROR) if not os.path.exists(onnxFile): print("Failed finding %s" % onnxFile) exit() if len(pluginFileList) > 0: bUseOnnxruntime = False trt.init_libnvinfer_plugins(logger, '') for soFile in pluginFileList: if not os.path.exists(soFile): print("Failed finding %s" % soFile) exit() ctypes.cdll.LoadLibrary(soFile) # parse ONNX file to get metadata of network ----------------------------------- builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) parser = trt.OnnxParser(network, logger) with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing %s" % onnxFile) for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing %s" % onnxFile) layerList = [] for i in range(network.num_layers): layer = network.get_layer(i) layerList.append([layer.name, layer.type.name]) if bPrintNetwork: print("%4d->%s,in=%d,out=%d,%s" % (i, str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name)) for j in range(layer.num_inputs): tensor = layer.get_input(j) print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) for j in range(layer.num_outputs): tensor = layer.get_output(j) print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) # preare data for inference ---------------------------------------------------- dataMap = {} if ioDataFile != "": # use IO data from file and create shape list from ioData = np.load(ioDataFile) for key, value in ioData.items(): dataMap[key] = value else: # use random input data for i in range(network.num_inputs): inputTensor = network.get_input(i) shape = [x if x != -1 else 1 for x in inputTensor.shape] dataMap[inputTensor.name] = np.random.rand(np.prod(shape)).astype(trt.nptype(inputTensor.dtype)).reshape(shape) # Main process ----------------------------------------------------------------- def run(bFP32, layerNameListInFP32=[]): #print("%s, Build engine of %s: %s" % (dt.now(), ("FP32" if bFP32 else "FP16"), [x[0] for x in layerNameListInFP32])) # for debug command = "trtexec --onnx=%s --useSpinWait --noDataTransfers" % onnxFile command += " " + "--saveEngine=%s" % trtFile #command += " " + "--verbose" # for debug if not bFP32: command += " " + "--fp16" + " " if len(layerNameListInFP32) > 0: command += " " + "--precisionConstraints=prefer" for layerName, layerType in layerNameListInFP32: if layerType not in excludeList: command += " " + "--layerPrecisions=%s:fp32" % layerName else: #print("Skip Layer %s, Type = %s" % (layerName, layerType)) return command += " " + "2>/dev/null" output = os.popen(command) time = "+inf" for line in output.readlines(): #print(line) # for debug if "[I] GPU Compute Time" in line: time = float(line.split("ms")[3].split("=")[1]) with open(trtFile, "rb") as f: engineString = f.read() engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) # create inference Engine using Runtime nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() for key, value in dataMap.items(): if engine.get_tensor_mode(key) == trt.TensorIOMode.INPUT: context.set_input_shape(key, value.shape) #for i in range(nIO): # for debug # print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] for i in range(nInput): bufferH.append(np.ascontiguousarray(dataMap[lTensorName[i]])) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) if bFP32: for i in range(nInput, nIO): dataMap[lTensorName[i]] = bufferH[i] else: maxErrorList = [] mediumErrorList = [] for i in range(nInput, nIO): a = bufferH[i] b = dataMap[lTensorName[i]] maxErrorList.append(np.max(np.abs(a - b))) mediumErrorList.append(np.median(np.abs(a - b))) resultList.append([time, maxErrorList, mediumErrorList, layerNameListInFP32]) for b in bufferD: # free the GPU memory buffer after all work cudart.cudaFree(b) return # Build model in FP32 mode run(True) # Build model in FP16 mode run(False) for layer in tqdm(layerList): run(False, [layer]) print(resultList) resultList = sorted(resultList, key=(lambda x: x[1][0])) # sort by max absolute error with open(reportFile, "w") as ff: for line in resultList: ff.write(str(line)) ff.write("\n") if targetAccuracy > 0: n = np.argmin(np.cumsum([x[1][0] for x in resultList]) >= resultList[-1][1][0] - targetAccuracy) for i in range(n): print(resultList[i]) # double check #run(False, None) if bDrawPlot: from matplotlib import pyplot as plt
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/FP16FineTuning/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "AddScalar", scopeName, n, [tensorX], OrderedDict([["scalar", 1.0]]), "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor1] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/trtexec/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import numpy as np import tensorrt as trt logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, 28, 28]) profile.set_shape(inputTensor.name, [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28]) config.add_optimization_profile(profile) w = np.random.rand(32, 1, 5, 5).astype(np.float32).reshape(-1) b = np.random.rand(32).astype(np.float32).reshape(-1) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], w, b) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.random.rand(64, 32, 5, 5).astype(np.float32).reshape(-1) b = np.random.rand(64).astype(np.float32).reshape(-1) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], w, b) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.first_transpose = (0, 2, 3, 1) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.random.rand(64 * 7 * 7, 1024).astype(np.float32) b = np.random.rand(1, 1024).astype(np.float32) _7 = network.add_constant(w.shape, trt.Weights(np.ascontiguousarray(w))) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(np.ascontiguousarray(b))) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.random.rand(1024, 10).astype(np.float32) b = np.random.rand(1, 10).astype(np.float32) _12 = network.add_constant(w.shape, trt.Weights(np.ascontiguousarray(w))) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(np.ascontiguousarray(b))) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) # Core code of Network Printer for i in range(network.num_layers): layer = network.get_layer(i) print("%4d->%s,in=%d,out=%d,%s" % (i, str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name)) for j in range(layer.num_inputs): tensor = layer.get_input(j) print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) for j in range(layer.num_outputs): tensor = layer.get_output(j) print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name)) #engineString = builder.build_serialized_network(network, config)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/NetworkPrinter/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "Identity", scopeName, n, [tensorX], None, "", np.float32, ["B"]) tensor2, n = addNode(graph, "UnknownNode1", scopeName, n, [tensor1], None, "", np.float32, ["B"]) tensor3, n = addNode(graph, "Identity", scopeName, n, [tensor2], None, "", np.float32, ["B"]) tensor4, n = addNode(graph, "UnknownNode2", scopeName, n, [tensor3], None, "", np.float32, ["B"]) tensor5, n = addNode(graph, "Identity", scopeName, n, [tensor4], None, "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor5] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/DebugExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "Identity", scopeName, n, [tensorX], None, "", np.float32, ["B"]) tensor2, n = addNode(graph, "UnknownNode", scopeName, n, [tensor1], None, "", np.float32, ["B"]) tensor3, n = addNode(graph, "Identity", scopeName, n, [tensor2], None, "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor3] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/InspectExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "AddScalar", scopeName, n, [tensorX], OrderedDict([["scalar", 1.0]]), "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor1] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx") # ModelC ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) constant0 = gs.Constant("constant0", np.ascontiguousarray(np.zeros([1], dtype=np.float32))) n = 0 scopeName = "C" tensor1, n = addNode(graph, "Div", scopeName, n, [tensorX, constant0], None, "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor1] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelC.onnx") print("Succeeded create %s" % "modelC.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/RunExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs onnxFile = "./model.onnx" tensor0 = gs.Variable("tensor-0", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) graphNodeList = [] tensor1 = gs.Variable("tensor-1", np.float32, None) node1 = gs.Node("Conv", "Conv-1", inputs=[tensor0, constant32x1, constant32], outputs=[tensor1]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor2 = gs.Variable("tensor-2", np.float32, None) node2 = gs.Node("Relu", "ReLU-2", inputs=[tensor1], outputs=[tensor2]) graphNodeList.append(node2) tensor3 = gs.Variable("tensor-3", np.float32, None) node3 = gs.Node("MaxPool", "MaxPool-3", inputs=[tensor2], outputs=[tensor3]) node3.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node3) tensor4 = gs.Variable("tensor-4", np.float32, None) node1 = gs.Node("Conv", "Conv-4", inputs=[tensor3, constant64x32, constant64], outputs=[tensor4]) node1.attrs = OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]) graphNodeList.append(node1) tensor5 = gs.Variable("tensor-5", np.float32, None) node5 = gs.Node("Relu", "ReLU-5", inputs=[tensor4], outputs=[tensor5]) graphNodeList.append(node5) tensor6 = gs.Variable("tensor-6", np.float32, None) node6 = gs.Node("MaxPool", "MaxPool-6", inputs=[tensor5], outputs=[tensor6]) node6.attrs = OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]) graphNodeList.append(node6) tensor7 = gs.Variable("tensor-7", np.float32, None) node7 = gs.Node("Transpose", "Transpose-7", inputs=[tensor6], outputs=[tensor7], attrs=OrderedDict([("perm", [0, 2, 3, 1])])) graphNodeList.append(node7) tensor8 = gs.Variable("tensor-8", np.float32, None) node8 = gs.Node("Reshape", "Reshape-7", inputs=[tensor7, constantM1Comma3136], outputs=[tensor8]) graphNodeList.append(node8) tensor9 = gs.Variable("tensor-9", np.float32, None) node9 = gs.Node("MatMul", "MatMul-9", inputs=[tensor8, constant3136x1024], outputs=[tensor9]) graphNodeList.append(node9) tensor10 = gs.Variable("tensor-10", np.float32, None) node10 = gs.Node("Add", "Add-10", inputs=[tensor9, constant1024], outputs=[tensor10]) graphNodeList.append(node10) tensor11 = gs.Variable("tensor-11", np.float32, None) node11 = gs.Node("Relu", "ReLU-11", inputs=[tensor10], outputs=[tensor11]) graphNodeList.append(node11) tensor12 = gs.Variable("tensor-12", np.float32, None) node12 = gs.Node("MatMul", "MatMul-12", inputs=[tensor11, constant1024x10], outputs=[tensor12]) graphNodeList.append(node12) tensor13 = gs.Variable("tensor-13", np.float32, None) node13 = gs.Node("Add", "Add-13", inputs=[tensor12, constant10], outputs=[tensor13]) graphNodeList.append(node13) tensor14 = gs.Variable("tensor-14", np.float32, None) node14 = gs.Node("Softmax", "Softmax-14", inputs=[tensor13], outputs=[tensor14], attrs=OrderedDict([("axis", 1)])) graphNodeList.append(node14) tensor15 = gs.Variable("tensor-15", np.int64, None) node15 = gs.Node("ArgMax", "ArgMax-15", inputs=[tensor14], outputs=[tensor15], attrs=OrderedDict([("axis", 1), ("keepdims", 0)])) graphNodeList.append(node15) graph = gs.Graph(nodes=graphNodeList, inputs=[tensor0], outputs=[tensor15]) graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), onnxFile) print("Succeeded create %s" % onnxFile)
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/TemplateExample/getOnnxModel.py
#!/usr/bin/env python3 # Template auto-generated by polygraphy [v0.33.0] on 10/09/22 at 09:13:18 # Generation Command: /opt/conda/bin/polygraphy template trt-network model.onnx --output modifyNetwork.py # Creates a TensorRT Network using the Network API. import tensorrt as trt from polygraphy import func from polygraphy.backend.trt import NetworkFromOnnxPath # Loaders parse_network_from_onnx = NetworkFromOnnxPath('/work/gitlab/tensorrt-cookbook/08-Tool/Polygraphy/templateExample/model.onnx') @func.extend(parse_network_from_onnx) def load_network(builder, network, parser): pass # TODO: Set up the network here. This function should not return anything.
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/TemplateExample/modifyNetwork.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) batchName = 12 # Static Shape mode #batchName = "B" # Dynamic Shape mode tensorX = gs.Variable("tensorX", np.float32, [batchName, 2, 3, 4]) constant0C1 = gs.Constant("constant0C1", np.ascontiguousarray(np.array([0, 1], dtype=np.int64))) constant2C3 = gs.Constant("constant2C3", np.ascontiguousarray(np.array([2, 3], dtype=np.int64))) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Shape", scopeName, n, [tensorX], None, "", np.int64, [4]) tensor2, n = addNode(graph, "ReduceProd", scopeName, n, [tensor1], OrderedDict([["axes", [0]], ["keepdims", 1]]), "", np.int64, [1]) tensor3, n = addNode(graph, "Reshape", scopeName, n, [tensorX, tensor2], None, "", np.float32, ["%s*24" % str(batchName)]) tensor4, n = addNode(graph, "Gather", scopeName, n, [tensor1, constant0C1], None, "", np.int64, [2]) tensor5, n = addNode(graph, "Gather", scopeName, n, [tensor1, constant2C3], None, "", np.int64, [2]) tensor6, n = addNode(graph, "ReduceProd", scopeName, n, [tensor5], OrderedDict([["axes", [0]], ["keepdims", 1]]), "", np.int64, [1]) tensor7, n = addNode(graph, "Concat", scopeName, n, [tensor4, tensor6], OrderedDict([["axis", 0]]), "", np.int64, [4]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensorX, tensor7], None, "", np.float32, [batchName, 2, 12]) graph.inputs = [tensorX] graph.outputs = [tensor3, tensor8] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/SurgeonExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/DataExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from collections import OrderedDict import numpy as np import onnx import onnx_graphsurgeon as gs def addNode(graph, nodeType, prefix, number, inputList, attribution=None, suffix="", dtype=None, shape=None): # ONLY for the node with one output tensor! # graph: The ONNX graph for edition # nodeType: The type of the node to add, for example, "Concat" # prefix: Optimization type, for example "RemoveLoop" # number: An incremental number to prevent duplicate names # inputlist: The list of input tensors for the node # attribution: The attribution dictionary of the node, for example, OrderedDict([('axis',0)]) # suffix: Extra name for marking the tensor, for example "bTensor" # dtype: The data type of the output tensor (optional) # shape: The shape of the output tensor (optional) tensorName = prefix + "-V-" + str(number) + "-" + nodeType nodeName = prefix + "-N-" + str(number) + "-" + nodeType if attribution == None: attribution = OrderedDict() if len(suffix) > 0: tensorName += "-" + suffix tensor = gs.Variable(tensorName, dtype, shape) node = gs.Node(nodeType, nodeName, inputs=inputList, outputs=[tensor], attrs=attribution) graph.nodes.append(node) return tensor, number + 1 # ModelA ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B", 1, 28, 28]) constant32x1 = gs.Constant("constant32x1", np.ascontiguousarray(np.random.rand(32, 1, 5, 5).reshape(32, 1, 5, 5).astype(np.float32) * 2 - 1)) constant32 = gs.Constant("constant32", np.ascontiguousarray(np.random.rand(32).reshape(32).astype(np.float32) * 2 - 1)) constant64x32 = gs.Constant("constant64x32", np.ascontiguousarray(np.random.rand(64, 32, 5, 5).reshape(64, 32, 5, 5).astype(np.float32) * 2 - 1)) constant64 = gs.Constant("constant64", np.ascontiguousarray(np.random.rand(64).reshape(64).astype(np.float32) * 2 - 1)) constantM1Comma3136 = gs.Constant("constantM1Comma3136", np.ascontiguousarray(np.array([-1, 7 * 7 * 64], dtype=np.int64))) constant3136x1024 = gs.Constant("constant3136x1024", np.ascontiguousarray(np.random.rand(3136, 1024).reshape(3136, 1024).astype(np.float32) * 2 - 1)) constant1024 = gs.Constant("constant1024", np.ascontiguousarray(np.random.rand(1024).reshape(1024).astype(np.float32) * 2 - 1)) constant1024x10 = gs.Constant("constant1024x10", np.ascontiguousarray(np.random.rand(1024, 10).reshape(1024, 10).astype(np.float32) * 2 - 1)) constant10 = gs.Constant("constant10", np.ascontiguousarray(np.random.rand(10).reshape(10).astype(np.float32) * 2 - 1)) n = 0 scopeName = "A" tensor1, n = addNode(graph, "Conv", scopeName, n, [tensorX, constant32x1, constant32], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 32, 28, 28]) tensor2, n = addNode(graph, "Relu", scopeName, n, [tensor1], None, "", np.float32, ["B", 32, 28, 28]) tensor3, n = addNode(graph, "MaxPool", scopeName, n, [tensor2], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 32, 14, 14]) tensor4, n = addNode(graph, "Conv", scopeName, n, [tensor3, constant64x32, constant64], OrderedDict([["kernel_shape", [5, 5]], ["pads", [2, 2, 2, 2]]]), "", np.float32, ["B", 64, 14, 14]) tensor5, n = addNode(graph, "Relu", scopeName, n, [tensor4], None, "", np.float32, ["B", 64, 14, 14]) tensor6, n = addNode(graph, "MaxPool", scopeName, n, [tensor5], OrderedDict([["kernel_shape", [2, 2]], ["pads", [0, 0, 0, 0]], ["strides", [2, 2]]]), "", np.float32, ["B", 64, 7, 7]) tensor7, n = addNode(graph, "Transpose", scopeName, n, [tensor6], OrderedDict([["perm", [0, 2, 3, 1]]]), "", np.float32, ["B", 7, 7, 64]) tensor8, n = addNode(graph, "Reshape", scopeName, n, [tensor7, constantM1Comma3136], None, "", np.float32, ["B", 3136]) tensor9, n = addNode(graph, "MatMul", scopeName, n, [tensor8, constant3136x1024], None, "", np.float32, ["B", 1024]) tensor10, n = addNode(graph, "Add", scopeName, n, [tensor9, constant1024], None, "", np.float32, ["B", 1024]) tensor11, n = addNode(graph, "Relu", scopeName, n, [tensor10], None, "", np.float32, ["B", 1024]) tensor12, n = addNode(graph, "MatMul", scopeName, n, [tensor11, constant1024x10], None, "", np.float32, ["B", 10]) tensor13, n = addNode(graph, "Add", scopeName, n, [tensor12, constant10], None, "", np.float32, ["B", 10]) tensor14, n = addNode(graph, "Softmax", scopeName, n, [tensor13], OrderedDict([["axis", 1]]), "", np.float32, ["B", 10]) tensor15, n = addNode(graph, "ArgMax", scopeName, n, [tensor14], OrderedDict([["axis", 1], ["keepdims", 0]]), "", np.int64, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor13, tensor15] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelA.onnx") print("Succeeded create %s" % "modelA.onnx") # ModelB ----------------------------------------------------------------------- graph = gs.Graph(nodes=[], inputs=[], outputs=[]) tensorX = gs.Variable("tensorX", np.float32, ["B"]) n = 0 scopeName = "B" tensor1, n = addNode(graph, "AddScalar", scopeName, n, [tensorX], OrderedDict([["scalar", 1.0]]), "", np.float32, ["B"]) graph.inputs = [tensorX] graph.outputs = [tensor1] graph.cleanup().toposort() onnx.save(gs.export_onnx(graph), "modelB.onnx") print("Succeeded create %s" % "modelB.onnx")
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/Polygraphy-CLI/ConvertExample/getOnnxModel.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import numpy as np import nvtx import tensorrt as trt from cuda import cudart trtFile = "./model.plan" data = np.arange(3 * 4 * 5, dtype=np.float32).reshape(3, 4, 5) def run(): logger = trt.Logger(trt.Logger.ERROR) if os.path.isfile(trtFile): with open(trtFile, "rb") as f: engineString = f.read() if engineString == None: print("Failed getting serialized engine!") return print("Succeeded getting serialized engine!") else: builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputTensor = network.add_input("inputT0", trt.float32, [-1, -1, -1]) profile.set_shape(inputTensor.name, [1, 1, 1], [3, 4, 5], [6, 8, 10]) config.add_optimization_profile(profile) identityLayer = network.add_identity(inputTensor) network.mark_output(identityLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building serialized engine!") return print("Succeeded building serialized engine!") with open(trtFile, "wb") as f: f.write(engineString) print("Succeeded saving .plan file!") engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) if engine == None: print("Failed building engine!") return print("Succeeded building engine!") nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [3, 4, 5]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) #nvtx.push_range("Inference part, with nvtx marked", color="green") # another way to use with nvtx.annotate("Inference part, with nvtx marked", color="green"): for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) #nvtx.pop_range() # another way to use for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) if __name__ == "__main__": os.system("rm -rf ./*.plan") run() run()
trt-samples-for-hackathon-cn-master
cookbook/07-Tool/nvtx/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-TensorFlow1/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf1 import tensorrt as trt np.random.seed(31193) tf1.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 paraFile = "./para.npz" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" trtVersion = trt.__version__.split(".") # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.npz ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf1.compat.v1.disable_eager_execution() cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow1 -------------------------------- def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData x = tf1.compat.v1.placeholder(tf1.float32, [None, nHeight, nWidth, 1], name="x") y_ = tf1.compat.v1.placeholder(tf1.float32, [None, 10], name="y_") w1 = tf1.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf1.compat.v1.get_variable("b1", shape=[32], initializer=tf1.constant_initializer(value=0.1)) h1 = tf1.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf1.nn.relu(h2) h4 = tf1.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf1.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf1.compat.v1.get_variable("b2", shape=[64], initializer=tf1.constant_initializer(value=0.1)) h5 = tf1.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf1.nn.relu(h6) h8 = tf1.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf1.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf1.compat.v1.get_variable("b3", shape=[1024], initializer=tf1.constant_initializer(value=0.1)) h9 = tf1.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf1.matmul(h9, w3) h11 = h10 + b3 h12 = tf1.nn.relu(h11) w4 = tf1.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf1.compat.v1.get_variable("b4", shape=[10], initializer=tf1.constant_initializer(value=0.1)) h13 = tf1.matmul(h12, w4) h14 = h13 + b4 y = tf1.nn.softmax(h14, name="y") z = tf1.argmax(y, 1, name="z") crossEntropy = -tf1.reduce_sum(y_ * tf1.math.log(y)) trainStep = tf1.compat.v1.train.AdamOptimizer(1e-4).minimize(crossEntropy) accuracy = tf1.reduce_mean(tf1.cast(tf1.equal(z, tf1.argmax(y_, 1)), tf1.float32), name="accuracy") tfConfig = tf1.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf1.compat.v1.Session(config=tfConfig) sess.run(tf1.compat.v1.global_variables_initializer()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) trainStep.run(session=sess, feed_dict={x: xSample, y_: ySample}) if i % 10 == 0: accuracyValue = accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, batch %3d, train acc = %f" % (dt.now(), 10 + i, accuracyValue)) xTest, yTest = getBatch(testFileList, nTrainBatchSize, False) accuracyValue = 0 for i in range(len(testFileList) // nTrainBatchSize): xSample = xTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] ySample = yTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] accuracyValue += accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, test acc = %f" % (dt.now(), accuracyValue / (len(testFileList) // nTrainBatchSize))) para = {} # save weight as file print("Parameter of the model:") for i in tf1.compat.v1.get_collection(tf1.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print("%s:\t%s" % (name, value.shape)) para[name] = value np.savez(paraFile, **para) sess.close() del para print("Succeeded building model in TensorFlow1!") # Rebuild network, load weights and do inference in TensorRT ------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, nHeight, nWidth]) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) para = np.load(paraFile) w = np.ascontiguousarray(para["w1:0"].transpose(3, 2, 0, 1)) b = np.ascontiguousarray(para["b1:0"]) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(para["w2:0"].transpose(3, 2, 0, 1)) b = np.ascontiguousarray(para["b2:0"]) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.first_transpose = (0, 2, 3, 1) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(para["w3:0"]) b = np.ascontiguousarray(para["b3:0"].reshape(1, -1)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(para["w4:0"]) b = np.ascontiguousarray(para["b4:0"].reshape(1, -1)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-TensorFlow1/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-Paddlepaddle/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import calibrator import cv2 import numpy as np import paddle import paddle.nn.functional as F import tensorrt as trt from cuda import cudart np.random.seed(31193) paddle.seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 paddleFilePath = "./model/model" paraFile = "./para.npz" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.npz ./*.plan ./*.cache " + paddleFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, 1, nHeight, nWidth], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(1, nHeight, nWidth).astype(np.float32) / 255 yData[i] = label return xData, yData # Create network and train model in Paddlepaddle ------------------------------- class Net(paddle.nn.Layer): def __init__(self, num_classes=1): super(Net, self).__init__() self.conv1 = paddle.nn.Conv2D(1, 32, [5, 5], 1, 2) self.pool1 = paddle.nn.MaxPool2D(2, 2) self.conv2 = paddle.nn.Conv2D(32, 64, [5, 5], 1, 2) self.pool2 = paddle.nn.MaxPool2D(2, 2) self.flatten = paddle.nn.Flatten(1) self.fc1 = paddle.nn.Linear(64 * 7 * 7, 1024) self.fc2 = paddle.nn.Linear(1024, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.pool1(x) x = self.conv2(x) x = F.relu(x) x = self.pool2(x) x = self.flatten(x) x = self.fc1(x) x = F.relu(x) y = self.fc2(x) z = F.softmax(y, 1) z = paddle.argmax(z, 1) return y, z model = Net() model.train() opt = paddle.optimizer.Adam(0.001, parameters=model.parameters()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) xSample = paddle.to_tensor(xSample) ySample = paddle.to_tensor(ySample) y, z = model(xSample) loss = F.cross_entropy(y, paddle.argmax(ySample, 1, keepdim=True)) loss.backward() opt.step() opt.clear_grad() if i % 10 == 0: accuracyValue = paddle.sum(z - paddle.argmax(ySample, 1) == 0).numpy().item() / nTrainBatchSize print("%s, batch %3d, train acc = %f" % (dt.now(), 10 + i, accuracyValue)) model.eval() xTest, yTest = getBatch(testFileList, nTrainBatchSize, False) xTest = paddle.to_tensor(xTest) yTest = paddle.to_tensor(yTest) accuracyValue = 0 for i in range(len(testFileList) // nTrainBatchSize): xSample = xTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] ySample = yTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] y, z = model(xSample) accuracyValue += paddle.sum(z - paddle.argmax(ySample, 1) == 0).numpy().item() print("%s, test acc = %f" % (dt.now(), accuracyValue / (len(testFileList) // nTrainBatchSize * nTrainBatchSize))) # Two methods to save weights as file if True: # extract weights from model print("Parameter of the model:") para = {} for item in model.named_parameters(): print(item[0], ":", item[1].shape) para[item[0]] = item[1] np.savez(paraFile, **para) else: # etract weights from file inputDescList = [] inputDescList.append(paddle.static.InputSpec(shape=[None, 1, nHeight, nWidth], dtype='float32', name='x')) modelStatic = paddle.jit.to_static(model, inputDescList) paddle.jit.save(modelStatic, paddleFilePath) stateDict = paddle.load(paddleFilePath) print("Parameter of the model:") para = {} for key in stateDict.keys(): print(key, ":", stateDict[key].shape) para[key] = stateDict[key] np.savez(paraFile, **para) del para print("Succeeded building model in Paddlepaddle!") # Rebuild network, load weights and do inference in TensorRT ------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, nHeight, nWidth]) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) para = np.load(paraFile) w = np.ascontiguousarray(para["conv1.weight"]) b = np.ascontiguousarray(para["conv1.bias"]) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(para["conv2.weight"]) b = np.ascontiguousarray(para["conv2.bias"]) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(para["fc1.weight"]) b = np.ascontiguousarray(para["fc1.bias"].reshape(1, -1)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(para["fc2.weight"]) b = np.ascontiguousarray(para["fc2.bias"].reshape(1, -1)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-Paddlepaddle/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import sys from datetime import datetime as dt import numpy as np import tensorrt as trt from cuda import cudart os.environ["TF_ENABLE_DEPRECATION_WARNINGS"] = "1" os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf tf.compat.v1.disable_eager_execution() np.random.seed(31193) tf.compat.v1.set_random_seed(97) nB, nC, nH, nW = 2, 1, 28, 28 cOut, hW, wW = 32, 5, 5 inputData = np.random.rand(nB, nH, nW, nC).astype(np.float32).reshape([nB, nH, nW, nC]) # NHWC format def printArrayInformation(x, info="", n=5): if 0 in x.shape: print('%s:%s' % (info, str(x.shape))) print() return print( '%s:%s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \ info,str(x.shape),np.sum(abs(x)),np.var(x),np.max(x),np.min(x),np.sum(np.abs(np.diff(x.reshape(-1)))) )) print('\t', x.reshape(-1)[:n], x.reshape(-1)[-n:]) def check(a, b, weak=False, checkEpsilon=1e-5): if weak: a = a.astype(np.float32) b = b.astype(np.float32) res = np.all(np.abs(a - b) < checkEpsilon) else: res = np.all(a == b) diff0 = np.max(np.abs(a - b)) diff1 = np.max(np.abs(a - b) / (np.abs(b) + checkEpsilon)) print("check:%s, absDiff=%f, relDiff=%f" % (res, diff0, diff1)) def test_tf_nn_conv2d(): print("\ntf.nn.conv2d ------------------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") weight = tf.compat.v1.get_variable("w1", shape=[hW, wW, nC, cOut], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) y = tf.nn.conv2d( \ x, filter=weight, strides=None, padding="SAME", use_cudnn_on_gpu=True, data_format="NHWC", dilations=[1, 1, 1, 1], name="y", filters=None ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_nn_conv2d.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, -1, nC)) profile.set_shape(inputT0.name, [1, 1, 1, nC], [nB, nH, nW, nC], [nB * 2, nH * 2, nW * 2, nC]) config.add_optimization_profile(profile) _h1 = network.add_shuffle(inputT0) # NHWC to NCHW _h1.first_transpose = (0, 3, 1, 2) weight = np.load("./para_tf_nn_conv2d.npz")["w1:0"].transpose(3, 2, 0, 1).reshape(-1) _h2 = network.add_convolution_nd(_h1.get_output(0), cOut, [hW, wW], weight, None) _h2.padding_nd = (2, 2) _h3 = network.add_shuffle(_h2.get_output(0)) # NCHW to NHWC, align with TF _h3.first_transpose = (0, 2, 3, 1) network.mark_output(_h3.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) def test_tf_layers_Conv2D(): print("\ntf.layers.Conv2D --------------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") conv = tf.compat.v1.layers.Conv2D( \ cOut, [hW,wW], strides=(1, 1), padding="same", data_format="channels_last", dilation_rate=(1, 1), activation=tf.nn.relu, use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=False, name="convolution", ) y = conv(x) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_layers_Conv2D.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, -1, nC)) profile.set_shape(inputT0.name, [1, 1, 1, nC], [nB, nH, nW, nC], [nB * 2, nH * 2, nW * 2, nC]) config.add_optimization_profile(profile) _h1 = network.add_shuffle(inputT0) # NHWC to NCHW _h1.first_transpose = (0, 3, 1, 2) para = np.load("./para_tf_layers_Conv2D.npz") weight = np.ascontiguousarray(para["convolution/kernel:0"].transpose(3, 2, 0, 1).reshape(-1)) bias = np.ascontiguousarray(para["convolution/bias:0"].reshape(-1)) _h2 = network.add_convolution_nd(_h1.get_output(0), cOut, [hW, wW], weight, bias) _h2.padding_nd = (2, 2) _h3 = network.add_activation(_h2.get_output(0), trt.ActivationType.RELU) _h4 = network.add_shuffle(_h3.get_output(0)) # NCHW to NHWC, align with TF _h4.first_transpose = (0, 2, 3, 1) network.mark_output(_h4.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) def test_tf_keras_layer_Conv2D(): print("\ntf.keras.layers.Conv2D --------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") conv = tf.keras.layers.Conv2D( \ cOut, [hW,wW], strides=(1, 1), padding="same", data_format="channels_last", dilation_rate=(1, 1), activation=tf.nn.relu, use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None ) y = conv(x) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_keras_layer_Conv2D.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, -1, nC)) profile.set_shape(inputT0.name, [1, 1, 1, nC], [nB, nH, nW, nC], [nB * 2, nH * 2, nW * 2, nC]) config.add_optimization_profile(profile) _h1 = network.add_shuffle(inputT0) # NHWC to NCHW _h1.first_transpose = (0, 3, 1, 2) para = np.load("./para_tf_keras_layer_Conv2D.npz") weight = np.ascontiguousarray(para["conv2d/kernel:0"].transpose(3, 2, 0, 1).reshape(-1)) bias = np.ascontiguousarray(para["conv2d/bias:0"].reshape(-1)) _h2 = network.add_convolution_nd(_h1.get_output(0), cOut, [hW, wW], weight, bias) _h2.padding_nd = (2, 2) _h3 = network.add_activation(_h2.get_output(0), trt.ActivationType.RELU) _h4 = network.add_shuffle(_h3.get_output(0)) # NCHW to NHWC, align with TF _h4.first_transpose = (0, 2, 3, 1) network.mark_output(_h4.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) if __name__ == "__main__": cudart.cudaDeviceSynchronize() np.set_printoptions(precision=3, linewidth=200, suppress=True) test_tf_nn_conv2d() test_tf_layers_Conv2D() test_tf_keras_layer_Conv2D() print("\ntest finish!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/TypicalAPI-TensorFlow1/Convolution.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import sys from datetime import datetime as dt import cv2 import numpy as np import tensorrt as trt from cuda import cudart os.environ["TF_ENABLE_DEPRECATION_WARNINGS"] = "1" os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf tf.compat.v1.disable_eager_execution() np.random.seed(31193) tf.compat.v1.set_random_seed(97) nB, nC, nH, nW = 2, 1, 28, 28 cOut = 32 inputData = np.random.rand(nB, nH, nW, nC).astype(np.float32).reshape([nB, nH, nW, nC]) # NHWC format def printArrayInformation(x, info="", n=5): if 0 in x.shape: print('%s:%s' % (info, str(x.shape))) print() return print( '%s:%s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \ info,str(x.shape),np.sum(abs(x)),np.var(x),np.max(x),np.min(x),np.sum(np.abs(np.diff(x.reshape(-1)))) )) print('\t', x.reshape(-1)[:n], x.reshape(-1)[-n:]) def check(a, b, weak=False, checkEpsilon=1e-5): if weak: a = a.astype(np.float32) b = b.astype(np.float32) res = np.all(np.abs(a - b) < checkEpsilon) else: res = np.all(a == b) diff0 = np.max(np.abs(a - b)) diff1 = np.max(np.abs(a - b) / (np.abs(b) + checkEpsilon)) print("check:%s, absDiff=%f, relDiff=%f" % (res, diff0, diff1)) def test_tf_nn_linalg_matmul(): print("\ntf.nn.linalg.matmul -----------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") weight = tf.compat.v1.get_variable("w1", shape=[nH * nW * nC, cOut], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) _h1 = tf.reshape(x, [-1, nH * nW * nC]) y = tf.linalg.matmul( \ _h1, weight, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name="y" ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_nn_linalg_matmul.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, nH, nW, nC)) profile.set_shape(inputT0.name, [1, nH, nW, nC], [nB, nH, nW, nC], [nB * 2, nH, nW, nC]) config.add_optimization_profile(profile) weight = np.load("./para_tf_nn_linalg_matmul.npz")["w1:0"].transpose(1, 0).reshape(-1) _h1 = network.add_fully_connected(inputT0, cOut, weight, None) _h2 = network.add_shape(_h1.get_output(0)) # remove the last two dimension (1,1), align with TF _h3 = network.add_slice(_h2.get_output(0), [0], [2], [1]) _h4 = network.add_shuffle(_h1.get_output(0)) _h4.set_input(1, _h3.get_output(0)) network.mark_output(_h4.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) def test_tf_layers_Dense(): print("\ntf.layers.Dense ---------------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") _h1 = tf.reshape(x, [-1, nH * nW * nC]) fc = tf.compat.v1.layers.Dense( \ cOut, activation=tf.nn.relu, use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=False, name="tf-layers-Dense-FC" ) y = fc(_h1) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_layers_Dense.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, nH, nW, nC)) profile.set_shape(inputT0.name, [1, nH, nW, nC], [nB, nH, nW, nC], [nB * 2, nH, nW, nC]) config.add_optimization_profile(profile) para = np.load("./para_tf_layers_Dense.npz") weight = para["tf-layers-Dense-FC/kernel:0"].transpose(1, 0).reshape(-1) bias = para["tf-layers-Dense-FC/bias:0"].reshape(-1) _h1 = network.add_fully_connected(inputT0, cOut, weight, bias) _h2 = network.add_activation(_h1.get_output(0), trt.ActivationType.RELU) _h3 = network.add_shape(_h2.get_output(0)) # remove the last two dimension (1,1), align with TF _h4 = network.add_slice(_h3.get_output(0), [0], [2], [1]) _h5 = network.add_shuffle(_h2.get_output(0)) _h5.set_input(1, _h4.get_output(0)) network.mark_output(_h5.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) def test_tf_keras_layers_Dense(): print("\ntf.keras.layers.Dense ---------------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nH, nW, nC], name="x") _h1 = tf.reshape(x, [-1, nH * nW * nC]) fc = tf.keras.layers.Dense( \ cOut, activation=tf.nn.relu, use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="tf-keras-layers-Dense-FC" ) y = fc(_h1) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF = sess.run(y, feed_dict={x: inputData}) tfPara = {} # save weight as file print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("para_tf_keras_layers_Dense.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, nH, nW, nC)) profile.set_shape(inputT0.name, [1, nH, nW, nC], [nB, nH, nW, nC], [nB * 2, nH, nW, nC]) config.add_optimization_profile(profile) para = np.load("./para_tf_keras_layers_Dense.npz") weight = para["tf-keras-layers-Dense-FC/kernel:0"].transpose(1, 0).reshape(-1) bias = para["tf-keras-layers-Dense-FC/bias:0"].reshape(-1) _h1 = network.add_fully_connected(inputT0, cOut, weight, bias) _h2 = network.add_activation(_h1.get_output(0), trt.ActivationType.RELU) _h3 = network.add_shape(_h2.get_output(0)) # remove the last two dimension (1,1), align with TF _h4 = network.add_slice(_h3.get_output(0), [0], [2], [1]) _h5 = network.add_shuffle(_h2.get_output(0)) _h5.set_input(1, _h4.get_output(0)) network.mark_output(_h5.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nB, nH, nW, nC]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputData.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) printArrayInformation(inputData, "input") #print(inputData) printArrayInformation(outputTF, "TF output") #print(outputTF) printArrayInformation(outputH0, "TRT output") #print(outputH0) check(outputTF, outputH0, True) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) if __name__ == "__main__": cudart.cudaDeviceSynchronize() np.set_printoptions(precision=3, linewidth=200, suppress=True) test_tf_nn_linalg_matmul() test_tf_layers_Dense() test_tf_keras_layers_Dense() print("\ntest finish!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/TypicalAPI-TensorFlow1/FullyConnected.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt import numpy as np import tensorrt as trt from cuda import cudart os.environ["TF_ENABLE_DEPRECATION_WARNINGS"] = "1" os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf tf.compat.v1.disable_eager_execution() np.random.seed(31193) tf.compat.v1.set_random_seed(97) epsilon = 1e-6 nBatchSize, nSequenceLength, nInputDim, nHiddenDim = 2, 4, 7, 5 inputX = np.random.rand(nBatchSize, nSequenceLength, nInputDim).astype(np.float32).reshape([nBatchSize, nSequenceLength, nInputDim]) inputH = np.random.rand(nBatchSize, nHiddenDim).astype(np.float32).reshape([nBatchSize, nHiddenDim]) inputC = np.random.rand(nBatchSize, nHiddenDim).astype(np.float32).reshape([nBatchSize, nHiddenDim]) def printArrayInformation(x, info="", n=5): if 0 in x.shape: print('%s:%s' % (info, str(x.shape))) print() return print( '%s:%s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \ info,str(x.shape),np.sum(abs(x)),np.var(x),np.max(x),np.min(x),np.sum(np.abs(np.diff(x.reshape(-1)))) )) print('\t', x.reshape(-1)[:n], x.reshape(-1)[-n:]) def check(a, b, weak=False, checkEpsilon=1e-5): if weak: a = a.astype(np.float32) b = b.astype(np.float32) res = np.all(np.abs(a - b) < checkEpsilon) else: res = np.all(a == b) diff0 = np.max(np.abs(a - b)) diff1 = np.max(np.abs(a - b) / (np.abs(b) + checkEpsilon)) print("check:%s, absDiff=%f, relDiff=%f" % (res, diff0, diff1)) # for debug def smallTest(x0, h0, c0): def sigmoid(x): return 1 / (1 + np.exp(-x)) para = np.load("test?.npz") weight = [np.split(i, [nInputDim], axis=0) for i in np.split(para["?/kernel:0"], 4, axis=1)] bias = np.split(para["?/bias:0"], 4) h, c = h0, c0 for t in range(nSequenceLength): x = x0[:, t, :] it = sigmoid(np.matmul(x, weight[0][0]) + np.matmul(h, weight[0][1]) + bias[0]) ct_ = np.tanh(np.matmul(x, weight[1][0]) + np.matmul(h, weight[1][1]) + bias[1]) ft = sigmoid(np.matmul(x, weight[2][0]) + np.matmul(h, weight[2][1]) + bias[2]) ot = sigmoid(np.matmul(x, weight[3][0]) + np.matmul(h, weight[3][1]) + bias[3]) ct = ft * c0 + it * ct_ ht = ot * np.tanh(ct) print("ht=\n", ht, "\nct=\n", ct) h = ht c = ct print("here") return def test1(): print("\ntf.keras.layers.LSTM or tf.keras.layers.LSTMCell + tf.keras.layers.RNN") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="c0") # Two equivalent realization if True: # tf.keras.layers.LSTM lstm = tf.compat.v1.keras.layers.LSTM( \ nHiddenDim, activation="tanh", recurrent_activation="sigmoid", use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), recurrent_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), unit_forget_bias=False, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, implementation=1, return_sequences=True, return_state=True, go_backwards=False, stateful=False, unroll=False, time_major=False ) else: # tf.keras.layers.LSTMCell + tf.keras.layers.RNN cell = tf.keras.layers.LSTMCell( \ nHiddenDim, activation="tanh", recurrent_activation="sigmoid", use_bias=True, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), recurrent_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), unit_forget_bias=False, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, ) lstm = tf.keras.layers.RNN( \ cell, return_sequences=True, return_state=True, go_backwards=False, stateful=False, unroll=False, time_major=False ) y, h1, c1 = lstm(x, initial_state=[h0, c0]) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFh1, outputTFc1 = sess.run([y, h1, c1], feed_dict={x: inputX, h0: inputH, c0: inputC}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test1.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ # Two equivalent realization if True: # use Loop Structure, Dynamic Shape mode is supported but Refit is not supported logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test1.npz") weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], np.ascontiguousarray(i.reshape(-1))) for i in np.split(para["lstm/kernel:0"], 4, axis=1)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], np.ascontiguousarray(i.reshape(-1))) for i in np.split(para["lstm/recurrent_kernel:0"], 4, axis=1)] biasLayerList = [network.add_constant([1, nHiddenDim], np.ascontiguousarray(i.reshape(-1))) for i in np.split(para["lstm/bias:0"], 4)] loop = network.add_loop() def gate(network, xTensor, wx, hTensor, wh, b, isSigmoid): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) _h4 = network.add_activation(_h3.get_output(0), trt.ActivationType.SIGMOID if isSigmoid else trt.ActivationType.TANH) return _h4 _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), True) gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), True) gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), False) gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), True) _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) newHiddenStateLayer = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) #printArrayInformation(inputX,"x") #print(inputX) #printArrayInformation(inputH,"h0") #print(inputH) #printArrayInformation(inputC,"c0") #print(inputC) #printArrayInformation(outputTFh1,"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFc1,"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFh1, outputH0, True, "h1") check(outputTFc1, outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) else: # use RNNV2 layer, Dynamic Shape mode is not supported, deprecated since TensorRT 8.5 logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (nBatchSize, nSequenceLength, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (nBatchSize, 1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (nBatchSize, 1, nHiddenDim)) rnnV2Layer = network.add_rnn_v2(inputT0, 1, nHiddenDim, nSequenceLength, trt.RNNOperation.LSTM) rnnV2Layer.direction = trt.RNNDirection.UNIDIRECTION rnnV2Layer.input_mode = trt.RNNInputMode.LINEAR rnnV2Layer.hidden_state = inputT1 rnnV2Layer.cell_state = inputT2 gateList = [trt.RNNGateType.INPUT, trt.RNNGateType.FORGET, trt.RNNGateType.CELL, trt.RNNGateType.OUTPUT] para = np.load("test1.npz") weightXList = [i.transpose().reshape(-1) for i in np.split(para["lstm/kernel:0"], 4, axis=1)] weightHList = [i.transpose().reshape(-1) for i in np.split(para["lstm/recurrent_kernel:0"], 4, axis=1)] biasList = [i.reshape(-1) for i in np.split(para["lstm/bias:0"], 4)] for gate, weightX, weightH, bias in zip(gateList, weightXList, weightHList, biasList): rnnV2Layer.set_weights_for_gate(0, gate, True, weightX) rnnV2Layer.set_weights_for_gate(0, gate, False, weightH) rnnV2Layer.set_bias_for_gate(0, gate, True, bias) rnnV2Layer.set_bias_for_gate(0, gate, False, np.zeros([nHiddenDim], dtype=np.float32)) network.mark_output(rnnV2Layer.get_output(0)) network.mark_output(rnnV2Layer.get_output(1)) network.mark_output(rnnV2Layer.get_output(2)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) #print("inputH0 :", inputX.shape) #print(inputX) #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH0,"TRT AllOutput") #printArrayInformation(outputTFh1,"TF h1") #printArrayInformation(outputH1,"TRT h1") #printArrayInformation(outputTFc1,"TF c1") #printArrayInformation(outputH2,"TRT c1") check(outputTF, outputH0, True, "AllOutput") check(outputTFh1, outputH1.reshape(nBatchSize, nHiddenDim), True, "h1") check(outputTFc1, outputH2.reshape(nBatchSize, nHiddenDim), True, "c1") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) def test2(): print("\ntf.keras.layers.CuDNNLSTM -----------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="c0") lstm = tf.compat.v1.keras.layers.CuDNNLSTM( \ nHiddenDim, kernel_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), recurrent_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), bias_initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1), unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=True, return_state=True, go_backwards=False, stateful=False, time_major=False ) y, h1, c1 = lstm(x, initial_state=[h0, c0]) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFh1, outputTFc1 = sess.run([y, h1, c1], feed_dict={x: inputX, h0: inputH, c0: inputC}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test2.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test2.npz") # the shape and order of the weights is different from keras.layers.LSTM weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], i.reshape(nHiddenDim, nInputDim).transpose().reshape(-1)) for i in np.split(para["cu_dnnlstm/kernel:0"], 4, axis=1)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], i.transpose().reshape(-1)) for i in np.split(para["cu_dnnlstm/recurrent_kernel:0"], 4, axis=1)] biasLayerList = [network.add_constant([1, nHiddenDim], i.reshape(-1)) for i in np.split(np.sum(para["cu_dnnlstm/bias:0"].reshape(2, -1), axis=0), 4)] loop = network.add_loop() def gate(network, xTensor, wx, hTensor, wh, b, isSigmoid): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) _h4 = network.add_activation(_h3.get_output(0), trt.ActivationType.SIGMOID if isSigmoid else trt.ActivationType.TANH) return _h4 _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), True) gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), True) gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), False) gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), True) _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) newHiddenStateLayer = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) #printArrayInformation(inputX,"input") #print(inputX) #printArrayInformation(outputTFh1,"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFc1,"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFh1, outputH0, True, "h1") check(outputTFc1, outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) def test3(): print("\n[tf.nn.rnn_cell.BasicLSTMCell / tf.contrib.rnn.BasicLSTMCell] + [tf.nn.static_rnn / tf.nn.dynamic_rnn]") forgetBias = 1.0 # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="c0") # tf.nn.rnn_cell.BasicLSTMCell and tf.contrib.rnn.BasicLSTMCell are alias cell = tf.nn.rnn_cell.BasicLSTMCell( \ #cell = tf.contrib.rnn.BasicLSTMCell( \ nHiddenDim, forget_bias=forgetBias, state_is_tuple=True, activation=None, reuse=None, name=None, dtype=None ) # Two equivalent realization if True: y,hc = tf.nn.static_rnn( \ cell, [ x[:,i,:] for i in range(nSequenceLength) ], initial_state=[c0,h0], dtype=None, sequence_length=None, scope=None ) else: y,hc = tf.nn.dynamic_rnn( \ cell, x, sequence_length=None, initial_state=[c0,h0], dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFhc = sess.run([y, hc], feed_dict={x: inputX, h0: inputH, c0: inputC}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test3.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test3.npz") weight = [np.split(i, [nInputDim], axis=0) for i in np.split(para["rnn/basic_lstm_cell/kernel:0"], 4, axis=1)] bias = np.split(para["rnn/basic_lstm_cell/bias:0"], 4) weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], weight[i][0].reshape(-1)) for i in range(4)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], weight[i][1].reshape(-1)) for i in range(4)] biasLayerList = [network.add_constant([1, nHiddenDim], bias[i]) for i in range(4)] loop = network.add_loop() def gate(network, xTensor, wx, hTensor, wh, b, gateName): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) if gateName == "F" and np.abs(forgetBias) > epsilon: _constant = network.add_constant([1, 1], np.array(forgetBias, dtype=np.float32)) _h4 = network.add_elementwise(_h3.get_output(0), _constant.get_output(0), trt.ElementWiseOperation.SUM) else: _h4 = _h3 if gateName == "C": _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.TANH) else: _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.SIGMOID) return _h5 _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) # order if weights is ICFO, rather than IFCO gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), "I") gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), "C") gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), "F") gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), "O") _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) newHiddenStateLayer = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) outputTF = np.concatenate([x[:, np.newaxis, :] for x in outputTF], axis=1) #printArrayInformation(inputX,"input") #print(inputX) #printArrayInformation(outputTFhc[1],"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFhc[0],"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFhc[1], outputH0, True, "h1") check(outputTFhc[0], outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) def test4(): print("\n[tf.nn.rnn_cell.LSTMCell / tf.contrib.rnn.LSTMCell] + [tf.nn.static_rnn / tf.nn.dynamic_rnn]") forgetBias = 1.0 useProjection = True # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="c0") # tf.nn.rnn_cell.LSTMCell and tf.contrib.rnn.LSTMCell are alias cell = tf.nn.rnn_cell.LSTMCell( \ #cell = tf.contrib.rnn.LSTMCell( \ nHiddenDim, use_peepholes=False, cell_clip=None, initializer=None, num_proj=(nHiddenDim if useProjection else None), # only None or nHiddenDim are supported? the order of weights using None is the same as the version which name contains Basic. proj_clip=None, num_unit_shards=None, num_proj_shards=None, forget_bias=forgetBias, state_is_tuple=True, activation=None, reuse=None, name=None, dtype=None, ) # Two equivalent realization if True: y,hc = tf.nn.static_rnn( \ cell, [ x[:,i,:] for i in range(nSequenceLength) ], initial_state=[c0,h0], dtype=None, sequence_length=None, scope=None ) else: y,hc = tf.nn.dynamic_rnn( \ cell, x, sequence_length=None, initial_state=[c0,h0], dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFhc = sess.run([y, hc], feed_dict={x: inputX, h0: inputH, c0: inputC}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test4.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test4.npz") weight = [np.split(i, [nInputDim], axis=0) for i in np.split(para["rnn/lstm_cell/kernel:0"], 4, axis=1)] bias = np.split(para["rnn/lstm_cell/bias:0"], 4) weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], weight[i][0].reshape(-1)) for i in range(4)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], weight[i][1].reshape(-1)) for i in range(4)] biasLayerList = [network.add_constant([1, nHiddenDim], bias[i]) for i in range(4)] loop = network.add_loop() def gate(network, xTensor, wx, hTensor, wh, b, gateName): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) if gateName == "F" and np.abs(forgetBias) > epsilon: _constant = network.add_constant([1, 1], np.array(forgetBias, dtype=np.float32)) _h4 = network.add_elementwise(_h3.get_output(0), _constant.get_output(0), trt.ElementWiseOperation.SUM) else: _h4 = _h3 if gateName == "C": _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.TANH) else: _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.SIGMOID) return _h5 _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) # the order of weights is ICFO rather than IFCO gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), "I") gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), "C") gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), "F") gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), "O") _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) _h8 = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) if useProjection: matrix2D = network.add_constant([nHiddenDim, nHiddenDim], para["rnn/lstm_cell/projection/kernel:0"].astype(np.float32)) newHiddenStateLayer = network.add_matrix_multiply(_h8.get_output(0), trt.MatrixOperation.NONE, matrix2D.get_output(0), trt.MatrixOperation.NONE) else: newHiddenStateLayer = _h8 hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) outputTF = np.concatenate([x[:, np.newaxis, :] for x in outputTF], axis=1) #printArrayInformation(inputX,"input") #print(inputX) #printArrayInformation(outputTFhc[1],"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFhc[0],"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFhc[1], outputH0, True, "h1") check(outputTFhc[0], outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) def test5(): print("\ntf.contrib.cudnn_rnn.CudnnLSTM ------------------------------------") # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, 1, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, 1, nHiddenDim], name="c0") lstm = tf.contrib.cudnn_rnn.CudnnLSTM( \ 1, nHiddenDim, input_mode="linear_input", direction="unidirectional", dropout=0.0, seed=None, dtype=tf.dtypes.float32, kernel_initializer=None, bias_initializer=None, name=None ) y, hc = lstm( x, initial_state=(h0, c0), # [h0,c0] rather than [c0,h0] sequence_lengths=None, time_major=False, training=False ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFhc = sess.run([y, hc], feed_dict={x: inputX, h0: inputH.reshape([nBatchSize, 1, nHiddenDim]), c0: inputC.reshape([nBatchSize, 1, nHiddenDim])}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test5.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test5.npz")["cudnn_lstm/opaque_kernel:0"] # --------------------------------+-------------------------------+ # | weight | bias | # --------------------------------+-------------------------------+ # |wIX|wCX|wFX|wOX|wIH|wCH|wFH|wOH|bIX|bCX|bFX|bOX|bIH|bCH|bFH|bOH| # --------------------------------+-------------------------------+ weightX, weightH, bias = np.split(para, [nInputDim * nHiddenDim * 4, (nInputDim + nHiddenDim) * nHiddenDim * 4]) weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], i.reshape(nHiddenDim, nInputDim).transpose().reshape(-1)) for i in np.split(weightX, 4)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], i.reshape(nHiddenDim, nHiddenDim).transpose().reshape(-1)) for i in np.split(weightH, 4)] biasLayerList = [network.add_constant([1, nHiddenDim], i.reshape(-1)) for i in np.split(np.sum(bias.reshape(2, -1), axis=0), 4)] def gate(network, xTensor, wx, hTensor, wh, b, isSigmoid): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) _h4 = network.add_activation(_h3.get_output(0), trt.ActivationType.SIGMOID if isSigmoid else trt.ActivationType.TANH) return _h4 loop = network.add_loop() _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), True) gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), True) gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), False) gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), True) _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) newHiddenStateLayer = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) outputTFhc = [i[:, 0, :] for i in outputTFhc] #printArrayInformation(inputX,"input") #print(inputX) #printArrayInformation(outputTFhc[0],"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFhc[1],"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFhc[0], outputH0, True, "h1") check(outputTFhc[1], outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) def test6(): print("\n[tf.contrib.rnn.LSTMBlockCell / tf.contrib.rnn.LSTMBlockFusedCell] + [tf.nn.static_rnn / tf.nn.dynamic_rnn]") forgetBias = 1.0 # TensorFlow part ---------------------------------------------------------- x = tf.compat.v1.placeholder(tf.float32, [None, nSequenceLength, nInputDim], name="x") h0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="h0") c0 = tf.compat.v1.placeholder(tf.float32, [None, nHiddenDim], name="c0") # tf.contrib.rnn.LSTMBlockCell and tf.contrib.rnn.LSTMBlockFusedCell shares the same API and the order of weights cell = tf.contrib.rnn.LSTMBlockCell( \ #cell = tf.contrib.rnn.LSTMBlockFusedCell( \ nHiddenDim, forget_bias=forgetBias, cell_clip=None, use_peephole=False, dtype=None, reuse=None, name="tf-contrib-rnn-LSTMBlockCell-LSTM" ) # Two equivalent realization if True: y,hc = tf.nn.static_rnn( \ cell, [ x[:,i,:] for i in range(nSequenceLength) ], initial_state=[c0,h0], dtype=None, sequence_length=None, scope=None ) else: y,hc = tf.nn.dynamic_rnn( \ cell, x, sequence_length=None, initial_state=[c0,h0], dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None ) tfConfig = tf.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.compat.v1.Session(config=tfConfig) sess.run(tf.compat.v1.global_variables_initializer()) outputTF, outputTFhc = sess.run([y, hc], feed_dict={x: inputX, h0: inputH, c0: inputC}) tfPara = {} print("Weight:") for i in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.GLOBAL_VARIABLES): name, value = i.name, sess.run(i) print(name, value.shape) tfPara[name] = value np.savez("test6.npz", **tfPara) sess.close() # TensorRT part ------------------------------------------------------------ logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() inputT0 = network.add_input("inputT0", trt.float32, (-1, -1, nInputDim)) inputT1 = network.add_input("inputT1", trt.float32, (-1, nHiddenDim)) inputT2 = network.add_input("inputT2", trt.float32, (-1, nHiddenDim)) profile.set_shape(inputT0.name, [1, 1, nInputDim], [nBatchSize, nSequenceLength, nInputDim], [nBatchSize * 2, nSequenceLength * 2, nInputDim]) profile.set_shape(inputT1.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) profile.set_shape(inputT2.name, [1, nHiddenDim], [nBatchSize, nHiddenDim], [nBatchSize * 2, nHiddenDim]) config.add_optimization_profile(profile) para = np.load("test6.npz") weight = [np.split(i, [nInputDim], axis=0) for i in np.split(para["rnn/tf-contrib-rnn-LSTMBlockCell-LSTM/kernel:0"], 4, axis=1)] bias = np.split(para["rnn/tf-contrib-rnn-LSTMBlockCell-LSTM/bias:0"], 4) weightXLayerList = [network.add_constant([nInputDim, nHiddenDim], weight[i][0].reshape(-1)) for i in range(4)] weightHLayerList = [network.add_constant([nHiddenDim, nHiddenDim], weight[i][1].reshape(-1)) for i in range(4)] biasLayerList = [network.add_constant([1, nHiddenDim], bias[i]) for i in range(4)] loop = network.add_loop() def gate(network, xTensor, wx, hTensor, wh, b, gateName): _h0 = network.add_matrix_multiply(xTensor, trt.MatrixOperation.NONE, wx, trt.MatrixOperation.NONE) _h1 = network.add_matrix_multiply(hTensor, trt.MatrixOperation.NONE, wh, trt.MatrixOperation.NONE) _h2 = network.add_elementwise(_h0.get_output(0), _h1.get_output(0), trt.ElementWiseOperation.SUM) _h3 = network.add_elementwise(_h2.get_output(0), b, trt.ElementWiseOperation.SUM) if gateName == "F" and np.abs(forgetBias) > epsilon: _constant = network.add_constant([1, 1], np.array(forgetBias, dtype=np.float32)) _h4 = network.add_elementwise(_h3.get_output(0), _constant.get_output(0), trt.ElementWiseOperation.SUM) else: _h4 = _h3 if gateName == "C": _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.TANH) else: _h5 = network.add_activation(_h4.get_output(0), trt.ActivationType.SIGMOID) return _h5 _t0 = network.add_shape(inputT0) _t1 = network.add_slice(_t0.get_output(0), [1], [1], [1]) _t2 = network.add_shuffle(_t1.get_output(0)) _t2.reshape_dims = () loop.add_trip_limit(_t2.get_output(0), trt.TripLimit.COUNT) iteratorLayer = loop.add_iterator(inputT0, 1, False) # iterator throws one piece of inputT0 each time, shape: [nBatchSize, nInputDim] hiddenStateLayer = loop.add_recurrence(inputT1) # initial hidden state and cell state cellStateLayer = loop.add_recurrence(inputT2) # ICFO not IFCO gateI = gate(network, iteratorLayer.get_output(0), weightXLayerList[0].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[0].get_output(0), biasLayerList[0].get_output(0), "I") gateC = gate(network, iteratorLayer.get_output(0), weightXLayerList[1].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[1].get_output(0), biasLayerList[1].get_output(0), "C") gateF = gate(network, iteratorLayer.get_output(0), weightXLayerList[2].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[2].get_output(0), biasLayerList[2].get_output(0), "F") gateO = gate(network, iteratorLayer.get_output(0), weightXLayerList[3].get_output(0), hiddenStateLayer.get_output(0), weightHLayerList[3].get_output(0), biasLayerList[3].get_output(0), "O") _h5 = network.add_elementwise(gateF.get_output(0), cellStateLayer.get_output(0), trt.ElementWiseOperation.PROD) _h6 = network.add_elementwise(gateI.get_output(0), gateC.get_output(0), trt.ElementWiseOperation.PROD) newCellStateLayer = network.add_elementwise(_h5.get_output(0), _h6.get_output(0), trt.ElementWiseOperation.SUM) _h7 = network.add_activation(newCellStateLayer.get_output(0), trt.ActivationType.TANH) newHiddenStateLayer = network.add_elementwise(gateO.get_output(0), _h7.get_output(0), trt.ElementWiseOperation.PROD) hiddenStateLayer.set_input(1, newHiddenStateLayer.get_output(0)) cellStateLayer.set_input(1, newCellStateLayer.get_output(0)) loopOutput0 = loop.add_loop_output(hiddenStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final hidden state, shape: [nBatchSize,nHiddenSize] loopOutput1 = loop.add_loop_output(newHiddenStateLayer.get_output(0), trt.LoopOutput.CONCATENATE, 1) # output all hidden state, shape: [nBatchSize,nSequenceLength,nHiddenSize] loopOutput1.set_input(1, _t2.get_output(0)) loopOutput2 = loop.add_loop_output(cellStateLayer.get_output(0), trt.LoopOutput.LAST_VALUE, 0) # output final cell state, shape: [nBatchSize,nHiddenSize] network.mark_output(loopOutput0.get_output(0)) network.mark_output(loopOutput1.get_output(0)) network.mark_output(loopOutput2.get_output(0)) engineString = builder.build_serialized_network(network, config) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_input_shape(engine.get_tensor_name(0), [nBatchSize, nSequenceLength, nInputDim]) context.set_input_shape(engine.get_tensor_name(1), [nBatchSize, nHiddenDim]) context.set_input_shape(engine.get_tensor_name(2), [nBatchSize, nHiddenDim]) _, stream = cudart.cudaStreamCreate() inputH0 = np.ascontiguousarray(inputX.reshape(-1)) inputH1 = np.ascontiguousarray(inputH.reshape(-1)) inputH2 = np.ascontiguousarray(inputC.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(3), dtype=trt.nptype(engine.get_binding_dtype(3))) outputH1 = np.empty(context.get_binding_shape(4), dtype=trt.nptype(engine.get_binding_dtype(4))) outputH2 = np.empty(context.get_binding_shape(5), dtype=trt.nptype(engine.get_binding_dtype(5))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, inputD1 = cudart.cudaMallocAsync(inputH1.nbytes, stream) _, inputD2 = cudart.cudaMallocAsync(inputH2.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) _, outputD1 = cudart.cudaMallocAsync(outputH1.nbytes, stream) _, outputD2 = cudart.cudaMallocAsync(outputH2.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD1, inputH1.ctypes.data, inputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) cudart.cudaMemcpyAsync(inputD2, inputH2.ctypes.data, inputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(inputD1), int(inputD2), int(outputD0), int(outputD1), int(outputD2)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH1.ctypes.data, outputD1, outputH1.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaMemcpyAsync(outputH2.ctypes.data, outputD2, outputH2.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) outputTF = np.concatenate([x[:, np.newaxis, :] for x in outputTF], axis=1) #printArrayInformation(inputX,"input") #print(inputX) #printArrayInformation(outputTFhc[1],"TF h1") #printArrayInformation(outputH0,"TRT h1") #printArrayInformation(outputTFhc[0],"TF c1") #printArrayInformation(outputH2,"TRT c1") #printArrayInformation(outputTF,"TF AllOutput") #printArrayInformation(outputH1,"TRT AllOutput") check(outputTFhc[1], outputH0, True, "h1") check(outputTFhc[0], outputH2, True, "c1") check(outputTF, outputH1, True, "AllOutput") cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(inputD1) cudart.cudaFree(inputD2) cudart.cudaFree(outputD0) cudart.cudaFree(outputD1) cudart.cudaFree(outputD2) if __name__ == "__main__": cudart.cudaDeviceSynchronize() np.set_printoptions(precision=3, linewidth=200, suppress=True) test1() # tf.keras.layers.LSTM or tf.keras.layers.LSTMCell + tf.keras.layers.RNN test2() # tf.keras.layers.CuDNNLSTM test3() # tf.nn.rnn_cell.BasicLSTMCell / tf.contrib.rnn.BasicLSTMCell + tf.nn.static_rnn / tf.nn.dynamic_rnn test4() # tf.nn.rnn_cell.LSTMCell / tf.contrib.rnn.LSTMCell + tf.nn.static_rnn / tf.nn.dynamic_rnn test5() # tf.contrib.cudnn_rnn.CudnnLSTM test6() # tf.contrib.rnn.LSTMBlockCell / tf.contrib.rnn.LSTMBlockFusedCell + tf.nn.static_rnn / tf.nn.dynamic_rnn print("\ntest finish!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/TypicalAPI-TensorFlow1/RNN-LSTM.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-TensorFlow2/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf2 import tensorrt as trt np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 paraFile = "./para.npz" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.npz ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow2 -------------------------------- def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) para = {} # save weight as file print("Parameter of the model:") for weight in model.weights: name, value = weight.name, weight.numpy() print("%s:\t%s" % (name, value.shape)) para[name] = value np.savez(paraFile, **para) del para print("Succeeded building model in TensorFlow2!") # Rebuild network, load weights and do inference in TensorRT ------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, nHeight, nWidth]) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) para = np.load(paraFile) w = np.ascontiguousarray(para["conv1/kernel:0"].transpose(3, 2, 0, 1)) b = np.ascontiguousarray(para["conv1/bias:0"]) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(para["conv2/kernel:0"].transpose(3, 2, 0, 1)) b = np.ascontiguousarray(para["conv2/bias:0"]) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.first_transpose = (0, 2, 3, 1) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(para["dense1/kernel:0"]) b = np.ascontiguousarray(para["dense1/bias:0"].reshape(1, -1)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(para["dense2/kernel:0"]) b = np.ascontiguousarray(para["dense2/bias:0"].reshape(1, -1)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-TensorFlow2/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-pyTorch/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import calibrator import cv2 import numpy as np import tensorrt as trt import torch as t import torch.nn.functional as F from cuda import cudart from torch.autograd import Variable np.random.seed(31193) t.manual_seed(97) t.cuda.manual_seed_all(97) t.backends.cudnn.deterministic = True nTrainBatchSize = 128 nHeight = 28 nWidth = 28 paraFile = "./para.npz" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.npz ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() # Create network and train model in pyTorch ------------------------------------ class Net(t.nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = t.nn.Conv2d(1, 32, (5, 5), padding=(2, 2), bias=True) self.conv2 = t.nn.Conv2d(32, 64, (5, 5), padding=(2, 2), bias=True) self.fc1 = t.nn.Linear(64 * 7 * 7, 1024, bias=True) self.fc2 = t.nn.Linear(1024, 10, bias=True) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) x = x.reshape(-1, 64 * 7 * 7) x = F.relu(self.fc1(x)) y = self.fc2(x) z = F.softmax(y, dim=1) z = t.argmax(z, dim=1) return y, z class MyData(t.utils.data.Dataset): def __init__(self, isTrain=True): if isTrain: self.data = trainFileList else: self.data = testFileList def __getitem__(self, index): imageName = self.data[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) index = int(imageName[-7]) label[index] = 1 return t.from_numpy(data.reshape(1, nHeight, nWidth).astype(np.float32)), t.from_numpy(label) def __len__(self): return len(self.data) model = Net().cuda() ceLoss = t.nn.CrossEntropyLoss() opt = t.optim.Adam(model.parameters(), lr=0.001) trainDataset = MyData(True) testDataset = MyData(False) trainLoader = t.utils.data.DataLoader(dataset=trainDataset, batch_size=nTrainBatchSize, shuffle=True) testLoader = t.utils.data.DataLoader(dataset=testDataset, batch_size=nTrainBatchSize, shuffle=True) for epoch in range(10): for xTrain, yTrain in trainLoader: xTrain = Variable(xTrain).cuda() yTrain = Variable(yTrain).cuda() opt.zero_grad() y_, z = model(xTrain) loss = ceLoss(y_, yTrain) loss.backward() opt.step() with t.no_grad(): acc = 0 n = 0 for xTest, yTest in testLoader: xTest = Variable(xTest).cuda() yTest = Variable(yTest).cuda() y_, z = model(xTest) acc += t.sum(z == t.matmul(yTest, t.Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).to("cuda:0"))).cpu().numpy() n += xTest.shape[0] print("%s, epoch %2d, loss = %f, test acc = %f" % (dt.now(), epoch + 1, loss.data, acc / n)) para = {} # save weight as file for name, parameter in model.named_parameters(): #print(name, parameter.detach().cpu().numpy().shape) para[name] = parameter.detach().cpu().numpy() np.savez(paraFile, **para) del para print("Succeeded building model in pyTorch!") # Rebuild network, load weights and do inference in TensorRT ------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) inputTensor = network.add_input("inputT0", trt.float32, [-1, 1, nHeight, nWidth]) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) para = np.load(paraFile) w = np.ascontiguousarray(para["conv1.weight"]) b = np.ascontiguousarray(para["conv1.bias"]) _0 = network.add_convolution_nd(inputTensor, 32, [5, 5], trt.Weights(w), trt.Weights(b)) _0.padding_nd = [2, 2] _1 = network.add_activation(_0.get_output(0), trt.ActivationType.RELU) _2 = network.add_pooling_nd(_1.get_output(0), trt.PoolingType.MAX, [2, 2]) _2.stride_nd = [2, 2] w = np.ascontiguousarray(para["conv2.weight"]) b = np.ascontiguousarray(para["conv2.bias"]) _3 = network.add_convolution_nd(_2.get_output(0), 64, [5, 5], trt.Weights(w), trt.Weights(b)) _3.padding_nd = [2, 2] _4 = network.add_activation(_3.get_output(0), trt.ActivationType.RELU) _5 = network.add_pooling_nd(_4.get_output(0), trt.PoolingType.MAX, [2, 2]) _5.stride_nd = [2, 2] _6 = network.add_shuffle(_5.get_output(0)) _6.reshape_dims = (-1, 64 * 7 * 7) w = np.ascontiguousarray(para["fc1.weight"].transpose()) b = np.ascontiguousarray(para["fc1.bias"].reshape(1, -1)) _7 = network.add_constant(w.shape, trt.Weights(w)) _8 = network.add_matrix_multiply(_6.get_output(0), trt.MatrixOperation.NONE, _7.get_output(0), trt.MatrixOperation.NONE) _9 = network.add_constant(b.shape, trt.Weights(b)) _10 = network.add_elementwise(_8.get_output(0), _9.get_output(0), trt.ElementWiseOperation.SUM) _11 = network.add_activation(_10.get_output(0), trt.ActivationType.RELU) w = np.ascontiguousarray(para["fc2.weight"].transpose()) b = np.ascontiguousarray(para["fc2.bias"].reshape(1, -1)) _12 = network.add_constant(w.shape, trt.Weights(w)) _13 = network.add_matrix_multiply(_11.get_output(0), trt.MatrixOperation.NONE, _12.get_output(0), trt.MatrixOperation.NONE) _14 = network.add_constant(b.shape, trt.Weights(b)) _15 = network.add_elementwise(_13.get_output(0), _14.get_output(0), trt.ElementWiseOperation.SUM) _16 = network.add_softmax(_15.get_output(0)) _16.axes = 1 << 1 _17 = network.add_topk(_16.get_output(0), trt.TopKOperation.MAX, 1, 1 << 1) network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-pyTorch/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from glob import glob import cv2 import numpy as np nCalibrationData = 100 nHeight = 28 nWidth = 28 dataPath = "../../../00-MNISTData/" calibrationDataPath = dataPath + "test/" inferenceDataFile = dataPath + "8.png" inferenceData = cv2.imread(inferenceDataFile, cv2.IMREAD_GRAYSCALE).astype(np.float32) calibrationDataFileList = sorted(glob(calibrationDataPath + "*.jpg"))[:nCalibrationData] calibrationData = np.empty([nCalibrationData, 1, nHeight, nWidth]) for i in range(nCalibrationData): calibrationData[i, 0] = cv2.imread(calibrationDataFileList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) dataDictionary = {} dataDictionary["inferenceData"] = inferenceData dataDictionary["calibrationData"] = calibrationData np.savez("data.npz", **dataDictionary) print("Succeeded creating data for calibration and inference!")
trt-samples-for-hackathon-cn-master
cookbook/03-BuildEngineByTensorRTAPI/MNISTExample-pyTorch/C++/createCalibrationAndInferenceData.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np import pytorch_quantization.calib as calib import pytorch_quantization.nn as qnn import tensorrt as trt import torch as t import torch.nn.functional as F from cuda import cudart from pytorch_quantization import quant_modules from pytorch_quantization.tensor_quant import QuantDescriptor from torch.autograd import Variable np.random.seed(31193) t.manual_seed(97) t.cuda.manual_seed_all(97) t.backends.cudnn.deterministic = True nTrainBatchSize = 128 nCalibrationBatch = 4 nHeight = 28 nWidth = 28 onnxFile = "./model.onnx" onnxFilePolygraphy = "./model-p.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for QAT calibrator = ["max", "histogram"][0] percentileList = [99.9, 99.99, 99.999, 99.9999] quant_desc_input = QuantDescriptor(calib_method=calibrator, axis=None) qnn.QuantConv2d.set_default_quant_desc_input(quant_desc_input) qnn.QuantConvTranspose2d.set_default_quant_desc_input(quant_desc_input) qnn.QuantLinear.set_default_quant_desc_input(quant_desc_input) quant_desc_weight = QuantDescriptor(calib_method=calibrator, axis=None) qnn.QuantConv2d.set_default_quant_desc_weight(quant_desc_weight) qnn.QuantConvTranspose2d.set_default_quant_desc_weight(quant_desc_weight) qnn.QuantLinear.set_default_quant_desc_weight(quant_desc_weight) os.system("rm -rf ./*.onnx ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() # Create network and train model in pyTorch ------------------------------------ class Net(t.nn.Module): def __init__(self): super(Net, self).__init__() #self.conv1 = t.nn.Conv2d(1, 32, (5, 5), padding=(2, 2), bias=True) # replace into corresponding Quantize API self.conv1 = qnn.QuantConv2d(1, 32, (5, 5), padding=(2, 2), bias=True) #self.conv2 = t.nn.Conv2d(32, 64, (5, 5), padding=(2, 2), bias=True) self.conv2 = qnn.QuantConv2d(32, 64, (5, 5), padding=(2, 2), bias=True) #self.fc1 = t.nn.Linear(64 * 7 * 7, 1024, bias=True) self.fc1 = qnn.QuantLinear(64 * 7 * 7, 1024, bias=True) #self.fc2 = t.nn.Linear(1024, 10, bias=True) self.fc2 = qnn.QuantLinear(1024, 10, bias=True) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) x = x.reshape(-1, 64 * 7 * 7) x = F.relu(self.fc1(x)) y = self.fc2(x) z = F.softmax(y, dim=1) z = t.argmax(z, dim=1) return y, z class MyData(t.utils.data.Dataset): def __init__(self, isTrain=True): if isTrain: self.data = trainFileList else: self.data = testFileList def __getitem__(self, index): imageName = self.data[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) index = int(imageName[-7]) label[index] = 1 return t.from_numpy(data.reshape(1, nHeight, nWidth).astype(np.float32)), t.from_numpy(label) def __len__(self): return len(self.data) model = Net().cuda() ceLoss = t.nn.CrossEntropyLoss() opt = t.optim.Adam(model.parameters(), lr=0.001) trainDataset = MyData(True) testDataset = MyData(False) trainLoader = t.utils.data.DataLoader(dataset=trainDataset, batch_size=nTrainBatchSize, shuffle=True) testLoader = t.utils.data.DataLoader(dataset=testDataset, batch_size=nTrainBatchSize, shuffle=True) for epoch in range(10): for xTrain, yTrain in trainLoader: xTrain = Variable(xTrain).cuda() yTrain = Variable(yTrain).cuda() opt.zero_grad() y_, z = model(xTrain) loss = ceLoss(y_, yTrain) loss.backward() opt.step() with t.no_grad(): acc = 0 n = 0 for xTest, yTest in testLoader: xTest = Variable(xTest).cuda() yTest = Variable(yTest).cuda() y_, z = model(xTest) acc += t.sum(z == t.matmul(yTest, t.Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).to("cuda:0"))).cpu().numpy() n += xTest.shape[0] print("%s, epoch %2d, loss = %f, test acc = %f" % (dt.now(), epoch + 1, loss.data, acc / n)) print("Succeeded building model in pyTorch!") # Calibrate model in pyTorch --------------------------------------------------- quant_modules.initialize() with t.no_grad(): # turn on calibration tool for name, module in model.named_modules(): if isinstance(module, qnn.TensorQuantizer): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() for i, (xTrain, yTrain) in enumerate(trainLoader): if i >= nCalibrationBatch: break model(Variable(xTrain).cuda()) # turn off calibration tool for name, module in model.named_modules(): if isinstance(module, qnn.TensorQuantizer): if module._calibrator is not None: module.enable_quant() module.disable_calib() else: module.enable() def computeArgMax(model, **kwargs): for _, module in model.named_modules(): if isinstance(module, qnn.TensorQuantizer) and module._calibrator is not None: if isinstance(module._calibrator, calib.MaxCalibrator): module.load_calib_amax() else: module.load_calib_amax(**kwargs) if calibrator == "max": computeArgMax(model, method="max") #modelName = "./model-max-%d.pth" % (nCalibrationBatch * trainLoader.batch_size) else: for percentile in percentileList: computeArgMax(model, method="percentile") #modelName = "./model-percentile-%f-%d.pth" % (percentile, nCalibrationBatch * trainLoader.batch_size) for method in ["mse", "entropy"]: computeArgMax(model, method=method) #modelName = "./model-%s-%f.pth" % (method, percentile) #t.save(model.state_dict(), modelName) print("Succeeded calibrating model in pyTorch!") # Fine-tune model in pyTorch, not required ------------------------------------- model.cuda() for epoch in range(10): for xTrain, yTrain in trainLoader: xTrain = Variable(xTrain).cuda() yTrain = Variable(yTrain).cuda() opt.zero_grad() y_, z = model(xTrain) loss = ceLoss(y_, yTrain) loss.backward() opt.step() with t.no_grad(): acc = 0 n = 0 for xTest, yTest in testLoader: xTest = Variable(xTest).cuda() yTest = Variable(yTest).cuda() y_, z = model(xTest) acc += t.sum(z == t.matmul(yTest, t.Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).to("cuda:0"))).cpu().numpy() n += xTest.shape[0] print("%s, epoch %2d, loss = %f, test acc = %f" % (dt.now(), epoch + 1, loss.data, acc / n)) print("Succeeded fine tuning model in pyTorch!") # Export model as ONNX file ---------------------------------------------------- model.eval() qnn.TensorQuantizer.use_fb_fake_quant = True t.onnx.export(model, t.randn(1, 1, nHeight, nWidth, device="cuda"), onnxFile, input_names=["x"], output_names=["y", "z"], do_constant_folding=True, verbose=True, keep_initializers_as_inputs=True, opset_version=13, dynamic_axes={"x": {0: "nBatchSize"}}) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ os.system("polygraphy surgeon sanitize --fold-constant %s -o %s" % (onnxFile, onnxFilePolygraphy)) logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFilePolygraphy): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFilePolygraphy, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) network.unmark_output(network.get_output(0)) # remove output tensor "y" engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/pyTorch-ONNX-TensorRT-QAT/main.py
""" from cuda import cudart #from datetime import datetime as dt import numpy as np import onnx import onnx_graphsurgeon as gs import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import config_pb2, meta_graph_pb2, rewriter_config_pb2 from tensorflow.python.framework import importer, ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver import tensorrt as trt import cv2 tf2.compat.v1.disable_eager_execution() np.random.seed(31193) tf2.compat.v1.set_random_seed(97) nTrainbatchSize = 256 ckptFile = "./model.ckpt" pbFile = "model-V1.pb" pb2File = "model-V2.pb" onnxFile = "model-V1.onnx" onnx2File = "model-V2.onnx" trtFile = "model.plan" #inferenceImage = dataPath + "8.png" outputNodeName = "z" isRemoveTransposeNode = False # 变量说明见用到该变量的地方 isAddQDQForInput = False # 变量说明见用到该变量的地方 """ import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np #=============================================================================== from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model/" pbFile = "model.pb" onnxFile = "./model.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # 是否保存为单独的一个 .pb文件(两种导出方式),这里选 True 或 Flase 都能导出为 .onnx bSinglePbFile = True # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" #=============================================================================== isAddQDQForInput = False #=============================================================================== #os.system("rm -rf %s ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData # TensorFlow 中创建网络并保存为 .pb 文件 ------------------------------------------- modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) x = modelInput tf2.quantization.quantize(x, ) tf2.quantization.dequantize """ tf.quantization.quantize( input, min_range, max_range, T, mode="MIN_COMBINED", round_mode="HALF_AWAY_FROM_ZERO", name=None, narrow_range=False, axis=None, ensure_minimum_range=0.01 ) tf.quantization.dequantize( input, min_range, max_range, mode="MIN_COMBINED", name=None, axis=None, narrow_range=False, dtype=tf.dtypes.float32 ) """ layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) #history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) history = model.fit(xTrain, yTrain, batch_size=128, epochs=1, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) #checkpoint = tf2.train.Checkpoint(model) #checkpoint.save(checkpointPath) #print("Succeeded saving .ckpt in TensorFlow!") import tensorflow_model_optimization as tfmot modelQAT = tfmot.quantization.keras.quantize_model(model) modelQAT.summary() # `quantize_model` requires a recompile. modelQAT.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) modelQAT.fit(xTrain, yTrain, batch_size=nTrainBatchSize, epochs=1, validation_split=0.1) print("Baseline test accuracy: %.4f" % model.evaluate(xTest, yTest, verbose=0)[1]) print("Quantize test accuracy: %.4f" % modelQAT.evaluate(xTest, yTest, verbose=0)[1]) tf2.saved_model.save(model, pbFilePath) if bSinglePbFile: modelFunction = tf2.function(lambda Input: modelQAT(Input)).get_concrete_function(tf2.TensorSpec(modelQAT.inputs[0].shape, modelQAT.inputs[0].dtype)) frozen_func = convert_variables_to_constants_v2(modelFunction) frozen_func.graph.as_graph_def() print("_________________________________________________________________") print("Frozen model inputs:\n", frozen_func.inputs) print("Frozen model outputs:\n", frozen_func.outputs) print("Frozen model layers:") for op in frozen_func.graph.get_operations(): print(op.name) tf2.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=pbFilePath, name=pbFile, as_text=False) print("Succeeded building model in TensorFlow2!") # 将 .pb 文件转换为 .onnx 文件 ---------------------------------------------------- if bSinglePbFile: os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs-as-nchw 'Input:0' --opset 13 --inputs 'Input:0' --outputs 'Identity:0'" % (pbFilePath + pbFile, onnxFile)) else: os.system("python3 -m tf2onnx.convert --saved-model %s --output %s --inputs-as-nchw 'Input:0' --opset 13" % (pbFilePath, onnxFile)) print("Succeeded converting model into ONNX!") # TensorRT 中加载 .onnx 创建 engine --------------------------------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) networkFlag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION)) network = builder.create_network(networkFlag) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, 28, 28] profile.set_shape(inputTensor.name, [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28]) config.add_optimization_profile(profile) # 为所有输入张量添加 quantize 节点,这里使用经验值 127 <-> 1.0 # 理想状态下需要在 QAT 过程中获取这些取值并添加到输入节点上 if isAddQDQForInput: quantizeScale = np.array([1.0 / 127.0], dtype=np.float32) dequantizeScale = np.array([127.0 / 1.0], dtype=np.float32) one = np.array([1], dtype=np.float32) zero = np.array([0], dtype=np.float32) for i in range(network.num_inputs): inputTensor = network.get_input(i) for j in range(network.num_layers): layer = network.get_layer(j) for k in range(layer.num_inputs): if (layer.get_input(k) == inputTensor): print(i, layer, k) #quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, quantizeScale) quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, one) quantizeLayer.set_output_type(0, trt.int8) quantizeLayer.name = "InputQuantizeNode" quantizeLayer.get_output(0).name = "QuantizedInputTensor" #dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, dequantizeScale) dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, one) dequantizeLayer.set_output_type(0, trt.float32) dequantizeLayer.name = "InputDequantizeNode" dequantizeLayer.get_output(0).name = "DequantizedInputTensor" layer.set_input(k, dequantizeLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_binding_shape(0, [1, 1, 28, 28]) _, stream = cudart.cudaStreamCreate() print("Binding0->", engine.get_binding_shape(0), context.get_binding_shape(0), engine.get_binding_dtype(0)) print("Binding1->", engine.get_binding_shape(1), context.get_binding_shape(1), engine.get_binding_dtype(1)) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32) inputH0 = np.ascontiguousarray(data.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) print("inputH0 :", data.shape) #print(data) print("outputH0:", outputH0.shape) print(outputH0) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT-QAT-TODO/mainV3.py
""" from cuda import cudart #from datetime import datetime as dt import numpy as np import onnx import onnx_graphsurgeon as gs import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import config_pb2, meta_graph_pb2, rewriter_config_pb2 from tensorflow.python.framework import importer, ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver import tensorrt as trt import cv2 tf2.compat.v1.disable_eager_execution() np.random.seed(31193) tf2.compat.v1.set_random_seed(97) nTrainbatchSize = 256 ckptFile = "./model.ckpt" pbFile = "model-V1.pb" pb2File = "model-V2.pb" onnxFile = "model-V1.onnx" onnx2File = "model-V2.onnx" trtFile = "model.plan" #inferenceImage = dataPath + "8.png" outputNodeName = "z" isRemoveTransposeNode = False # 变量说明见用到该变量的地方 isAddQDQForInput = False # 变量说明见用到该变量的地方 """ import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np #=============================================================================== from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model/" pbFile = "model.pb" onnxFile = "./model.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # 是否保存为单独的一个 .pb文件(两种导出方式),这里选 True 或 Flase 都能导出为 .onnx bSinglePbFile = True # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" #=============================================================================== isAddQDQForInput = False checkpointPath = "./checkpoint/model" checkpointSuffix = "-1" #=============================================================================== os.system("rm -rf %s ./checkpoint/ ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData # TensorFlow 中创建网络并保存为 .pb 文件 ------------------------------------------- model = tf2.keras.Sequential([tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32), tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1"), tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1"), tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2"), tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2"), tf2.keras.layers.Reshape([-1], name="reshape"), tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1"), tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2"), tf2.keras.layers.Softmax(axis=1, name="softmax")]) model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) #history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) checkpoint = tf2.train.Checkpoint(model) checkpoint.save(checkpointPath) print("Succeeded saving .ckpt in TensorFlow!") import tensorflow_model_optimization as tfmot LastValueQuantizer = tfmot.quantization.keras.quantizers.LastValueQuantizer MovingAverageQuantizer = tfmot.quantization.keras.quantizers.MovingAverageQuantizer class DefaultDenseQuantizeConfig(tfmot.quantization.keras.QuantizeConfig): # Configure how to quantize weights. def get_weights_and_quantizers(self, layer): return [(layer.kernel, LastValueQuantizer(num_bits=8, symmetric=True, narrow_range=False, per_axis=False))] # Configure how to quantize activations. def get_activations_and_quantizers(self, layer): return [(layer.activation, MovingAverageQuantizer(num_bits=8, symmetric=True, narrow_range=False, per_axis=False))] def set_quantize_weights(self, layer, quantize_weights): # Add this line for each item returned in `get_weights_and_quantizers` # , in the same order layer.kernel = quantize_weights[0] def set_quantize_activations(self, layer, quantize_activations): # Add this line for each item returned in `get_activations_and_quantizers` # , in the same order. layer.activation = quantize_activations[0] # Configure how to quantize outputs (may be equivalent to activations). def get_output_quantizers(self, layer): return [] def get_config(self): return {} quantize_annotate_layer = tfmot.quantization.keras.quantize_annotate_layer quantize_annotate_model = tfmot.quantization.keras.quantize_annotate_model quantize_scope = tfmot.quantization.keras.quantize_scope #modelQAT = quantize_annotate_model(tf2.keras.Sequential([quantize_annotate_layer(CustomLayer(20, input_shape=(20, )), DefaultDenseQuantizeConfig()), tf.keras.layers.Flatten()])) model2 = tf2.keras.Sequential([ tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32), quantize_annotate_layer(tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1"), DefaultDenseQuantizeConfig()), tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1"), quantize_annotate_layer(tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2"), DefaultDenseQuantizeConfig()), tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2"), tf2.keras.layers.Reshape([-1], name="reshape"), quantize_annotate_layer(tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1"), DefaultDenseQuantizeConfig()), quantize_annotate_layer(tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2"), DefaultDenseQuantizeConfig()), tf2.keras.layers.Softmax(axis=1, name="softmax"), ]) checkpoint = tf2.train.Checkpoint(model) checkpoint.restore(checkpointPath + checkpointSuffix) modelQAT = quantize_annotate_model(model2) with quantize_scope({"DefaultDenseQuantizeConfig": DefaultDenseQuantizeConfig}): # Use `quantize_apply` to actually make the model quantization aware. modelQAT = tfmot.quantization.keras.quantize_apply(modelQAT) modelQAT.summary() # `quantize_model` requires a recompile. modelQAT.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) modelQAT.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) print("Baseline test accuracy: %.4f" % model.evaluate(xTest, yTest, verbose=0)[1]) print("Quantize test accuracy: %.4f" % modelQAT.evaluate(xTest, yTest, verbose=0)[1]) tf2.saved_model.save(modelQAT, pbFilePath) if bSinglePbFile: modelFunction = tf2.function(lambda Input: modelQAT(Input)).get_concrete_function(tf2.TensorSpec(modelQAT.inputs[0].shape, modelQAT.inputs[0].dtype)) frozen_func = convert_variables_to_constants_v2(modelFunction) frozen_func.graph.as_graph_def() print("_________________________________________________________________") print("Frozen model inputs:\n", frozen_func.inputs) print("Frozen model outputs:\n", frozen_func.outputs) print("Frozen model layers:") for op in frozen_func.graph.get_operations(): print(op.name) tf2.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=pbFilePath, name=pbFile, as_text=False) print("Succeeded building model in TensorFlow2!") # 将 .pb 文件转换为 .onnx 文件 ---------------------------------------------------- if bSinglePbFile: os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs-as-nchw 'Input:0' --opset 13 --inputs 'Input:0' --outputs 'Identity:0'" % (pbFilePath + pbFile, onnxFile)) else: os.system("python3 -m tf2onnx.convert --saved-model %s --output %s --inputs-as-nchw 'Input:0' --opset 13" % (pbFilePath, onnxFile)) print("Succeeded converting model into ONNX!") # TensorRT 中加载 .onnx 创建 engine --------------------------------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) networkFlag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION)) network = builder.create_network(networkFlag) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, 28, 28] profile.set_shape(inputTensor.name, [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28]) config.add_optimization_profile(profile) # 为所有输入张量添加 quantize 节点,这里使用经验值 127 <-> 1.0 # 理想状态下需要在 QAT 过程中获取这些取值并添加到输入节点上 if isAddQDQForInput: quantizeScale = np.array([1.0 / 127.0], dtype=np.float32) dequantizeScale = np.array([127.0 / 1.0], dtype=np.float32) one = np.array([1], dtype=np.float32) zero = np.array([0], dtype=np.float32) for i in range(network.num_inputs): inputTensor = network.get_input(i) for j in range(network.num_layers): layer = network.get_layer(j) for k in range(layer.num_inputs): if (layer.get_input(k) == inputTensor): print(i, layer, k) #quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, quantizeScale) quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, one) quantizeLayer.set_output_type(0, trt.int8) quantizeLayer.name = "InputQuantizeNode" quantizeLayer.get_output(0).name = "QuantizedInputTensor" #dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, dequantizeScale) dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, one) dequantizeLayer.set_output_type(0, trt.float32) dequantizeLayer.name = "InputDequantizeNode" dequantizeLayer.get_output(0).name = "DequantizedInputTensor" layer.set_input(k, dequantizeLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_binding_shape(0, [1, 1, 28, 28]) _, stream = cudart.cudaStreamCreate() print("Binding0->", engine.get_binding_shape(0), context.get_binding_shape(0), engine.get_binding_dtype(0)) print("Binding1->", engine.get_binding_shape(1), context.get_binding_shape(1), engine.get_binding_dtype(1)) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32) inputH0 = np.ascontiguousarray(data.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) print("inputH0 :", data.shape) #print(data) print("outputH0:", outputH0.shape) print(outputH0) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT-QAT-TODO/mainV2.py
""" from cuda import cudart #from datetime import datetime as dt import numpy as np import onnx import onnx_graphsurgeon as gs import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import config_pb2, meta_graph_pb2, rewriter_config_pb2 from tensorflow.python.framework import importer, ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver import tensorrt as trt import cv2 tf2.compat.v1.disable_eager_execution() np.random.seed(31193) tf2.compat.v1.set_random_seed(97) nTrainbatchSize = 256 ckptFile = "./model.ckpt" pbFile = "model-V1.pb" pb2File = "model-V2.pb" onnxFile = "model-V1.onnx" onnx2File = "model-V2.onnx" trtFile = "model.plan" #inferenceImage = dataPath + "8.png" outputNodeName = "z" isRemoveTransposeNode = False # 变量说明见用到该变量的地方 isAddQDQForInput = False # 变量说明见用到该变量的地方 """ import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np #=============================================================================== from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model/" pbFile = "model.pb" onnxFile = "./model.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # 是否保存为单独的一个 .pb文件(两种导出方式),这里选 True 或 Flase 都能导出为 .onnx bSinglePbFile = True # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" #=============================================================================== isAddQDQForInput = False #=============================================================================== #os.system("rm -rf %s ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData # TensorFlow 中创建网络并保存为 .pb 文件 ------------------------------------------- modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) #history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) history = model.fit(xTrain, yTrain, batch_size=128, epochs=1, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) #checkpoint = tf2.train.Checkpoint(model) #checkpoint.save(checkpointPath) #print("Succeeded saving .ckpt in TensorFlow!") import tensorflow_model_optimization as tfmot modelQAT = tfmot.quantization.keras.quantize_model(model) modelQAT.summary() # `quantize_model` requires a recompile. modelQAT.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) modelQAT.fit(xTrain, yTrain, batch_size=nTrainBatchSize, epochs=1, validation_split=0.1) print("Baseline test accuracy: %.4f" % model.evaluate(xTest, yTest, verbose=0)[1]) print("Quantize test accuracy: %.4f" % modelQAT.evaluate(xTest, yTest, verbose=0)[1]) tf2.saved_model.save(model, pbFilePath) if bSinglePbFile: modelFunction = tf2.function(lambda Input: modelQAT(Input)).get_concrete_function(tf2.TensorSpec(modelQAT.inputs[0].shape, modelQAT.inputs[0].dtype)) frozen_func = convert_variables_to_constants_v2(modelFunction) frozen_func.graph.as_graph_def() print("_________________________________________________________________") print("Frozen model inputs:\n", frozen_func.inputs) print("Frozen model outputs:\n", frozen_func.outputs) print("Frozen model layers:") for op in frozen_func.graph.get_operations(): print(op.name) tf2.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=pbFilePath, name=pbFile, as_text=False) print("Succeeded building model in TensorFlow2!") # 将 .pb 文件转换为 .onnx 文件 ---------------------------------------------------- if bSinglePbFile: os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs-as-nchw 'Input:0' --opset 13 --inputs 'Input:0' --outputs 'Identity:0'" % (pbFilePath + pbFile, onnxFile)) else: os.system("python3 -m tf2onnx.convert --saved-model %s --output %s --inputs-as-nchw 'Input:0' --opset 13" % (pbFilePath, onnxFile)) print("Succeeded converting model into ONNX!") # TensorRT 中加载 .onnx 创建 engine --------------------------------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) networkFlag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION)) network = builder.create_network(networkFlag) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, 28, 28] profile.set_shape(inputTensor.name, [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28]) config.add_optimization_profile(profile) # 为所有输入张量添加 quantize 节点,这里使用经验值 127 <-> 1.0 # 理想状态下需要在 QAT 过程中获取这些取值并添加到输入节点上 if isAddQDQForInput: quantizeScale = np.array([1.0 / 127.0], dtype=np.float32) dequantizeScale = np.array([127.0 / 1.0], dtype=np.float32) one = np.array([1], dtype=np.float32) zero = np.array([0], dtype=np.float32) for i in range(network.num_inputs): inputTensor = network.get_input(i) for j in range(network.num_layers): layer = network.get_layer(j) for k in range(layer.num_inputs): if (layer.get_input(k) == inputTensor): print(i, layer, k) #quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, quantizeScale) quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, one) quantizeLayer.set_output_type(0, trt.int8) quantizeLayer.name = "InputQuantizeNode" quantizeLayer.get_output(0).name = "QuantizedInputTensor" #dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, dequantizeScale) dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, one) dequantizeLayer.set_output_type(0, trt.float32) dequantizeLayer.name = "InputDequantizeNode" dequantizeLayer.get_output(0).name = "DequantizedInputTensor" layer.set_input(k, dequantizeLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_binding_shape(0, [1, 1, 28, 28]) _, stream = cudart.cudaStreamCreate() print("Binding0->", engine.get_binding_shape(0), context.get_binding_shape(0), engine.get_binding_dtype(0)) print("Binding1->", engine.get_binding_shape(1), context.get_binding_shape(1), engine.get_binding_dtype(1)) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32) inputH0 = np.ascontiguousarray(data.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) print("inputH0 :", data.shape) #print(data) print("outputH0:", outputH0.shape) print(outputH0) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT-QAT-TODO/mainV1.py
import os import sys #from datetime import datetime as dt import numpy as np import onnx import onnx_graphsurgeon as gs from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import cv2 import tensorflow as tf2 import tensorrt as trt from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import (config_pb2, meta_graph_pb2, rewriter_config_pb2) from tensorflow.python.framework import importer, ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver #dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" #sys.path.append(dataPath) #import loadMnistData tf2.compat.v1.disable_eager_execution() np.random.seed(31193) tf2.compat.v1.set_random_seed(97) nTrainbatchSize = 256 ckptFile = "./model.ckpt" pbFile = "./model-V1.pb" pb2File = "./model-V2.pb" onnxFile = "./model-V1.onnx" onnx2File = "./model-V2.onnx" trtFile = "./model.plan" #inferenceImage = dataPath + "8.png" outputNodeName = "z" isRemoveTransposeNode = False # 变量说明见用到该变量的地方 isAddQDQForInput = False # 变量说明见用到该变量的地方 import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np #=============================================================================== from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model-NCHW/" pbFile = "model-NCHW.pb" onnxFile = "./model-NCHW.onnx" trtFile = "./model-NCHW.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" #=============================================================================== checkpointPath = "./checkpoint/model" checkpointSuffix = "-1" #=============================================================================== #os.system("rm -rf %s ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData # TensorFlow 中创建网络并保存为 .pb 文件 ------------------------------------------- modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) #history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) history = model.fit(xTrain, yTrain, batch_size=128, epochs=1, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) #checkpoint = tf2.train.Checkpoint(model) #checkpoint.save(checkpointPath) #print("Succeeded saving .ckpt in TensorFlow!") import tensorflow_model_optimization as tfmot quantize_model = tfmot.quantization.keras.quantize_model # q_aware stands for for quantization aware. q_aware_model = quantize_model(model) q_aware_model.summary() # `quantize_model` requires a recompile. q_aware_model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) train_images_subset = xTrain[:1000] # out of 3000 train_labels_subset = yTrain[:1000] q_aware_model.fit(train_images_subset, train_labels_subset, batch_size=100, epochs=1, validation_split=0.1) _, baseline_model_accuracy = model.evaluate(xTest, yTest, verbose=0) _, q_aware_model_accuracy = q_aware_model.evaluate(xTest, yTest, verbose=0) print("Baseline test accuracy:", baseline_model_accuracy) print("Quant test accuracy:", q_aware_model_accuracy) #---------------- """ # TensorFlow 中创建推理网络并保存为 .pb ----------------------------------------- modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) w = tf2.math.argmax(z) model = tf2.keras.Model(inputs=modelInput, outputs=w, name="MNISTExample2") checkpoint = tf2.train.Checkpoint(model) checkpoint.restore(checkpointPath + checkpointSuffix) tf2.quantize.experimental_create_eval_graph(symmetric=True, use_qdq=True) print("Finish!") exit() tf2.contrib.quantize.experimental_create_eval_graph(symmetric=True, use_qdq=True) with tf2.Session(graph=g2) as sess: tf2.compat.v1.train.Saver().restore(sess, ckptFile) constantGraph = tf2.graph_util.convert_variables_to_constants(sess, g2.as_graph_def(), [outputNodeName]) with tf2.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) print("Succeeded saving .pb in TensorFlow!") # 优化 .pb --------------------------------------------------------------------- with open(pbFile, "rb") as f: graphdef = graph_pb2.GraphDef() graphdef.ParseFromString(f.read()) graph = ops.Graph() with graph.as_default(): outputCollection = meta_graph_pb2.CollectionDef() for output in outputNodeName.split(","): outputCollection.node_list.value.append(output) importer.import_graph_def(graphdef, name="") metagraph = saver.export_meta_graph(graph_def=graph.as_graph_def(add_shapes=True), graph=graph) metagraph.collection_def["train_op"].CopyFrom(outputCollection) rewriter_config = rewriter_config_pb2.RewriterConfig() rewriter_config.optimizers.extend(["constfold"]) rewriter_config.meta_optimizer_iterations = (rewriter_config_pb2.RewriterConfig.ONE) session_config = config_pb2.ConfigProto() session_config.graph_options.rewrite_options.CopyFrom(rewriter_config) folded_graph = tf_optimizer.OptimizeGraph(session_config, metagraph) with open(pb2File, "wb") as f: f.write(folded_graph.SerializeToString()) print("Succeeded optimizing .pb in TensorFlow!") # 将 .pb 文件转换为 .onnx 文件 -------------------------------------------------- os.system("python3 -m tf2onnx.convert --opset 11 --input %s --output %s --inputs 'input_0:0' --outputs '%s:0' --inputs-as-nchw 'x:0'" % (pb2File, onnxFile, outputNodeName)) print("Succeeded converting model into ONNX!") # 优化 .onnx 文件,去除 Conv 前的 Transpose 节点 -------------------------------- graph = gs.import_onnx(onnx.load(onnxFile)) # 原 repo 中解释,导出的计算图中 Conv 的 Weight 输入前会有一个 Transpose 节点,并且 TensorRT QAT 模式不支持这个节点,这里用于手工转置并去除该 Transpose 节点 # 但是在目前导出的计算图中已经没有了这个节点,不再需要这一步 if isRemoveTransposeNode: for node in [n for n in graph.nodes if n.op == "Conv"]: convKernelTensor = node.i(1).i().i().inputs[0] convKernelTensor.values = convKernelTensor.values.transpose(3, 2, 0, 1) node.inputs[1] = node.i(1).i(0).outputs[0] onnx.save_model(gs.export_onnx(graph.cleanup().toposort()), onnx2File) print("Succeeded optimizing .onnx in Onnx!") # TensorRT 中加载 .onnx 创建 engine --------------------------------------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) networkFlag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION)) network = builder.create_network(networkFlag) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, 28, 28] profile.set_shape(inputTensor.name, [1, 1, 28, 28], [4, 1, 28, 28], [16, 1, 28, 28]) config.add_optimization_profile(profile) # 为所有输入张量添加 quantize 节点,这里使用经验值 127 <-> 1.0 # 理想状态下需要在 QAT 过程中获取这些取值并添加到输入节点上 if isAddQDQForInput: quantizeScale = np.array([1.0 / 127.0], dtype=np.float32) dequantizeScale = np.array([127.0 / 1.0], dtype=np.float32) one = np.array([1], dtype=np.float32) zero = np.array([0], dtype=np.float32) for i in range(network.num_inputs): inputTensor = network.get_input(i) for j in range(network.num_layers): layer = network.get_layer(j) for k in range(layer.num_inputs): if (layer.get_input(k) == inputTensor): print(i, layer, k) #quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, quantizeScale) quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, one) quantizeLayer.set_output_type(0, trt.int8) quantizeLayer.name = "InputQuantizeNode" quantizeLayer.get_output(0).name = "QuantizedInputTensor" #dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, dequantizeScale) dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, one) dequantizeLayer.set_output_type(0, trt.float32) dequantizeLayer.name = "InputDequantizeNode" dequantizeLayer.get_output(0).name = "DequantizedInputTensor" layer.set_input(k, dequantizeLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) context = engine.create_execution_context() context.set_binding_shape(0, [1, 1, 28, 28]) _, stream = cudart.cudaStreamCreate() print("Binding0->", engine.get_binding_shape(0), context.get_binding_shape(0), engine.get_binding_dtype(0)) print("Binding1->", engine.get_binding_shape(1), context.get_binding_shape(1), engine.get_binding_dtype(1)) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32) inputH0 = np.ascontiguousarray(data.reshape(-1)) outputH0 = np.empty(context.get_binding_shape(1), dtype=trt.nptype(engine.get_binding_dtype(1))) _, inputD0 = cudart.cudaMallocAsync(inputH0.nbytes, stream) _, outputD0 = cudart.cudaMallocAsync(outputH0.nbytes, stream) cudart.cudaMemcpyAsync(inputD0, inputH0.ctypes.data, inputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice, stream) context.execute_async_v2([int(inputD0), int(outputD0)], stream) cudart.cudaMemcpyAsync(outputH0.ctypes.data, outputD0, outputH0.nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost, stream) cudart.cudaStreamSynchronize(stream) print("inputH0 :", data.shape) #print(data) print("outputH0:", outputH0.shape) print(outputH0) cudart.cudaStreamDestroy(stream) cudart.cudaFree(inputD0) cudart.cudaFree(outputD0) print("Succeeded running model in TensorRT!") """
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT-QAT-TODO/tf2-usageOfCheckpoint.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/pyTorch-ONNX-TensorRT/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import calibrator import cv2 import numpy as np import tensorrt as trt import torch as t import torch.nn.functional as F from cuda import cudart from torch.autograd import Variable np.random.seed(31193) t.manual_seed(97) t.cuda.manual_seed_all(97) t.backends.cudnn.deterministic = True nTrainBatchSize = 128 nHeight = 28 nWidth = 28 onnxFile = "./model.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.onnx ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() # Create network and train model in pyTorch ------------------------------------ class Net(t.nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = t.nn.Conv2d(1, 32, (5, 5), padding=(2, 2), bias=True) self.conv2 = t.nn.Conv2d(32, 64, (5, 5), padding=(2, 2), bias=True) self.fc1 = t.nn.Linear(64 * 7 * 7, 1024, bias=True) self.fc2 = t.nn.Linear(1024, 10, bias=True) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) x = x.reshape(-1, 64 * 7 * 7) x = F.relu(self.fc1(x)) y = self.fc2(x) z = F.softmax(y, dim=1) z = t.argmax(z, dim=1) return y, z class MyData(t.utils.data.Dataset): def __init__(self, isTrain=True): if isTrain: self.data = trainFileList else: self.data = testFileList def __getitem__(self, index): imageName = self.data[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) index = int(imageName[-7]) label[index] = 1 return t.from_numpy(data.reshape(1, nHeight, nWidth).astype(np.float32)), t.from_numpy(label) def __len__(self): return len(self.data) model = Net().cuda() ceLoss = t.nn.CrossEntropyLoss() opt = t.optim.Adam(model.parameters(), lr=0.001) trainDataset = MyData(True) testDataset = MyData(False) trainLoader = t.utils.data.DataLoader(dataset=trainDataset, batch_size=nTrainBatchSize, shuffle=True) testLoader = t.utils.data.DataLoader(dataset=testDataset, batch_size=nTrainBatchSize, shuffle=True) for epoch in range(10): for xTrain, yTrain in trainLoader: xTrain = Variable(xTrain).cuda() yTrain = Variable(yTrain).cuda() opt.zero_grad() y_, z = model(xTrain) loss = ceLoss(y_, yTrain) loss.backward() opt.step() with t.no_grad(): acc = 0 n = 0 for xTest, yTest in testLoader: xTest = Variable(xTest).cuda() yTest = Variable(yTest).cuda() y_, z = model(xTest) acc += t.sum(z == t.matmul(yTest, t.Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).to("cuda:0"))).cpu().numpy() n += xTest.shape[0] print("%s, epoch %2d, loss = %f, test acc = %f" % (dt.now(), epoch + 1, loss.data, acc / n)) print("Succeeded building model in pyTorch!") # Export model as ONNX file ---------------------------------------------------- t.onnx.export(model, t.randn(1, 1, nHeight, nWidth, device="cuda"), onnxFile, input_names=["x"], output_names=["y", "z"], do_constant_folding=True, verbose=True, keep_initializers_as_inputs=True, opset_version=12, dynamic_axes={"x": {0: "nBatchSize"}, "z": {0: "nBatchSize"}}) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) network.unmark_output(network.get_output(0)) # remove output tensor "y" engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/pyTorch-ONNX-TensorRT/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # from glob import glob import cv2 import numpy as np nCalibrationData = 100 nHeight = 28 nWidth = 28 dataPath = "../../../00-MNISTData/" calibrationDataPath = dataPath + "test/" inferenceDataFile = dataPath + "8.png" inferenceData = cv2.imread(inferenceDataFile, cv2.IMREAD_GRAYSCALE).astype(np.float32) calibrationDataFileList = sorted(glob(calibrationDataPath + "*.jpg"))[:nCalibrationData] calibrationData = np.empty([nCalibrationData, 1, nHeight, nWidth]) for i in range(nCalibrationData): calibrationData[i, 0] = cv2.imread(calibrationDataFileList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) dataDictionary = {} dataDictionary["inferenceData"] = inferenceData dataDictionary["calibrationData"] = calibrationData np.savez("data.npz", **dataDictionary) print("Succeeded creating data for calibration and inference!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/pyTorch-ONNX-TensorRT/C++/createCalibrationAndInferenceData.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf1 import tensorrt as trt import uff np.random.seed(31193) tf1.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFile = "./model.pb" uffFile = "./model.uff" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" os.system("rm -rf ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf1.compat.v1.disable_eager_execution() cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow1 -------------------------------- def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData x = tf1.compat.v1.placeholder(tf1.float32, [None, nHeight, nWidth, 1], name="x") y_ = tf1.compat.v1.placeholder(tf1.float32, [None, 10], name="y_") w1 = tf1.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf1.compat.v1.get_variable("b1", shape=[32], initializer=tf1.constant_initializer(value=0.1)) h1 = tf1.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf1.nn.relu(h2) h4 = tf1.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf1.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf1.compat.v1.get_variable("b2", shape=[64], initializer=tf1.constant_initializer(value=0.1)) h5 = tf1.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf1.nn.relu(h6) h8 = tf1.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf1.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf1.compat.v1.get_variable("b3", shape=[1024], initializer=tf1.constant_initializer(value=0.1)) h9 = tf1.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf1.matmul(h9, w3) h11 = h10 + b3 h12 = tf1.nn.relu(h11) w4 = tf1.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf1.compat.v1.get_variable("b4", shape=[10], initializer=tf1.constant_initializer(value=0.1)) h13 = tf1.matmul(h12, w4) h14 = h13 + b4 y = tf1.nn.softmax(h14, name="y") z = tf1.argmax(y, 1, name="z") crossEntropy = -tf1.reduce_sum(y_ * tf1.math.log(y)) trainStep = tf1.compat.v1.train.AdamOptimizer(1e-4).minimize(crossEntropy) accuracy = tf1.reduce_mean(tf1.cast(tf1.equal(z, tf1.argmax(y_, 1)), tf1.float32), name="accuracy") tfConfig = tf1.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf1.compat.v1.Session(config=tfConfig) sess.run(tf1.compat.v1.global_variables_initializer()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) trainStep.run(session=sess, feed_dict={x: xSample, y_: ySample}) if i % 10 == 0: accuracyValue = accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, batch %3d, acc = %f" % (dt.now(), 10 + i, accuracyValue)) constantGraph = tf1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["z"]) with tf1.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) sess.close() print("Succeeded building model in TensorFlow1!") # Export model as UFF file ---------------------------------------------------- uff.from_tensorflow_frozen_model( pbFile, output_nodes=["y"], output_filename=uffFile, preprocessor=None, write_preprocessed=False, text=False, quiet=False, debug_mode=False, #input_node=["x"], #list_nodes=False, return_graph_info=False ) print("Succeeded converting model into .uff!") # Parse UFF file, rebuild network and do inference in TensorRT ---------------- logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network() # use Implicit Batch mode profile = builder.create_optimization_profile() config = builder.create_builder_config() parser = trt.UffParser() parser.register_input("x", [28, 28, 1], trt.UffInputOrder.NHWC) parser.register_output("y") parser.parse(uffFile, network) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] for i in range(nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) # we only use nBatchSize = 1 data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, nHeight, nWidth, 1) bufferH[0] = data for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-UFF-TensorRT/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os import sys from datetime import datetime as dt from glob import glob import cv2 import numpy as np import onnx import onnx_graphsurgeon as gs from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf import tensorrt as trt from tensorflow.core.framework import graph_pb2 from tensorflow.core.protobuf import (config_pb2, meta_graph_pb2, rewriter_config_pb2) from tensorflow.python.framework import importer, ops from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training import saver dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" sys.path.append(dataPath) import loadMnistData tf.compat.v1.disable_eager_execution() np.random.seed(31193) tf.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 ckptFile = "./model/model.ckpt" pbFile = "model-V1.pb" pb2File = "model-V2.pb" onnxFile = "model-V1.onnx" onnx2File = "model-V2.onnx" trtFile = "model.plan" inferenceImage = dataPath + "8.png" outputNodeName = "z" isRemoveTransposeNode = False isAddQDQForInput = False os.system("rm -rf ./model*.* checkpoint") # Create network and train model in TensorFlow1 -------------------------------- g1 = tf.Graph() with g1.as_default(): x = tf.compat.v1.placeholder(tf.float32, [None, 1, 28, 28], name="input_0") y_ = tf.compat.v1.placeholder(tf.float32, [None, 10], name="output_0") h0 = tf.transpose(x, [0, 2, 3, 1]) w1 = tf.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf.compat.v1.get_variable("b1", shape=[32], initializer=tf.constant_initializer(value=0.1)) h1 = tf.nn.conv2d(h0, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf.nn.relu(h2) h4 = tf.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf.compat.v1.get_variable("b2", shape=[64], initializer=tf.constant_initializer(value=0.1)) h5 = tf.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf.nn.relu(h6) h8 = tf.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf.compat.v1.get_variable("b3", shape=[1024], initializer=tf.constant_initializer(value=0.1)) h9 = tf.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf.matmul(h9, w3) h11 = h10 + b3 h12 = tf.nn.relu(h11) w4 = tf.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf.compat.v1.get_variable("b4", shape=[10], initializer=tf.constant_initializer(value=0.1)) h13 = tf.matmul(h12, w4) h14 = h13 + b4 loss = tf.compat.v1.losses.softmax_cross_entropy(onehot_labels=y_, logits=h14) acc = tf.compat.v1.metrics.accuracy(labels=tf.argmax(y_, axis=1), predictions=tf.argmax(h14, axis=1))[1] tf.contrib.quantize.experimental_create_training_graph(tf.compat.v1.get_default_graph(), symmetric=True, use_qdq=True, quant_delay=800) trainStep = tf.compat.v1.train.AdamOptimizer(0.001).minimize(loss) mnist = loadMnistData.MnistData(dataPath, isOneHot=True) with tf.Session(graph=g1) as sess: sess.run(tf.group(tf.compat.v1.global_variables_initializer(), tf.compat.v1.local_variables_initializer())) for i in range(1000): xSample, ySample = mnist.getBatch(nTrainBatchSize, True) trainStep.run(session=sess, feed_dict={x: xSample.reshape(-1, 1, 28, 28), y_: ySample}) if (i % 100 == 0): xSample, ySample = mnist.getBatch(100, False) test_accuracy = sess.run(acc, {x: xSample.reshape(-1, 1, 28, 28), y_: ySample}) print("%s, Step=%d, test acc=%.3f" % (dt.now(), i, acc.eval(session=sess, feed_dict={x: xSample.reshape(-1, 1, 28, 28), y_: ySample}))) tf.compat.v1.train.Saver().save(sess, ckptFile) xSample, ySample = mnist.getBatch(100, False) print("%s, test acc = %.3f" % (dt.now(), acc.eval(session=sess, feed_dict={x: xSample.reshape(-1, 1, 28, 28), y_: ySample}))) print("Succeeded saving .ckpt in TensorFlow!") # Save network as .pb ---------------------------------------------------------- g2 = tf.Graph() with g2.as_default(): x = tf.compat.v1.placeholder(tf.float32, [None, 1, 28, 28], name="input_0") h0 = tf.transpose(x, [0, 2, 3, 1]) w1 = tf.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf.compat.v1.get_variable("b1", shape=[32], initializer=tf.constant_initializer(value=0.1)) h1 = tf.nn.conv2d(h0, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf.nn.relu(h2) h4 = tf.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf.compat.v1.get_variable("b2", shape=[64], initializer=tf.constant_initializer(value=0.1)) h5 = tf.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf.nn.relu(h6) h8 = tf.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf.compat.v1.get_variable("b3", shape=[1024], initializer=tf.constant_initializer(value=0.1)) h9 = tf.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf.matmul(h9, w3) h11 = h10 + b3 h12 = tf.nn.relu(h11) w4 = tf.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf.compat.v1.get_variable("b4", shape=[10], initializer=tf.constant_initializer(value=0.1)) h13 = tf.matmul(h12, w4) h14 = h13 + b4 h15 = tf.nn.softmax(h14, name="softmax", axis=1) h16 = tf.argmax(h15, 1, name=outputNodeName) tf.contrib.quantize.experimental_create_eval_graph(symmetric=True, use_qdq=True) with tf.Session(graph=g2) as sess: tf.compat.v1.train.Saver().restore(sess, ckptFile) constantGraph = tf.graph_util.convert_variables_to_constants(sess, g2.as_graph_def(), [outputNodeName]) with tf.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) print("Succeeded saving .pb in TensorFlow!") # Optimize .pb ----------------------------------------------------------------- with open(pbFile, "rb") as f: graphdef = graph_pb2.GraphDef() graphdef.ParseFromString(f.read()) graph = ops.Graph() with graph.as_default(): outputCollection = meta_graph_pb2.CollectionDef() for output in outputNodeName.split(","): outputCollection.node_list.value.append(output) importer.import_graph_def(graphdef, name="") metagraph = saver.export_meta_graph(graph_def=graph.as_graph_def(add_shapes=True), graph=graph) metagraph.collection_def["train_op"].CopyFrom(outputCollection) rewriter_config = rewriter_config_pb2.RewriterConfig() rewriter_config.optimizers.extend(["constfold"]) rewriter_config.meta_optimizer_iterations = (rewriter_config_pb2.RewriterConfig.ONE) session_config = config_pb2.ConfigProto() session_config.graph_options.rewrite_options.CopyFrom(rewriter_config) folded_graph = tf_optimizer.OptimizeGraph(session_config, metagraph) with open(pb2File, "wb") as f: f.write(folded_graph.SerializeToString()) print("Succeeded optimizing .pb in TensorFlow!") # Export model as ONNX file ---------------------------------------------------- os.system("python3 -m tf2onnx.convert --opset 11 --input %s --output %s --inputs 'input_0:0' --outputs '%s:0' --inputs-as-nchw 'x:0'" % (pb2File, onnxFile, outputNodeName)) print("Succeeded converting model into ONNX!") # Optimize ONNX file to remove Transpose node before Conv node ----------------- graph = gs.import_onnx(onnx.load(onnxFile)) # In the original repo there is a Transpose node before the weight input of the Conv node, which is not supported by the TensorRT QAT mode, so we need to transpose the weight manually and remove the Transpose node. # However, this Transpose node does not appear in the current exported ONNX file, so this step is no longer needed. if isRemoveTransposeNode: for node in [n for n in graph.nodes if n.op == "Conv"]: convKernelTensor = node.i(1).i().i().inputs[0] convKernelTensor.values = convKernelTensor.values.transpose(3, 2, 0, 1) node.inputs[1] = node.i(1).i(0).outputs[0] onnx.save_model(gs.export_onnx(graph.cleanup().toposort()), onnx2File) print("Succeeded optimizing .onnx in Onnx!") # Parse ONNX file, rebuild network and do inference in TensorRT ---------------- logger = trt.Logger(trt.Logger.ERROR) builder = trt.Builder(logger) networkFlag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) | (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_PRECISION)) network = builder.create_network(networkFlag) profile = builder.create_optimization_profile() config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, nHeight, nWidth] profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) # Add the Quantize/Dequantize node for all input tensors, here we use empirical value 127<->1.0. # Ideally, these values need to be obtained in the QAT process. if isAddQDQForInput: quantizeScale = np.array([1.0 / 127.0], dtype=np.float32) dequantizeScale = np.array([127.0 / 1.0], dtype=np.float32) one = np.array([1], dtype=np.float32) zero = np.array([0], dtype=np.float32) for i in range(network.num_inputs): inputTensor = network.get_input(i) for j in range(network.num_layers): layer = network.get_layer(j) for k in range(layer.num_inputs): if (layer.get_input(k) == inputTensor): print(i, layer, k) #quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, quantizeScale) quantizeLayer = network.add_scale(inputTensor, trt.ScaleMode.UNIFORM, zero, one) quantizeLayer.set_output_type(0, trt.int8) quantizeLayer.name = "InputQuantizeNode" quantizeLayer.get_output(0).name = "QuantizedInputTensor" #dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, dequantizeScale) dequantizeLayer = network.add_scale(quantizeLayer.get_output(0), trt.ScaleMode.UNIFORM, zero, one) dequantizeLayer.set_output_type(0, trt.float32) dequantizeLayer.name = "InputDequantizeNode" dequantizeLayer.get_output(0).name = "DequantizedInputTensor" layer.set_input(k, dequantizeLayer.get_output(0)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] for i in range(nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH[0] = data for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-ONNX-TensorRT-QAT/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/Paddlepaddle-ONNX-TensorRT/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import calibrator import cv2 import numpy as np import paddle import paddle.nn.functional as F import tensorrt as trt from cuda import cudart np.random.seed(31193) paddle.seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 paddleFilePath = "./model/model" onnxFile = "./model.onnx" trtFile = "./model.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.npz ./*.plan ./*.cache " + paddleFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) cudart.cudaDeviceSynchronize() def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, 1, nHeight, nWidth], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(1, nHeight, nWidth).astype(np.float32) / 255 yData[i] = label return xData, yData # Create network and train model in Paddlepaddle ------------------------------- class Net(paddle.nn.Layer): def __init__(self, num_classes=1): super(Net, self).__init__() self.conv1 = paddle.nn.Conv2D(1, 32, [5, 5], 1, 2) self.pool1 = paddle.nn.MaxPool2D(2, 2) self.conv2 = paddle.nn.Conv2D(32, 64, [5, 5], 1, 2) self.pool2 = paddle.nn.MaxPool2D(2, 2) self.flatten = paddle.nn.Flatten(1) self.fc1 = paddle.nn.Linear(64 * 7 * 7, 1024) self.fc2 = paddle.nn.Linear(1024, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.pool1(x) x = self.conv2(x) x = F.relu(x) x = self.pool2(x) x = self.flatten(x) x = self.fc1(x) x = F.relu(x) y = self.fc2(x) z = F.softmax(y, 1) z = paddle.argmax(z, 1) return y, z model = Net() model.train() opt = paddle.optimizer.Adam(0.001, parameters=model.parameters()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) xSample = paddle.to_tensor(xSample) ySample = paddle.to_tensor(ySample) y, z = model(xSample) loss = F.cross_entropy(y, paddle.argmax(ySample, 1, keepdim=True)) loss.backward() opt.step() opt.clear_grad() if i % 10 == 0: accuracyValue = paddle.sum(z - paddle.argmax(ySample, 1) == 0).numpy().item() / nTrainBatchSize print("%s, batch %3d, train acc = %f" % (dt.now(), 10 + i, accuracyValue)) model.eval() xTest, yTest = getBatch(testFileList, nTrainBatchSize, False) xTest = paddle.to_tensor(xTest) yTest = paddle.to_tensor(yTest) accuracyValue = 0 for i in range(len(testFileList) // nTrainBatchSize): xSample = xTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] ySample = yTest[i * nTrainBatchSize:(i + 1) * nTrainBatchSize] y, z = model(xSample) accuracyValue += paddle.sum(z - paddle.argmax(ySample, 1) == 0).numpy().item() print("%s, test acc = %f" % (dt.now(), accuracyValue / (len(testFileList) // nTrainBatchSize * nTrainBatchSize))) print("Succeeded building model in Paddlepaddle!") # Export model as ONNX file ---------------------------------------------------- inputDescList = [] inputDescList.append(paddle.static.InputSpec(shape=[None, 1, nHeight, nWidth], dtype='float32', name='x')) paddle.onnx.export(model, onnxFile[:-5], input_spec=inputDescList, opset_version=11) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) network.unmark_output(network.get_output(0)) # remove output tensor "y" engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/Paddlepaddle-ONNX-TensorRT/main.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-ONNX-TensorRT/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf1 import tensorrt as trt np.random.seed(31193) tf1.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFile = "./model-NHWC.pb" onnxFile = "./model-NHWC.onnx" trtFile = "./model-NHWC.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" trtVersion = trt.__version__.split(".") # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf1.compat.v1.disable_eager_execution() cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow1 -------------------------------- def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData x = tf1.compat.v1.placeholder(tf1.float32, [None, nHeight, nWidth, 1], name="x") y_ = tf1.compat.v1.placeholder(tf1.float32, [None, 10], name="y_") w1 = tf1.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf1.compat.v1.get_variable("b1", shape=[32], initializer=tf1.constant_initializer(value=0.1)) h1 = tf1.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf1.nn.relu(h2) h4 = tf1.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf1.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf1.compat.v1.get_variable("b2", shape=[64], initializer=tf1.constant_initializer(value=0.1)) h5 = tf1.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf1.nn.relu(h6) h8 = tf1.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf1.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf1.compat.v1.get_variable("b3", shape=[1024], initializer=tf1.constant_initializer(value=0.1)) h9 = tf1.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf1.matmul(h9, w3) h11 = h10 + b3 h12 = tf1.nn.relu(h11) w4 = tf1.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf1.compat.v1.get_variable("b4", shape=[10], initializer=tf1.constant_initializer(value=0.1)) h13 = tf1.matmul(h12, w4) h14 = h13 + b4 y = tf1.nn.softmax(h14, name="y") z = tf1.argmax(y, 1, name="z") crossEntropy = -tf1.reduce_sum(y_ * tf1.math.log(y)) trainStep = tf1.compat.v1.train.AdamOptimizer(1e-4).minimize(crossEntropy) accuracy = tf1.reduce_mean(tf1.cast(tf1.equal(z, tf1.argmax(y_, 1)), tf1.float32), name="accuracy") tfConfig = tf1.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf1.compat.v1.Session(config=tfConfig) sess.run(tf1.compat.v1.global_variables_initializer()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) trainStep.run(session=sess, feed_dict={x: xSample, y_: ySample}) if i % 10 == 0: accuracyValue = accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, batch %3d, acc = %f" % (dt.now(), 10 + i, accuracyValue)) constantGraph = tf1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["z"]) with tf1.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) sess.close() print("Succeeded building model in TensorFlow1!") # Export model as ONNX file ---------------------------------------------------- os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs 'x:0' --outputs 'z:0'" % (pbFile, onnxFile)) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, nHeight, nWidth, 1] profile.set_shape(inputTensor.name, [1, nHeight, nWidth, 1], [4, nHeight, nWidth, 1], [8, nHeight, nWidth, 1]) config.add_optimization_profile(profile) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, nHeight, nWidth, 1]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-ONNX-TensorRT/main-NHWC.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf1 import tensorrt as trt np.random.seed(31193) tf1.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFile = "./model-NCHW.pb" onnxFile = "./model-NCHW.onnx" trtFile = "./model-NCHW.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" trtVersion = trt.__version__.split(".") # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf1.compat.v1.disable_eager_execution() cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow1 -------------------------------- def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData x = tf1.compat.v1.placeholder(tf1.float32, [None, nHeight, nWidth, 1], name="x") y_ = tf1.compat.v1.placeholder(tf1.float32, [None, 10], name="y_") w1 = tf1.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf1.compat.v1.get_variable("b1", shape=[32], initializer=tf1.constant_initializer(value=0.1)) h1 = tf1.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf1.nn.relu(h2) h4 = tf1.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf1.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf1.compat.v1.get_variable("b2", shape=[64], initializer=tf1.constant_initializer(value=0.1)) h5 = tf1.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf1.nn.relu(h6) h8 = tf1.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf1.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf1.compat.v1.get_variable("b3", shape=[1024], initializer=tf1.constant_initializer(value=0.1)) h9 = tf1.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf1.matmul(h9, w3) h11 = h10 + b3 h12 = tf1.nn.relu(h11) w4 = tf1.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf1.compat.v1.get_variable("b4", shape=[10], initializer=tf1.constant_initializer(value=0.1)) h13 = tf1.matmul(h12, w4) h14 = h13 + b4 y = tf1.nn.softmax(h14, name="y") z = tf1.argmax(y, 1, name="z") crossEntropy = -tf1.reduce_sum(y_ * tf1.math.log(y)) trainStep = tf1.compat.v1.train.AdamOptimizer(1e-4).minimize(crossEntropy) accuracy = tf1.reduce_mean(tf1.cast(tf1.equal(z, tf1.argmax(y_, 1)), tf1.float32), name="accuracy") tfConfig = tf1.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf1.compat.v1.Session(config=tfConfig) sess.run(tf1.compat.v1.global_variables_initializer()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) trainStep.run(session=sess, feed_dict={x: xSample, y_: ySample}) if i % 10 == 0: accuracyValue = accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, batch %3d, acc = %f" % (dt.now(), 10 + i, accuracyValue)) constantGraph = tf1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["z"]) with tf1.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) sess.close() print("Succeeded building model in TensorFlow1!") # Export model as ONNX file ---------------------------------------------------- os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs 'x:0' --outputs 'z:0' --inputs-as-nchw 'x:0'" % (pbFile, onnxFile)) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, nHeight, nWidth] profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(data)) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-ONNX-TensorRT/main-NCHW.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf1 import tensorrt as trt np.random.seed(31193) tf1.compat.v1.set_random_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFile = "./model-NHWC-C2.pb" onnxFile = "./model-NHWC-C2.onnx" trtFile = "./model-NHWC-C2.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" trtVersion = trt.__version__.split(".") # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf ./*.plan ./*.cache") np.set_printoptions(precision=3, linewidth=200, suppress=True) tf1.compat.v1.disable_eager_execution() cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow1 -------------------------------- def getBatch(fileList, nSize=1, isTrain=True): if isTrain: indexList = np.random.choice(len(fileList), nSize) else: nSize = len(fileList) indexList = np.arange(nSize) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i, index in enumerate(indexList): imageName = fileList[index] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData x = tf1.compat.v1.placeholder(tf1.float32, [None, nHeight, nWidth, 2], name="x") y_ = tf1.compat.v1.placeholder(tf1.float32, [None, 10], name="y_") w1 = tf1.compat.v1.get_variable("w1", shape=[5, 5, 1, 32], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b1 = tf1.compat.v1.get_variable("b1", shape=[32], initializer=tf1.constant_initializer(value=0.1)) h1 = tf1.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding="SAME") h2 = h1 + b1 h3 = tf1.nn.relu(h2) h4 = tf1.nn.max_pool2d(h3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w2 = tf1.compat.v1.get_variable("w2", shape=[5, 5, 32, 64], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b2 = tf1.compat.v1.get_variable("b2", shape=[64], initializer=tf1.constant_initializer(value=0.1)) h5 = tf1.nn.conv2d(h4, w2, strides=[1, 1, 1, 1], padding="SAME") h6 = h5 + b2 h7 = tf1.nn.relu(h6) h8 = tf1.nn.max_pool2d(h7, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") w3 = tf1.compat.v1.get_variable("w3", shape=[7 * 7 * 64, 1024], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b3 = tf1.compat.v1.get_variable("b3", shape=[1024], initializer=tf1.constant_initializer(value=0.1)) h9 = tf1.reshape(h8, [-1, 7 * 7 * 64]) h10 = tf1.matmul(h9, w3) h11 = h10 + b3 h12 = tf1.nn.relu(h11) w4 = tf1.compat.v1.get_variable("w4", shape=[1024, 10], initializer=tf1.truncated_normal_initializer(mean=0, stddev=0.1)) b4 = tf1.compat.v1.get_variable("b4", shape=[10], initializer=tf1.constant_initializer(value=0.1)) h13 = tf1.matmul(h12, w4) h14 = h13 + b4 y = tf1.nn.softmax(h14, name="y") z = tf1.argmax(y, 1, name="z") crossEntropy = -tf1.reduce_sum(y_ * tf1.math.log(y)) trainStep = tf1.compat.v1.train.AdamOptimizer(1e-4).minimize(crossEntropy) accuracy = tf1.reduce_mean(tf1.cast(tf1.equal(z, tf1.argmax(y_, 1)), tf1.float32), name="accuracy") tfConfig = tf1.compat.v1.ConfigProto() tfConfig.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf1.compat.v1.Session(config=tfConfig) sess.run(tf1.compat.v1.global_variables_initializer()) for i in range(100): xSample, ySample = getBatch(trainFileList, nTrainBatchSize, True) xSample = np.tile(xSample, [1, 1, 1, 2]) trainStep.run(session=sess, feed_dict={x: xSample, y_: ySample}) if i % 10 == 0: accuracyValue = accuracy.eval(session=sess, feed_dict={x: xSample, y_: ySample}) print("%s, batch %3d, acc = %f" % (dt.now(), 10 + i, accuracyValue)) constantGraph = tf1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["z"]) with tf1.gfile.FastGFile(pbFile, mode="wb") as f: f.write(constantGraph.SerializeToString()) sess.close() print("Succeeded building model in TensorFlow1!") # Export model as ONNX file ---------------------------------------------------- os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs 'x:0' --outputs 'z:0'" % (pbFile, onnxFile)) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, nHeight, nWidth, 2] profile.set_shape(inputTensor.name, [1, nHeight, nWidth, 2], [4, nHeight, nWidth, 2], [8, nHeight, nWidth, 2]) config.add_optimization_profile(profile) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, nHeight, nWidth, 2]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH.append(np.ascontiguousarray(np.tile(data, [1, 1, 1, 2]))) for i in range(nInput, nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow1-ONNX-TensorRT/main-NHWC-C2.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from glob import glob import cv2 import numpy as np import tensorrt as trt from cuda import cudart class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, calibrationDataPath, nCalibration, inputShape, cacheFile): trt.IInt8EntropyCalibrator2.__init__(self) self.imageList = glob(calibrationDataPath + "*.jpg")[:100] self.nCalibration = nCalibration self.shape = inputShape # (N,C,H,W) self.buffeSize = trt.volume(inputShape) * trt.float32.itemsize self.cacheFile = cacheFile _, self.dIn = cudart.cudaMalloc(self.buffeSize) self.oneBatch = self.batchGenerator() print(int(self.dIn)) def __del__(self): cudart.cudaFree(self.dIn) def batchGenerator(self): for i in range(self.nCalibration): print("> calibration %d" % i) subImageList = np.random.choice(self.imageList, self.shape[0], replace=False) yield np.ascontiguousarray(self.loadImageList(subImageList)) def loadImageList(self, imageList): res = np.empty(self.shape, dtype=np.float32) for i in range(self.shape[0]): res[i, 0] = cv2.imread(imageList[i], cv2.IMREAD_GRAYSCALE).astype(np.float32) return res def get_batch_size(self): # necessary API return self.shape[0] def get_batch(self, nameList=None, inputNodeName=None): # necessary API try: data = next(self.oneBatch) cudart.cudaMemcpy(self.dIn, data.ctypes.data, self.buffeSize, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) return [int(self.dIn)] except StopIteration: return None def read_calibration_cache(self): # necessary API if os.path.exists(self.cacheFile): print("Succeed finding cahce file: %s" % (self.cacheFile)) with open(self.cacheFile, "rb") as f: cache = f.read() return cache else: print("Failed finding int8 cache!") return def write_calibration_cache(self, cache): # necessary API with open(self.cacheFile, "wb") as f: f.write(cache) print("Succeed saving int8 cache!") return if __name__ == "__main__": cudart.cudaDeviceSynchronize() m = MyCalibrator("../../00-MNISTData/test/", 5, (1, 1, 28, 28), "./int8.cache") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList") m.get_batch("FakeNameList")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT/calibrator.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model-NHWC/" pbFile = "model-NHWC.pb" onnxFile = "./model-NHWC.onnx" trtFile = "./model-NHWC.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # Two equivalent method to export ONNX file, using single .pb file or several files in a directory bSinglePbFile = True # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf %s ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow2 -------------------------------- def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) tf2.saved_model.save(model, pbFilePath) if bSinglePbFile: modelFunction = tf2.function(lambda Input: model(Input)).get_concrete_function(tf2.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)) frozen_func = convert_variables_to_constants_v2(modelFunction) frozen_func.graph.as_graph_def() print("_________________________________________________________________") print("Frozen model inputs:\n", frozen_func.inputs) print("Frozen model outputs:\n", frozen_func.outputs) print("Frozen model layers:") for op in frozen_func.graph.get_operations(): print(op.name) tf2.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=pbFilePath, name=pbFile, as_text=False) print("Succeeded building model in TensorFlow2!") # Export model as ONNX file ---------------------------------------------------- if bSinglePbFile: os.system("python3 -m tf2onnx.convert --input %s --output %s --opset 13 --inputs 'Input:0' --outputs 'Identity:0'" % (pbFilePath + pbFile, onnxFile)) else: os.system("python3 -m tf2onnx.convert --saved-model %s --output %s --opset 13" % (pbFilePath, onnxFile)) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, nHeight, nWidth, 1] profile.set_shape(inputTensor.name, [1, nHeight, nWidth, 1], [4, nHeight, nWidth, 1], [8, nHeight, nWidth, 1]) config.add_optimization_profile(profile) outputTensor = network.get_output(0) network.unmark_output(outputTensor) _17 = network.add_topk(outputTensor, trt.TopKOperation.MAX, 1, 1 << 1) # add last ArgMax node network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, nHeight, nWidth, 1]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] for i in range(nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, nHeight, nWidth, 1) bufferH[0] = data for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT/main-NHWC.py
# # Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed 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. # import os from datetime import datetime as dt from glob import glob import cv2 import numpy as np from cuda import cudart os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import calibrator import tensorflow as tf2 import tensorrt as trt from tensorflow.python.framework.convert_to_constants import \ convert_variables_to_constants_v2 np.random.seed(31193) tf2.random.set_seed(97) nTrainBatchSize = 128 nHeight = 28 nWidth = 28 pbFilePath = "./model-NCHW/" pbFile = "model-NCHW.pb" onnxFile = "./model-NCHW.onnx" trtFile = "./model-NCHW.plan" dataPath = os.path.dirname(os.path.realpath(__file__)) + "/../../00-MNISTData/" trainFileList = sorted(glob(dataPath + "train/*.jpg")) testFileList = sorted(glob(dataPath + "test/*.jpg")) inferenceImage = dataPath + "8.png" # Two equivalent method to export ONNX file, using single .pb file or several files in a directory bSinglePbFile = True # for FP16 mode bUseFP16Mode = False # for INT8 model bUseINT8Mode = False nCalibration = 1 cacheFile = "./int8.cache" calibrationDataPath = dataPath + "test/" os.system("rm -rf %s ./*.plan ./*.cache" % pbFilePath) np.set_printoptions(precision=3, linewidth=200, suppress=True) tf2.config.experimental.set_memory_growth(tf2.config.list_physical_devices("GPU")[0], True) cudart.cudaDeviceSynchronize() # Create network and train model in TensorFlow2 -------------------------------- def getData(fileList): nSize = len(fileList) xData = np.zeros([nSize, nHeight, nWidth, 1], dtype=np.float32) yData = np.zeros([nSize, 10], dtype=np.float32) for i in range(nSize): imageName = fileList[i] data = cv2.imread(imageName, cv2.IMREAD_GRAYSCALE) label = np.zeros(10, dtype=np.float32) label[int(imageName[-7])] = 1 xData[i] = data.reshape(nHeight, nWidth, 1).astype(np.float32) / 255 yData[i] = label return xData, yData modelInput = tf2.keras.Input(shape=[nHeight, nWidth, 1], dtype=tf2.dtypes.float32) layerConv1 = tf2.keras.layers.Conv2D(32, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv1") x = layerConv1(modelInput) layerPool1 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool1") x = layerPool1(x) layerConv2 = tf2.keras.layers.Conv2D(64, [5, 5], strides=[1, 1], padding="same", data_format=None, dilation_rate=[1, 1], groups=1, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="conv2") x = layerConv2(x) laerPool2 = tf2.keras.layers.MaxPool2D(pool_size=[2, 2], strides=[2, 2], padding="same", data_format=None, name="pool2") x = laerPool2(x) layerReshape = tf2.keras.layers.Reshape([-1], name="reshape") x = layerReshape(x) layerDense1 = tf2.keras.layers.Dense(1024, activation="relu", use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense1") x = layerDense1(x) layerDense2 = tf2.keras.layers.Dense(10, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name="dense2") x = layerDense2(x) layerSoftmax = tf2.keras.layers.Softmax(axis=1, name="softmax") z = layerSoftmax(x) model = tf2.keras.Model(inputs=modelInput, outputs=z, name="MNISTExample") model.summary() model.compile( loss=tf2.keras.losses.CategoricalCrossentropy(from_logits=False), optimizer=tf2.keras.optimizers.Adam(), metrics=["accuracy"], ) xTrain, yTrain = getData(trainFileList) history = model.fit(xTrain, yTrain, batch_size=128, epochs=10, validation_split=0.1) xTest, yTest = getData(testFileList) testScore = model.evaluate(xTest, yTest, verbose=2) print("%s, loss = %f, accuracy = %f" % (dt.now(), testScore[0], testScore[1])) tf2.saved_model.save(model, pbFilePath) if bSinglePbFile: modelFunction = tf2.function(lambda Input: model(Input)).get_concrete_function(tf2.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)) frozen_func = convert_variables_to_constants_v2(modelFunction) frozen_func.graph.as_graph_def() print("_________________________________________________________________") print("Frozen model inputs:\n", frozen_func.inputs) print("Frozen model outputs:\n", frozen_func.outputs) print("Frozen model layers:") for op in frozen_func.graph.get_operations(): print(op.name) tf2.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=pbFilePath, name=pbFile, as_text=False) print("Succeeded building model in TensorFlow2!") # Export model as ONNX file ---------------------------------------------------- if bSinglePbFile: os.system("python3 -m tf2onnx.convert --input %s --output %s --inputs-as-nchw 'Input:0' --opset 13 --inputs 'Input:0' --outputs 'Identity:0'" % (pbFilePath + pbFile, onnxFile)) else: os.system("python3 -m tf2onnx.convert --saved-model %s --output %s --inputs-as-nchw 'Input:0' --opset 13" % (pbFilePath, onnxFile)) print("Succeeded converting model into ONNX!") # Parse network, rebuild network and do inference in TensorRT ------------------ logger = trt.Logger(trt.Logger.VERBOSE) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) profile = builder.create_optimization_profile() config = builder.create_builder_config() if bUseFP16Mode: config.set_flag(trt.BuilderFlag.FP16) if bUseINT8Mode: config.set_flag(trt.BuilderFlag.INT8) config.int8_calibrator = calibrator.MyCalibrator(calibrationDataPath, nCalibration, (1, 1, nHeight, nWidth), cacheFile) parser = trt.OnnxParser(network, logger) if not os.path.exists(onnxFile): print("Failed finding ONNX file!") exit() print("Succeeded finding ONNX file!") with open(onnxFile, "rb") as model: if not parser.parse(model.read()): print("Failed parsing .onnx file!") for error in range(parser.num_errors): print(parser.get_error(error)) exit() print("Succeeded parsing .onnx file!") inputTensor = network.get_input(0) inputTensor.shape = [-1, 1, nHeight, nWidth] profile.set_shape(inputTensor.name, [1, 1, nHeight, nWidth], [4, 1, nHeight, nWidth], [8, 1, nHeight, nWidth]) config.add_optimization_profile(profile) outputTensor = network.get_output(0) network.unmark_output(outputTensor) _17 = network.add_topk(outputTensor, trt.TopKOperation.MAX, 1, 1 << 1) # add last ArgMax node network.mark_output(_17.get_output(1)) engineString = builder.build_serialized_network(network, config) if engineString == None: print("Failed building engine!") exit() print("Succeeded building engine!") with open(trtFile, "wb") as f: f.write(engineString) engine = trt.Runtime(logger).deserialize_cuda_engine(engineString) nIO = engine.num_io_tensors lTensorName = [engine.get_tensor_name(i) for i in range(nIO)] nInput = [engine.get_tensor_mode(lTensorName[i]) for i in range(nIO)].count(trt.TensorIOMode.INPUT) context = engine.create_execution_context() context.set_input_shape(lTensorName[0], [1, 1, nHeight, nWidth]) for i in range(nIO): print("[%2d]%s->" % (i, "Input " if i < nInput else "Output"), engine.get_tensor_dtype(lTensorName[i]), engine.get_tensor_shape(lTensorName[i]), context.get_tensor_shape(lTensorName[i]), lTensorName[i]) bufferH = [] for i in range(nIO): bufferH.append(np.empty(context.get_tensor_shape(lTensorName[i]), dtype=trt.nptype(engine.get_tensor_dtype(lTensorName[i])))) bufferD = [] for i in range(nIO): bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1]) data = cv2.imread(inferenceImage, cv2.IMREAD_GRAYSCALE).astype(np.float32).reshape(1, 1, nHeight, nWidth) bufferH[0] = data for i in range(nInput): cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) for i in range(nIO): context.set_tensor_address(lTensorName[i], int(bufferD[i])) context.execute_async_v3(0) for i in range(nInput, nIO): cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) for i in range(nIO): print(lTensorName[i]) print(bufferH[i]) for b in bufferD: cudart.cudaFree(b) print("Succeeded running model in TensorRT!")
trt-samples-for-hackathon-cn-master
cookbook/04-BuildEngineByONNXParser/TensorFlow2-ONNX-TensorRT/main-NCHW.py