Giter VIP home page Giter VIP logo

pytorch / tensorrt Goto Github PK

View Code? Open in Web Editor NEW
2.3K 70.0 329.0 45.41 MB

PyTorch/TorchScript/FX compiler for NVIDIA GPUs using TensorRT

Home Page: https://pytorch.org/TensorRT

License: BSD 3-Clause "New" or "Revised" License

Starlark 0.93% C++ 27.20% C 0.23% Python 37.14% Makefile 0.02% Batchfile 0.01% Dockerfile 0.09% Shell 0.20% Jupyter Notebook 33.56% CMake 0.59% CSS 0.04%
tensorrt libtorch machine-learning pytorch deep-learning jetson nvidia cuda

tensorrt's Introduction

PyTorch Logo


PyTorch is a Python package that provides two high-level features:

  • Tensor computation (like NumPy) with strong GPU acceleration
  • Deep neural networks built on a tape-based autograd system

You can reuse your favorite Python packages such as NumPy, SciPy, and Cython to extend PyTorch when needed.

Our trunk health (Continuous Integration signals) can be found at hud.pytorch.org.

More About PyTorch

Learn the basics of PyTorch

At a granular level, PyTorch is a library that consists of the following components:

Component Description
torch A Tensor library like NumPy, with strong GPU support
torch.autograd A tape-based automatic differentiation library that supports all differentiable Tensor operations in torch
torch.jit A compilation stack (TorchScript) to create serializable and optimizable models from PyTorch code
torch.nn A neural networks library deeply integrated with autograd designed for maximum flexibility
torch.multiprocessing Python multiprocessing, but with magical memory sharing of torch Tensors across processes. Useful for data loading and Hogwild training
torch.utils DataLoader and other utility functions for convenience

Usually, PyTorch is used either as:

  • A replacement for NumPy to use the power of GPUs.
  • A deep learning research platform that provides maximum flexibility and speed.

Elaborating Further:

A GPU-Ready Tensor Library

If you use NumPy, then you have used Tensors (a.k.a. ndarray).

Tensor illustration

PyTorch provides Tensors that can live either on the CPU or the GPU and accelerates the computation by a huge amount.

We provide a wide variety of tensor routines to accelerate and fit your scientific computation needs such as slicing, indexing, mathematical operations, linear algebra, reductions. And they are fast!

Dynamic Neural Networks: Tape-Based Autograd

PyTorch has a unique way of building neural networks: using and replaying a tape recorder.

Most frameworks such as TensorFlow, Theano, Caffe, and CNTK have a static view of the world. One has to build a neural network and reuse the same structure again and again. Changing the way the network behaves means that one has to start from scratch.

With PyTorch, we use a technique called reverse-mode auto-differentiation, which allows you to change the way your network behaves arbitrarily with zero lag or overhead. Our inspiration comes from several research papers on this topic, as well as current and past work such as torch-autograd, autograd, Chainer, etc.

While this technique is not unique to PyTorch, it's one of the fastest implementations of it to date. You get the best of speed and flexibility for your crazy research.

Dynamic graph

Python First

PyTorch is not a Python binding into a monolithic C++ framework. It is built to be deeply integrated into Python. You can use it naturally like you would use NumPy / SciPy / scikit-learn etc. You can write your new neural network layers in Python itself, using your favorite libraries and use packages such as Cython and Numba. Our goal is to not reinvent the wheel where appropriate.

Imperative Experiences

PyTorch is designed to be intuitive, linear in thought, and easy to use. When you execute a line of code, it gets executed. There isn't an asynchronous view of the world. When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward. The stack trace points to exactly where your code was defined. We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines.

Fast and Lean

PyTorch has minimal framework overhead. We integrate acceleration libraries such as Intel MKL and NVIDIA (cuDNN, NCCL) to maximize speed. At the core, its CPU and GPU Tensor and neural network backends are mature and have been tested for years.

Hence, PyTorch is quite fast — whether you run small or large neural networks.

The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives. We've written custom memory allocators for the GPU to make sure that your deep learning models are maximally memory efficient. This enables you to train bigger deep learning models than before.

Extensions Without Pain

Writing new neural network modules, or interfacing with PyTorch's Tensor API was designed to be straightforward and with minimal abstractions.

