chore: import upstream snapshot with attribution
Docker Image CI / build-ubuntu2004 (push) Waiting to run

This commit is contained in:
wehub-resource-sync
2026-07-13 13:36:55 +08:00
commit c8a779b1bb
1887 changed files with 3245738 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
# TensorRT Python Sample: Stream Writer
This sample demonstrates how to use the TensorRT Python API to serialize an engine directly to a custom stream using the `IStreamWriter` interface, rather than to a file or in-memory buffer. This is useful for advanced scenarios where you want to control how and where the engine bytes are written (e.g., to a network socket, custom buffer, or in-memory stream).
## What does this sample do?
- Builds a simple TensorRT network with two convolutional layers and ReLU activations.
- Implements a custom `StreamWriter` class inheriting from `trt.IStreamWriter` to collect serialized engine bytes.
- Serializes the engine using `builder.build_serialized_network_to_stream()` and writes the bytes to the custom stream.
- Deserializes the engine from the collected bytes to verify correctness.
## File Structure
- `build.py`: Main script containing the sample code.
- `README.md`: This document.
## How to Run
1. **Install Requirements**
Make sure you have the following Python packages installed:
- `tensorrt`
- `numpy`
- `polygraphy`
You can install Polygraphy via pip:
```
pip install polygraphy
```
The `tensorrt` Python package is typically provided by NVIDIA as a wheel file.
2. **Run the Sample**
```
python3 build.py
```
You should see output indicating the network is constructed, the engine is built and serialized to the stream, and then deserialized successfully.
## Key Concepts
- **IStreamWriter**: An interface in TensorRT that allows you to define custom logic for writing serialized engine bytes. You must implement the `write(self, data)` method.
- **build_serialized_network_to_stream**: A method that serializes the network and writes the bytes to the provided `IStreamWriter` instance.
## Example Output
```
Constructing network...
[I] TF32 is disabled by default. Turn on TF32 for better performance with minor accuracy differences.
[I] Configuring with profiles:[
Profile 0:
{input [min=[1, 3, 224, 224], opt=[1, 3, 224, 224], max=[1, 3, 224, 224]]}
]
Building engine and serializing to stream...
The total bytes written to stream is 267836
Deserializing engine from stream...
Engine deserialized successfully
```
# License
For terms and conditions for use, reproduction, and distribution, see the [TensorRT Software License Agreement](https://docs.nvidia.com/deeplearning/sdk/tensorrt-sla/index.html) documentation.
# Changelog
September 2025
Initial release of this sample.
# Known issues
There are no known issues in this sample.
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2026 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 tensorrt as trt
import numpy as np
from polygraphy.logger import G_LOGGER
from polygraphy.backend.trt import (
CreateNetwork,
CreateConfig,
engine_bytes_from_network,
get_trt_logger
)
DEBUG_LOG = False # Turn on to print TRT verbose logs
if DEBUG_LOG:
verbose = G_LOGGER.verbosity(G_LOGGER.SUPER_VERBOSE)
verbose.__enter__()
else:
verbose = None
def build_network():
builder, network = CreateNetwork()()
# A simple network with internal tensors
input_tensor = network.add_input(name="input", dtype=trt.float32, shape=(1, 3, 224, 224))
conv1_w = np.random.randn(16, 3, 3, 3).astype(np.float32)
conv1_b = np.random.randn(16).astype(np.float32)
conv1 = network.add_convolution_nd(input=input_tensor, num_output_maps=16, kernel_shape=(3, 3), kernel=conv1_w, bias=conv1_b)
relu1 = network.add_activation(input=conv1.get_output(0), type=trt.ActivationType.RELU)
conv2_w = np.random.randn(32, 16, 3, 3).astype(np.float32)
conv2_b = np.random.randn(32).astype(np.float32)
conv2 = network.add_convolution_nd(input=relu1.get_output(0), num_output_maps=32, kernel_shape=(3, 3), kernel=conv2_w, bias=conv2_b)
relu2 = network.add_activation(input=conv2.get_output(0), type=trt.ActivationType.RELU)
network.mark_output(tensor=relu2.get_output(0))
return builder, network
class StreamWriter(trt.IStreamWriter):
def __init__(self):
trt.IStreamWriter.__init__(self)
self.bytes = bytes()
def write(self, data):
self.bytes += data
return len(data)
def build_engine():
print("Constructing network...")
builder, network = build_network()
config = CreateConfig()(builder, network)
stream_writer = StreamWriter()
print("Building engine and serializing to stream...")
engine_bytes = builder.build_serialized_network_to_stream(network, config, stream_writer)
print("The total bytes written to stream is: ", len(stream_writer.bytes))
runtime = trt.Runtime(get_trt_logger())
print("Deserializing engine from stream...")
engine = runtime.deserialize_cuda_engine(stream_writer.bytes)
assert engine is not None, "Engine deserialization failed"
print("Engine deserialized successfully")
if __name__ == "__main__":
build_engine()
if verbose is not None:
verbose.__exit__(None, None, None)