Skip to content

Commit 639c2a3

Browse files
committed
feat(//py): Manylinux container and build system for multiple python
versions Signed-off-by: Naren Dasan <[email protected]> Signed-off-by: Naren Dasan <[email protected]>
1 parent 9e37dc1 commit 639c2a3

File tree

8 files changed

+297
-22
lines changed

8 files changed

+297
-22
lines changed

.gitignore

+3-1
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,6 @@ __pycache__
3333
*.egg-info
3434
dist
3535
bdist
36-
py/trtorch/_version.py
36+
py/trtorch/_version.py
37+
py/wheelhouse
38+
py/.eggs

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,16 @@ A tarball with the include files and library can then be found in bazel-bin
137137
bazel run //cpp/trtorchexec -- $(realpath <PATH TO GRAPH>) <input-size>
138138
```
139139

140+
## Compiling the Python Package
141+
142+
To compile the python package for your local machine, just run `python3 setup.py install` in the `//py` directory.
143+
To build wheel files for different python versions, first build the Dockerfile in ``//py`` then run the following
144+
command
145+
```
146+
docker run -it -v$(pwd)/..:/workspace/TRTorch build_trtorch_wheel /bin/bash /workspace/TRTorch/py/build_whl.sh
147+
```
148+
Python compilation expects using the tarball based compilation strategy from above.
149+
140150
## How do I add support for a new op...
141151

142152
### In TRTorch?

py/Dockerfile

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
FROM pytorch/manylinux-cuda102
2+
3+
RUN yum install -y ninja-build
4+
5+
RUN wget https://copr.fedorainfracloud.org/coprs/vbatts/bazel/repo/epel-7/vbatts-bazel-epel-7.repo \
6+
&& mv vbatts-bazel-epel-7.repo /etc/yum.repos.d/
7+
8+
RUN yum install -y bazel3
9+
10+
RUN mv /usr/bin/ninja-build /usr/bin/ninja
11+
12+
RUN mkdir /workspace
13+
14+
WORKDIR /workspace

py/LICENSE

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../LICENSE

py/README.md

+168
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# trtorch
2+
3+
> Ahead of Time (AOT) compiling for PyTorch JIT
4+
5+
TRTorch is a compiler for PyTorch/TorchScript, targeting NVIDIA GPUs via NVIDIA's TensorRT Deep Learning Optimizer and Runtime. Unlike PyTorch's Just-In-Time (JIT) compiler, TRTorch is an Ahead-of-Time (AOT) compiler, meaning that before you deploy your TorchScript code, you go through an explicit compile step to convert a standard TorchScript program into an module targeting a TensorRT engine. TRTorch operates as a PyTorch extention and compiles modules that integrate into the JIT runtime seamlessly. After compilation using the optimized graph should feel no different than running a TorchScript module. You also have access to TensorRT's suite of configurations at compile time, so you are able to specify operating precision (FP32/FP16/INT8) and other settings for your module.
6+
7+
## Example Usage
8+
9+
``` python
10+
import torch
11+
import torchvision
12+
import trtorch
13+
14+
# Get a model
15+
model = torchvision.models.alexnet(pretrained=True).eval().cuda()
16+
17+
# Create some example data
18+
data = torch.randn((1, 3, 224, 224)).to("cuda")
19+
20+
# Trace the module with example data
21+
traced_model = torch.jit.trace(model, [data])
22+
23+
# Compile module
24+
compiled_trt_model = trtorch.compile(model, {
25+
"input_shape": [data.shape],
26+
"op_precision": torch.half, # Run in FP16
27+
})
28+
29+
results = compiled_trt_model(data.half())
30+
```
31+
32+
## Installation
33+
34+
```
35+
pip3 install trtorch
36+
```
37+
38+
## Under the Hood
39+
40+
When a traced module is provided to TRTorch, the compiler takes the internal representation and transforms it into one like this:
41+
42+
```
43+
graph(%input.2 : Tensor):
44+
%2 : Float(84, 10) = prim::Constant[value=<Tensor>]()
45+
%3 : Float(120, 84) = prim::Constant[value=<Tensor>]()
46+
%4 : Float(576, 120) = prim::Constant[value=<Tensor>]()
47+
%5 : int = prim::Constant[value=-1]() # x.py:25:0
48+
%6 : int[] = prim::Constant[value=annotate(List[int], [])]()
49+
%7 : int[] = prim::Constant[value=[2, 2]]()
50+
%8 : int[] = prim::Constant[value=[0, 0]]()
51+
%9 : int[] = prim::Constant[value=[1, 1]]()
52+
%10 : bool = prim::Constant[value=1]() # ~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py:346:0
53+
%11 : int = prim::Constant[value=1]() # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:539:0
54+
%12 : bool = prim::Constant[value=0]() # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:539:0
55+
%self.classifer.fc3.bias : Float(10) = prim::Constant[value= 0.0464 0.0383 0.0678 0.0932 0.1045 -0.0805 -0.0435 -0.0818 0.0208 -0.0358 [ CUDAFloatType{10} ]]()
56+
%self.classifer.fc2.bias : Float(84) = prim::Constant[value=<Tensor>]()
57+
%self.classifer.fc1.bias : Float(120) = prim::Constant[value=<Tensor>]()
58+
%self.feat.conv2.weight : Float(16, 6, 3, 3) = prim::Constant[value=<Tensor>]()
59+
%self.feat.conv2.bias : Float(16) = prim::Constant[value=<Tensor>]()
60+
%self.feat.conv1.weight : Float(6, 1, 3, 3) = prim::Constant[value=<Tensor>]()
61+
%self.feat.conv1.bias : Float(6) = prim::Constant[value= 0.0530 -0.1691 0.2802 0.1502 0.1056 -0.1549 [ CUDAFloatType{6} ]]()
62+
%input0.4 : Tensor = aten::_convolution(%input.2, %self.feat.conv1.weight, %self.feat.conv1.bias, %9, %8, %9, %12, %8, %11, %12, %12, %10) # ~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py:346:0
63+
%input0.5 : Tensor = aten::relu(%input0.4) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:1063:0
64+
%input1.2 : Tensor = aten::max_pool2d(%input0.5, %7, %6, %8, %9, %12) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:539:0
65+
%input0.6 : Tensor = aten::_convolution(%input1.2, %self.feat.conv2.weight, %self.feat.conv2.bias, %9, %8, %9, %12, %8, %11, %12, %12, %10) # ~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py:346:0
66+
%input2.1 : Tensor = aten::relu(%input0.6) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:1063:0
67+
%x.1 : Tensor = aten::max_pool2d(%input2.1, %7, %6, %8, %9, %12) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:539:0
68+
%input.1 : Tensor = aten::flatten(%x.1, %11, %5) # x.py:25:0
69+
%27 : Tensor = aten::matmul(%input.1, %4)
70+
%28 : Tensor = trt::const(%self.classifer.fc1.bias)
71+
%29 : Tensor = aten::add_(%28, %27, %11)
72+
%input0.2 : Tensor = aten::relu(%29) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:1063:0
73+
%31 : Tensor = aten::matmul(%input0.2, %3)
74+
%32 : Tensor = trt::const(%self.classifer.fc2.bias)
75+
%33 : Tensor = aten::add_(%32, %31, %11)
76+
%input1.1 : Tensor = aten::relu(%33) # ~/.local/lib/python3.6/site-packages/torch/nn/functional.py:1063:0
77+
%35 : Tensor = aten::matmul(%input1.1, %2)
78+
%36 : Tensor = trt::const(%self.classifer.fc3.bias)
79+
%37 : Tensor = aten::add_(%36, %35, %11)
80+
return (%37)
81+
(CompileGraph)
82+
```
83+
84+
The graph has now been transformed from a collection of modules much like how your PyTorch Modules are collections of modules, each managing their own parameters into a single graph
85+
with the parameters inlined into the graph and all of the operations laid out. TRTorch has also executed a number of optimizations and mappings to make the graph easier to translate
86+
to TensorRT. From here the compiler can assemble the TensorRT engine by following the dataflow through the graph.
87+
88+
When the graph construction phase is complete, TRTorch produces a serialized TensorRT engine. From here depending on the API, this engine is returned to the user or moves into the graph
89+
construction phase. Here TRTorch creates a JIT Module to execute the TensorRT engine which will be instantiated and managed by the TRTorch runtime.
90+
91+
Here is the graph that you get back after compilation is complete:
92+
93+
```
94+
graph(%self.1 : __torch__.___torch_mangle_10.LeNet_trt,
95+
%2 : Tensor):
96+
%1 : int = prim::Constant[value=94106001690080]()
97+
%3 : Tensor = trt::execute_engine(%1, %2)
98+
return (%3)
99+
(AddEngineToGraph)
100+
```
101+
102+
You can see the call where the engine is executed, based on a constant which is the ID of the engine, telling JIT how to find the engine and the input tensor which will be fed to TensorRT.
103+
The engine represents the exact same calculations as what is done by running a normal PyTorch module but optimized to run on your GPU.
104+
105+
TRTorch converts from TorchScript by generating layers or subgraphs in correspondance with instructions seen in the graph. Converters are small modules of code used to map one specific
106+
operation to a layer or subgraph in TensorRT. Not all operations are support, but if you need to implement one, you can in C++.
107+
108+
## Registering Custom Converters
109+
110+
Operations are mapped to TensorRT through the use of modular converters, a function that takes a node from a the JIT graph and produces an equivalent layer or subgraph in TensorRT. TRTorch
111+
ships with a library of these converters stored in a registry, that will be executed depending on the node being parsed. For instance a `aten::relu(%input0.4)` instruction will trigger the
112+
relu converter to be run on it, producing an activation layer in the TensorRT graph. But since this library is not exhaustive you may need to write your own to get TRTorch to support your module.
113+
114+
Shipped with the TRTorch distribution are the internal core API headers. You can therefore access the converter registry and add a converter for the op you need.
115+
116+
For example, if we try to compile a graph with a build of TRTorch that doesn’t support the flatten operation (`aten::flatten`) you may see this error:
117+
118+
```
119+
terminate called after throwing an instance of 'trtorch::Error'
120+
what(): [enforce fail at core/conversion/conversion.cpp:109] Expected converter to be true but got false
121+
Unable to convert node: %input.1 : Tensor = aten::flatten(%x.1, %11, %5) # x.py:25:0 (conversion.AddLayer)
122+
Schema: aten::flatten.using_ints(Tensor self, int start_dim=0, int end_dim=-1) -> (Tensor)
123+
Converter for aten::flatten requested, but no such converter was found.
124+
If you need a converter for this operator, you can try implementing one yourself
125+
or request a converter: https://www.github.com/NVIDIA/TRTorch/issues
126+
```
127+
128+
We can register a converter for this operator in our application. All of the tools required to build a converter can be imported by including `trtorch/core/conversion/converters/converters.h`.
129+
We start by creating an instance of the self-registering `class trtorch::core::conversion::converters::RegisterNodeConversionPatterns()` which will register converters in the global converter
130+
registry, associating a function schema like `aten::flatten.using_ints(Tensor self, int start_dim=0, int end_dim=-1) -> (Tensor)` with a lambda that will take the state of the conversion, the
131+
node/operation in question to convert and all of the inputs to the node and produces as a side effect a new layer in the TensorRT network. Arguments are passed as a vector of inspectable unions
132+
of TensorRT ITensors and Torch IValues in the order arguments are listed in the schema.
133+
134+
Below is a implementation of a `aten::flatten` converter that we can use in our application. You have full access to the Torch and TensorRT libraries in the converter implementation. So for example
135+
we can quickly get the output size by just running the operation in PyTorch instead of implementing the full calculation outself like we do below for this flatten converter.
136+
137+
```c++
138+
#include "torch/script.h"
139+
#include "trtorch/trtorch.h"
140+
#include "trtorch/core/conversion/converters/converters.h"
141+
142+
static auto flatten_converter = trtorch::core::conversion::converters::RegisterNodeConversionPatterns()
143+
.pattern({
144+
"aten::flatten.using_ints(Tensor self, int start_dim=0, int end_dim=-1) -> (Tensor)",
145+
[](trtorch::core::conversion::ConversionCtx* ctx,
146+
const torch::jit::Node* n,
147+
trtorch::core::conversion::converters::args& args) -> bool {
148+
auto in = args[0].ITensor();
149+
auto start_dim = args[1].unwrapToInt();
150+
auto end_dim = args[2].unwrapToInt();
151+
auto in_shape = trtorch::core::util::toVec(in->getDimensions());
152+
auto out_shape = torch::flatten(torch::rand(in_shape), start_dim, end_dim).sizes();
153+
154+
auto shuffle = ctx->net->addShuffle(*in);
155+
shuffle->setReshapeDimensions(trtorch::core::util::toDims(out_shape));
156+
shuffle->setName(trtorch::core::util::node_info(n).c_str());
157+
158+
auto out_tensor = ctx->AssociateValueAndTensor(n->outputs()[0], shuffle->getOutput(0));
159+
return true;
160+
}
161+
});
162+
```
163+
164+
To use this converter in Python, it is recommended to use PyTorch’s [C++ / CUDA Extention](https://pytorch.org/tutorials/advanced/cpp_extension.html#custom-c-and-cuda-extensions) template to wrap
165+
your library of converters into a `.so` that you can load with `ctypes.CDLL()` in your Python application.
166+
167+
You can find more information on all the details of writing converters in the contributors documentation ([Writing Converters](https://nvidia.github.io/TRTorch/contributors/writing_converters.html#writing-converters)). If you
168+
find yourself with a large library of converter implementations, do consider upstreaming them, PRs are welcome and it would be great for the community to benefit as well.

py/build_whl.sh

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/bin/bash
2+
3+
# Example usage: docker run -it -v$(pwd)/..:/workspace/TRTorch build_trtorch_wheel /bin/bash /workspace/TRTorch/py/build_whl.sh
4+
5+
cd /workspace/TRTorch/py
6+
7+
export CXX=g++
8+
9+
build_py35() {
10+
/opt/python/cp35-cp35m/bin/python -m pip install -r requirements.txt
11+
/opt/python/cp35-cp35m/bin/python setup.py bdist_wheel
12+
#auditwheel repair --plat manylinux2014_x86_64
13+
}
14+
15+
build_py36() {
16+
/opt/python/cp36-cp36m/bin/python -m pip install -r requirements.txt
17+
/opt/python/cp36-cp36m/bin/python setup.py bdist_wheel
18+
#auditwheel repair --plat manylinux2014_x86_64
19+
}
20+
21+
build_py37() {
22+
/opt/python/cp37-cp37m/bin/python -m pip install -r requirements.txt
23+
/opt/python/cp37-cp37m/bin/python setup.py bdist_wheel
24+
#auditwheel repair --plat manylinux2014_x86_64
25+
}
26+
27+
build_py38() {
28+
/opt/python/cp38-cp38/bin/python -m pip install -r requirements.txt
29+
/opt/python/cp38-cp38/bin/python setup.py bdist_wheel
30+
#auditwheel repair --plat manylinux2014_x86_64
31+
}
32+
33+
build_py35
34+
build_py36
35+
build_py37
36+
build_py38

py/requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
torch==1.5.0
1+
torch==1.5.0

0 commit comments

Comments
 (0)