You can write new neural network layers in Python using the torch API or your favorite NumPy-based libraries such as SciPy.

If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate. No wrapper code needs to be written. You can see a tutorial here and an example here.

Installation

Binaries

Commands to install binaries via Conda or pip wheels are on our website: https://pytorch.org/get-started/locally/

NVIDIA Jetson Platforms

Python wheels for NVIDIA's Jetson Nano, Jetson TX1/TX2, Jetson Xavier NX/AGX, and Jetson AGX Orin are provided here and the L4T container is published here

They require JetPack 4.2 and above, and @dusty-nv and @ptrblck are maintaining them.

From Source

Prerequisites

If you are installing from source, you will need:

  • Python 3.8 or later (for Linux, Python 3.8.1+ is needed)
  • A compiler that fully supports C++17, such as clang or gcc (gcc 9.4.0 or newer is required)

We highly recommend installing an Anaconda environment. You will get a high-quality BLAS library (MKL) and you get controlled dependency versions regardless of your Linux distro.

If you want to compile with CUDA support, select a supported version of CUDA from our support matrix, then install the following:

Note: You could refer to the cuDNN Support Matrix for cuDNN versions with the various supported CUDA, CUDA driver and NVIDIA hardware

If you want to disable CUDA support, export the environment variable USE_CUDA=0. Other potentially useful environment variables may be found in setup.py.

If you are building for NVIDIA's Jetson platforms (Jetson Nano, TX1, TX2, AGX Xavier), Instructions to install PyTorch for Jetson Nano are available here

If you want to compile with ROCm support, install

  • AMD ROCm 4.0 and above installation
  • ROCm is currently supported only for Linux systems.

If you want to disable ROCm support, export the environment variable USE_ROCM=0. Other potentially useful environment variables may be found in setup.py.

Install Dependencies

Common

conda install cmake ninja
# Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section below
pip install -r requirements.txt

On Linux

conda install intel::mkl-static intel::mkl-include
# CUDA only: Add LAPACK support for the GPU if needed
conda install -c pytorch magma-cuda110  # or the magma-cuda* that matches your CUDA version from https://anaconda.org/pytorch/repo

# (optional) If using torch.compile with inductor/triton, install the matching version of triton
# Run from the pytorch directory after cloning
make triton

On MacOS

# Add this package on intel x86 processor machines only
conda install intel::mkl-static intel::mkl-include
# Add these packages if torch.distributed is needed
conda install pkg-config libuv

On Windows

conda install intel::mkl-static intel::mkl-include
# Add these packages if torch.distributed is needed.
# Distributed package support on Windows is a prototype feature and is subject to changes.
conda install -c conda-forge libuv=1.39

Get the PyTorch Source

git clone --recursive https://github.com/pytorch/pytorch
cd pytorch
# if you are updating an existing checkout
git submodule sync
git submodule update --init --recursive

Install PyTorch

On Linux

If you would like to compile PyTorch with new C++ ABI enabled, then first run this command:

export _GLIBCXX_USE_CXX11_ABI=1

If you're compiling for AMD ROCm then first run this command:

# Only run this if you're compiling for ROCm
python tools/amd_build/build_amd.py

Install PyTorch

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
python setup.py develop

Aside: If you are using Anaconda, you may experience an error caused by the linker:

build/temp.linux-x86_64-3.7/torch/csrc/stub.o: file not recognized: file format not recognized
collect2: error: ld returned 1 exit status
error: command 'g++' failed with exit status 1

This is caused by ld from the Conda environment shadowing the system ld. You should use a newer version of Python that fixes this issue. The recommended Python version is 3.8.1+.

On macOS

python3 setup.py develop

On Windows

Choose Correct Visual Studio Version.

PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise, Professional, or Community Editions. You can also install the build tools from https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools do not come with Visual Studio Code by default.

If you want to build legacy python code, please refer to Building on legacy code and CUDA

CPU-only builds

In this mode PyTorch computations will run on your CPU, not your GPU

conda activate
python setup.py develop

Note on OpenMP: The desired OpenMP implementation is Intel OpenMP (iomp). In order to link against iomp, you'll need to manually download the library and set up the building environment by tweaking CMAKE_INCLUDE_PATH and LIB. The instruction here is an example for setting up both MKL and Intel OpenMP. Without these configurations for CMake, Microsoft Visual C OpenMP runtime (vcomp) will be used.

CUDA based build

In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching

NVTX is needed to build Pytorch with CUDA. NVTX is a part of CUDA distributive, where it is called "Nsight Compute". To install it onto an already installed CUDA run CUDA installation once again and check the corresponding checkbox. Make sure that CUDA with Nsight Compute is installed after Visual Studio.

Currently, VS 2017 / 2019, and Ninja are supported as the generator of CMake. If ninja.exe is detected in PATH, then Ninja will be used as the default generator, otherwise, it will use VS 2017 / 2019.
If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain.

Additional libraries such as Magma, oneDNN, a.k.a. MKLDNN or DNNL, and Sccache are often needed. Please refer to the installation-helper to install them.

You can refer to the build_pytorch.bat script for some other environment variables configurations

cmd

:: Set the environment variables after you have downloaded and unzipped the mkl package,
:: else CMake would throw an error as `Could NOT find OpenMP`.
set CMAKE_INCLUDE_PATH={Your directory}\mkl\include
set LIB={Your directory}\mkl\lib;%LIB%

:: Read the content in the previous section carefully before you proceed.
:: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
:: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
:: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
set DISTUTILS_USE_SDK=1
for /f "usebackq tokens=*" %i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version [15^,17^) -products * -latest -property installationPath`) do call "%i\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION%

:: [Optional] If you want to override the CUDA host compiler
set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe

python setup.py develop
Adjust Build Options (Optional)

You can adjust the configuration of cmake variables optionally (without building first), by doing the following. For example, adjusting the pre-detected directories for CuDNN or BLAS can be done with such a step.

On Linux

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
python setup.py build --cmake-only
ccmake build  # or cmake-gui build

On macOS

export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py build --cmake-only
ccmake build  # or cmake-gui build

Docker Image

Using pre-built images

You can also pull a pre-built docker image from Docker Hub and run with docker v19.03+

docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest

Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g. for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you should increase shared memory size either with --ipc=host or --shm-size command line options to nvidia-docker run.

Building the image yourself

NOTE: Must be built with a docker version > 18.06

The Dockerfile is supplied to build images with CUDA 11.1 support and cuDNN v8. You can pass PYTHON_VERSION=x.y make variable to specify which Python version is to be used by Miniconda, or leave it unset to use the default.

make -f docker.Makefile
# images are tagged as docker.io/${your_docker_username}/pytorch

You can also pass the CMAKE_VARS="..." environment variable to specify additional CMake variables to be passed to CMake during the build. See setup.py for the list of available variables.

CMAKE_VARS="BUILD_CAFFE2=ON BUILD_CAFFE2_OPS=ON" make -f docker.Makefile

Building the Documentation

To build documentation in various formats, you will need Sphinx and the readthedocs theme.

cd docs/
pip install -r requirements.txt

You can then build the documentation by running make <format> from the docs/ folder. Run make to get a list of all available output formats.

If you get a katex error run npm install katex. If it persists, try npm install -g katex

Note: if you installed nodejs with a different package manager (e.g., conda) then npm will probably install a version of katex that is not compatible with your version of nodejs and doc builds will fail. A combination of versions that is known to work is [email protected] and [email protected]. To install the latter with npm you can run npm install -g [email protected]

Previous Versions

Installation instructions and binaries for previous PyTorch versions may be found on our website.

Getting Started

Three-pointers to get you started:

Resources

Communication

Releases and Contributing

Typically, PyTorch has three minor releases a year. Please let us know if you encounter a bug by filing an issue.

We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion.

If you plan to contribute new features, utility functions, or extensions to the core, please first open an issue and discuss the feature with us. Sending a PR without discussion might end up resulting in a rejected PR because we might be taking the core in a different direction than you might be aware of.

To learn more about making a contribution to Pytorch, please see our Contribution page. For more information about PyTorch releases, see Release page.

The Team

PyTorch is a community-driven project with several skillful engineers and researchers contributing to it.

PyTorch is currently maintained by Soumith Chintala, Gregory Chanan, Dmytro Dzhulgakov, Edward Yang, and Nikita Shulga with major contributions coming from hundreds of talented individuals in various forms and means. A non-exhaustive but growing list needs to mention: Trevor Killeen, Sasank Chilamkurthy, Sergey Zagoruyko, Adam Lerer, Francisco Massa, Alykhan Tejani, Luca Antiga, Alban Desmaison, Andreas Koepf, James Bradbury, Zeming Lin, Yuandong Tian, Guillaume Lample, Marat Dukhan, Natalia Gimelshein, Christian Sarofeen, Martin Raison, Edward Yang, Zachary Devito.

Note: This project is unrelated to hughperkins/pytorch with the same name. Hugh is a valuable contributor to the Torch community and has helped with many things Torch and PyTorch.

License

PyTorch has a BSD-style license, as found in the LICENSE file.

tensorrt's People

Contributors

abhi-iyer avatar andi4191 avatar apbose avatar arvindsridhar avatar bddppq avatar blchu avatar borisfom avatar bowang007 avatar chengyute avatar frank-wei avatar gcuendet-cognex avatar gs-olive avatar huydhn avatar inocsin avatar lamhoangtung avatar mengdih avatar mfeliz-cruise avatar narendasan avatar njuapp avatar p517332051 avatar peri044 avatar ruoqianguo avatar shashank3959 avatar svenchilton avatar tanayvarshney avatar vellamike avatar vinhngx avatar yoshida-ryuhei avatar zewenli98 avatar zsef123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tensorrt's Issues

Does TRTorch support bail-out mechanism?

A neural network model may have some operators which aren't supported by TensorRT.
When TensorRT cannot compile a subgraph, can the execution of the subgraph invoke torch operators again? Can a model execution mix TensorRT and vanilla torch operators?

Warning: Deprecation warning: In a future PyTorch release torch.full will no longer return tensors of floating dtype by default. Instead, a bool fill_value will return a tensor of torch.bool dtype, and an integral fill_value will return a tensor of torch.long dtype. Set the optional `dtype` or `out` arguments to suppress this warning. (operator() at ../aten/src/ATen/native/TensorFactories.cpp:361)

When I run the trt compiler with libtorch 1.5.0 build hash 4ff3872a2099993bf7e8c588f7182f3df777205b I receive the following warning Warning: Deprecation warning: In a future PyTorch release torch.full will no longer return tensors of floating dtype by default. Instead, a bool fill_value will return a tensor of torch.bool dtype, and an integral fill_value will return a tensor of torch.long dtype. Set the optional dtypeorout arguments to suppress this warning. (operator() at ../aten/src/ATen/native/TensorFactories.cpp:361). I dont think it is breaking although it should probably be addressed sooner than later.

TRTorch on Jetson Nano

Is there a build process outlined for getting this library built on a Jetson Nano or another ARM64 platform (TX2, Xavier, etc.)? The Bazel WORKSPACE seems rather dependent on X86 binaries and since I am new to Bazel I am having a hard time figuring out how to get it to build on Jetson Nano that already has TensorRT, CUDA, cuDNN, and libtorch/pytorch installed. Thanks

Solidify Arg class

There are a whole bunch of TODOs re: the Arg class

  • Implement Tag checking for the IValue unwrap functions
  • Potentially safely consolidate unwrap functions to only support valid types

Upsample Support Tracker

Use PyTorch Functionalization Pass

Having converters for inplace operators (add_) is potentially unsafe. We should use the functionalization pass in the lowering phase to switch these ops to their functional versions.

Grab dependencies automatically

We should either look at containerizing the build, or find someway to pull TensorRT, CUDA etc. with bazel. We already do this with libtorch. This should make it less likely builds will fail because of peoples environment

Fix the hack to keep the evaluator and converter implementations in the library

When compiling libtrtorch.so converters and evaluators are stripped since they are registered using self registering types and those variables have no uses. As a workaround we just include the implementation cpp files at the end of the registry cpp files to keep the symbols around. We should get rid of those includes and correctly handle the issue.

Version Bumps

With Libtorch 1.5.0 out we are going to be updating soon:

  • Libtorch 1.5.0
  • CUDA 10.2
  • cuDNN 7.6
  • TensorRT 7.0

Build Project failed with Bazel

Hi,

I configure the env and try to build such project.
INFO: Analyzed target //:libtrtorch (34 packages loaded, 1830 targets configured).
INFO: Found 1 target...
INFO: Deleting stale sandbox base /home/xxx/.cache/bazel/_bazel_xxx/2ed6247d0d5238dab6f58f41a8e8ad4b/sandbox
ERROR: missing input file 'external/tensorrt/lib/x86_64-linux-gnu/libnvinfer.so', owner: '@tensorrt//:lib/x86_64-linux-gnu/libnvinfer.so'
ERROR: /home/xxx/2ed6247d0d5238dab6f58f41a8e8ad4b/external/tensorrt/BUILD.bazel:15:1: @tensorrt//:nvinfer_lib: missing input file '@tensorrt//:lib/x86_64-linux-gnu/libnvinfer.so'
Target //:libtrtorch failed to build
Use --verbose_failures to see the command lines of failed build steps.
ERROR: /home/xxx/.cache/bazel/_bazel_xxxd5238dab6f58f41a8e8ad4b/external/tensorrt/BUILD.bazel:15:1 1 input file(s) do not exist
INFO: Elapsed time: 2.964s, Critical Path: 0.13s
INFO: 0 processes.
FAILED: Build did NOT complete successfully

could you help solve such errors or provide more env setting details?
I have email @narendasan and please check it.
Thanks.

Setup a manylinux system for Python builds

We need to create a system that lets us build Python manylinux builds instead of just supporting Ubuntu 18.04. This will probably be a Docker system like used in DALI

Conv/Deconv/ConvTranspose Support Tracker

Support Tuple Inputs

Hello. I am working with a model that takes in a tuple of inputs of different sizes. Is there a way to handle this within the existing TRTorch framework? I am attempting to compile the model with the following settings but get the accompanied error. I am running form source version on commit 247c748.

Compile settings:

compile_settings = {
    "input_shapes": [
        {
            "min": ([1, 3, 180, 320], [1,49,2]),
            "opt": ([1, 3, 180, 320], [1,49,2]),
            "max": ([1, 3, 180, 320], [1,49,2])
        }, # For static size [1, 3, 224, 224]
    ],
#     "op_precision": torch.half # Run with FP16
}

Error:

TypeError: (): incompatible function arguments. The following argument types are supported:
    1. (self: trtorch._C.InputRange, arg0: List[int]) -> None

Invoked with: <trtorch._C.InputRange object at 0x7fda486f67b0>, ([1, 3, 180, 320], [1, 49, 2])

The forward function of my model is the following:

    def forward(self,x,seq):
        
        x = self.input_conv(x)
        x = self.input_fc(x).unsqueeze(0)
        
        actions = self.action_fc(seq)
        x, hidden = self.lstm(actions, (x, x))
        
        output = self.output_fc(x)
        
        return output

Thanks

Start to handle branching in simple cases

The system works pretty well for traced models, but not much work has been done with torch script models that have branching. I noticed some common cases that we should be able to handle include branching for none arguments such as graphs like this:

  %50 : Function = prim::Constant[name="linear"]()
  %53 : bool = prim::Constant[value=0]() # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:7
  %54 : None = prim::Constant() # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:40
  %55 : int = prim::Constant[value=2]() # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:22
  %56 : int = prim::Constant[value=1]() # :0:0
  %57 : int = aten::dim(%input1.1) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:7
  %58 : bool = aten::eq(%57, %55) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:7
  %59 : bool = prim::If(%58) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:7
    block0():
      %60 : bool = aten::__isnot__(%94, %54) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:28
      -> (%60)
    block1():
      -> (%53)
  %input2.1 : Tensor = prim::If(%59) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1368:4
    block0():
      %bias0.4 : Tensor = prim::unchecked_cast(%94)
      %101 : Tensor = aten::linear(%input1.1, %95, %bias0.4)
      -> (%101)
    block1():
      %106 : Tensor? = prim::Constant()
      %107 : Tensor = aten::linear(%input1.1, %95, %106)
      %67 : bool = aten::__isnot__(%94, %54) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1373:11
      %output0.6 : Tensor = prim::If(%67) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1373:8
        block0():
          %bias1.4 : Tensor = prim::unchecked_cast(%94)
          %output0.7 : Tensor = aten::add_(%107, %bias1.4, %56) # /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py:1374:12
          -> (%output0.7)
        block1():
          -> (%107)
      -> (%output0.6)

Verify that engine runs in the correct stream

This is the stream that is used right now
c10::cuda::CUDAStream stream = c10::cuda::getCurrentCUDAStream(inputs[0].device().index());

Will this always be correct? What are the cases where this will give an incorrect stream?

How to use local pytorch instead of installing again.

Hi Naren,
glad to see that you check-in py binding and test.
TRTorch needs to install pytorch and torchvision again and I know it is easy to build trt from scratch.
But as a developer, I always build and set pytorch env locally and do need to install it again. Could you help provide options to call local pytorch instead of installing again. @narendasan

Thanks,
Alan

Add Support for TupleConstruct

I am running TRTorch V0.0.2 and trying to compile the resnet18 version of the model presented here https://github.com/NVIDIA-AI-IOT/trt_pose in C++. When I try to compile the graph in C++ I get the following error (note that if I try to compile in python there is no error and the kernel dies):

ERROR: [TRTorch Conversion Context] - %input.8 : Tensor = aten::_convolution(%218, %self.1.cmap_up.0.weight, %self.1.cmap_up.0.bias, %7, %5, %5, %11, %4, %8, %10, %10, %11) # /home/michael/anaconda3/envs/nvidia_dl/lib/python3.7/site-packages/torch/nn/modules/conv.py:790:0: kernel weights has count 2097152 but 4194304 was expected
ERROR: [TRTorch Conversion Context] - %input.8 : Tensor = aten::_convolution(%218, %self.1.cmap_up.0.weight, %self.1.cmap_up.0.bias, %7, %5, %5, %11, %4, %8, %10, %10, %11) # /home/michael/anaconda3/envs/nvidia_dl/lib/python3.7/site-packages/torch/nn/modules/conv.py:790:0: count of 2097152 weights in kernel, but kernel dimensions (4,4) with 512 input channels, 512 output channels and 1 groups were specified. Expected Weights count is 512 * 4*4 * 512 / 1 = 4194304
ERROR: [TRTorch Conversion Context] - %input.8 : Tensor = aten::_convolution(%218, %self.1.cmap_up.0.weight, %self.1.cmap_up.0.bias, %7, %5, %5, %11, %4, %8, %10, %10, %11) # /home/michael/anaconda3/envs/nvidia_dl/lib/python3.7/site-packages/torch/nn/modules/conv.py:790:0: kernel weights has count 2097152 but 4194304 was expected
ERROR: [TRTorch Conversion Context] - %input.8 : Tensor = aten::_convolution(%218, %self.1.cmap_up.0.weight, %self.1.cmap_up.0.bias, %7, %5, %5, %11, %4, %8, %10, %10, %11) # /home/michael/anaconda3/envs/nvidia_dl/lib/python3.7/site-packages/torch/nn/modules/conv.py:790:0: count of 2097152 weights in kernel, but kernel dimensions (4,4) with 512 input channels, 512 output channels and 1 groups were specified. Expected Weights count is 512 * 4*4 * 512 / 1 = 4194304

If I add in the line trtorch::CheckMethodOperatorSupport(script_model, "forward"); just before compiling I get the error

terminate called after throwing an instance of 'trtorch::Error'
  what():  [enforce fail at core/conversion/conversion.cpp:240] Expected schema to be true but got false
Unable to get schema for Node %245 : (Tensor, Tensor) = prim::TupleConstruct(%242, %244) (conversion.VerifyCoverterSupportForBlock

So I think this is expected behavior for a converter not being found but I am not entirely sure. If it is a converter missing it looks like it is related to handling the TupleConstruct since the model returns a tuple. Another model that I have tested and that just returns a tensor works fine. Are there any plans to get support for this implemented and is it as straight forward as adding another converter?

Pooling Support Tracker

Create a supportable graph API

Right now as if a graph is not supported, it will still run through the converters until it hits an unsupported op. We should have a light weight way to determine support and what ops need to be implemented to support the graph.

RFC: How should engines be integrated into the JIT Interpreter?

Right now as a side effect of registering an engine in the execution manager, a new op specifically for the engine is registered in the op registry. For instance running a ResNet backbone will be implemented with a new op with schema trt::execute_engine_55d1de7b7b50(Tensor in_input_38) -> (Tensor). We could also have a generic op like trt::execute_engine(int id, Tensor in_input_38, ...) -> (Tensor, ...) and rely on information in the engine manager to run the correct engine, as long as variadic arguments (and returns) work.

trtorchexec: error loading the model

I have a test model traced by below:

from torchvision.models.alexnet import alexnet
import torch

model = alexnet(pretrained=True).eval().cuda()
x = torch.ones((1, 3, 224, 224)).cuda()

traced_model = torch.jit.trace(model, x)
traced_model.save("alexnet.pt")

then I use trtorchexec, error occur:

error loading the model
open file failed, file path: ../../../../../data/alexnet.pt (FileAdapter at ../../caffe2/serialize/file_adapter.cc:11)
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x6a (0x7f21e5ae192a in /trtorch/bin/TRTorch/bazel-TRTorch/external/libtorch/lib/libc10.so)
frame #1: caffe2::serialize::FileAdapter::FileAdapter(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x2fa (0x7f21eb536b1a in /trtorch/bin/TRTorch/bazel-TRTorch/external/libtorch/lib/libtorch.so)
frame #2: torch::jit::load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, c10::optional<c10::Device>, std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&) + 0x40 (0x7f21ec811c70 in /trtorch/bin/TRTorch/bazel-TRTorch/external/libtorch/lib/libtorch.so)
frame #3: ./trtorchexec() [0x411bd4]
frame #4: __libc_start_main + 0xf0 (0x7f21be3ce830 in /lib/x86_64-linux-gnu/libc.so.6)
frame #5: ./trtorchexec() [0x410459]

my torch version is:

>>> import torch
>>> torch.__version__
'1.4.0'
>>> torch.version.cuda
'10.1'
>>> 

my libtorch use trtorch default libtorch.

How can I solve it?

Implement BatchNorm as a lowering pass

Right now there are a couple ways that batch norm is handled, there will be a folding pass, that merges applicable Conv2D -> BatchNorm patterns, there is a convertor that acts as a fallback. It would be nice if we could move that converter to be a lowering pass that synthesizes a subgraph of lower level op converters instead of having a large batch norm specific one. Some of the work is done in the unused unpack_batch_norm pass but it needs to be firmed up to support multiple dimensions.

Activation Support Tracker

Dynamic shape is mishandled by `aten::adaptive_avg_pooling2d` converter

DEBUG: [TRTorch - Debug Build] - Stride: [-1, -1]
DEBUG: [TRTorch - Debug Build] - Window: [-1, -1]
ERROR: [TRTorch Conversion Context] - Parameter check failed at: ../builder/Network.cpp::addPoolingNd::690, condition: allDimsGtEq(windowSize, 1) && volume(windowSize) < MAX_KERNEL_DIMS_PRODUCT
terminate called after throwing an instance of 'trtorch::Error'
  what():  [enforce fail at core/conversion/converters/impl/pooling.cpp:92] Expected new_layer to be true but got false
Unable to create average pooling layer from node: %x.1 : Tensor = aten::adaptive_avg_pool2d(%447, %6) # /home/narens/.local/lib/python3.6/site-packages/torch/nn/functional.py:889:0

Because the output size is calculated based on the input size and target output size, you get incorrect stride and window when using dynamic shape. Hopefully will get fixed with the work done on generating shape tensors

TRTorch with CUDA 10.0

Hi,

I tried installing TRTorch on my Ubuntu 16.04, PyTorch 1.5 compiled from source, CUDA 10.0, CUDNN 7.6.

I am getting a symbol error in all configurations I tried. I am grateful for any help.

seh2bp@trtorch:/workspace$ python -c "import torch; import trtorch" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/lib/python3.7/site-packages/torch/__init__.py", line 165, in <module> from torch._C import * ImportError: /opt/conda/lib/python3.7/site-packages/torch/lib/libshm.so: undefined symbol: _Z8_THErrorPKciS0_z

ldd output is here:

seh2bp@trtorch:/workspace$ ldd /opt/conda/lib/python3.7/site-packages/trtorch/lib/libtrtorch.so linux-vdso.so.1 (0x00007ffdff3c7000) libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f338cc4d000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f338c8af000) libnvinfer.so.7 => /opt/tensorrt/TensorRT-7.0.0.11/lib/libnvinfer.so.7 (0x00007f337ec34000) libcublas.so.10.0 => /usr/local/cuda-10.0/targets/x86_64-linux/lib/libcublas.so.10.0 (0x00007f337a69e000) libcudnn.so.7 => /usr/lib/x86_64-linux-gnu/libcudnn.so.7 (0x00007f3362e8d000) libtorch.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libtorch.so (0x00007f3362c8b000) libtorch_cuda.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libtorch_cuda.so (0x00007f33211cc000) libtorch_cpu.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libtorch_cpu.so (0x00007f3311fae000) libtorch_global_deps.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libtorch_global_deps.so (0x00007f3311da9000) libc10_cuda.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libc10_cuda.so (0x00007f3311b73000) libc10.so => /workspace/scer-docker/trtorch/files/libtorch/lib/libc10.so (0x00007f3311923000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f331170b000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f331131a000) /lib64/ld-linux-x86-64.so.2 (0x00007f338cfd6000) libcudart.so.10.0 => /usr/local/cuda-10.0/targets/x86_64-linux/lib/libcudart.so.10.0 (0x00007f33110a0000) libmyelin.so.1 => /opt/tensorrt/TensorRT-7.0.0.11/lib/libmyelin.so.1 (0x00007f331088f000) libnvrtc.so.10.0 => /usr/local/cuda-10.0/targets/x86_64-linux/lib/libnvrtc.so.10.0 (0x00007f330f273000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f330f06f000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f330ee50000) librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f330ec48000) libcudart-80664282.so.10.2 => /workspace/scer-docker/trtorch/files/libtorch/lib/libcudart-80664282.so.10.2 (0x00007f330e9c7000) libnvToolsExt-3965bdd0.so.1 => /workspace/scer-docker/trtorch/files/libtorch/lib/libnvToolsExt-3965bdd0.so.1 (0x00007f330e7bd000) libgomp-75eea7e8.so.1 => /workspace/scer-docker/trtorch/files/libtorch/lib/libgomp-75eea7e8.so.1 (0x00007f330e598000)

I tried different configurations:

  • use the downloaded libtorch built for cuda 10.2, I get the same error as above
  • use the installed libtorch (for a reason I don't understand I have 2 versions on in
    .../site-packages/torch and one in .../site-packages/torch-1.5.0-py3.7-linux-x86_64.egg/torch. Build with .../site-packages/torch fails because it is missing optimizer.h. I will not give further detail as I believe it will just complicate the issue unnecessarily. Any help is welcome.

What the advantages of TRTorch?

I used to use torch2trt to convert pytorch module, could you explain the advatage over torch2trt?

If the model contain op that tensorrt don't support, can trtorch convert it to engine?
Otherwise run the op supported by tensorrt with tensorrt, and other use libtorch?

I really appreciate for your great works, if you can answer my doubts, I will be very grateful.

RFC: Converter API

Right now the Converter API expects lambdas of the type: (ConversionCtx* ctx, torch::jit::Node* n, kwargs* args) -> bool

Questions:

  1. The bool return is a quick way to signal success or failure in converting the op. This could be something more descriptive

  2. Right now it is the responsibility of converters to log associations between torch::jit::Values and nvinfer1::ITensorss so that later is significantly easier to assemble the arguments to a node. It may be nice if you could return a vector of unions of IValues and ITensors and have the converter executor do the insertions. This would probably need to rely on some guarantee that order of return is easy to determine and constant

TRTorch documentation site

Right now the main documentation is the comments in the header file. We should probably have a static site for reference and some short tutorials

Look to support broadcasting comparisons for Dims

It would be nice if we can support in bool operator==(const nvinfer1::Dims& in1, const nvinfer1::Dims& in2) to return true if we can safely broadcast / reshape between the two Dims (or maybe this should be another function)

Implement a call function for the TRTEngine custom class

Right now you need to use the trt::execute_engine op to run a TensorRT engine. Being able to run the engine class like a module may be nice. Code is stubbed out but need to find the right interface class for the function.

Create a lightweight runtime library

Now that serialization works, in deployment scenarios with limited resources, it would be nice to have a reduced size library which can run TRTorch modules. All that should be required is the execution section of the core library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.