Skip to content

Add TensorRT Support to master branch (from #14) #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Nov 23, 2022
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ estimation, loads the pre-trained weights, and make human predictions on a singl
- Support for multi-GPU inference.
- Multi-person support by design (HigherHRNet is a bottom-up approach).
- A reference code that runs a live demo reading frames from a webcam or a video file.
- **NEW** Support for TensorRT (thanks to [@gpastal24](https://github.com/gpastal24), see [#14](https://github.com/stefanopini/simple-HigherHRNet/pull/14) and [#15](https://github.com/stefanopini/simple-HigherHRNet/pull/15)).
- **NEW** A [Jupyter Notebook](https://github.com/stefanopini/simple-HigherHRNet/blob/master/colab_notebook.ipynb) compatible with Google Colab showcasing how to use this repository.

This repository is built along the lines of the repository
[*simple-HRNet*](https://github.com/stefanopini/simple-HRNet).
Expand Down Expand Up @@ -110,6 +112,24 @@ For help:
python scripts/extract-keypoints.py --help
```

### Converting the model to TensorRT:

Warning: require the installation of TensorRT (see Nvidia website) and onnx.
On some platforms, they can be installed with
```
pip install tensorrt onnx
```

Converting in FP16:
```
python scripts/export-tensorrt-model.py --device 0 --half
```

For help:
```
python scripts/export-tensorrt-model.py --help
```

### Installation instructions

- Clone the repository
Expand Down Expand Up @@ -143,3 +163,5 @@ python scripts/extract-keypoints.py --help
- [ ] Optimize the post-processing steps
- [ ] Add COCO dataset and evaluation
- [ ] Add Train/Test scripts
- [x] Add TensorRT support
- [x] Add notebook compatible with Colab
60 changes: 36 additions & 24 deletions SimpleHigherHRNet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

from models.higherhrnet import HigherHRNet
from misc.HeatmapParser import HeatmapParser
from misc.utils import get_multi_scale_size, resize_align_multi_scale, get_multi_stage_outputs, aggregate_results, get_final_preds, bbox_iou
from misc.utils import (get_multi_scale_size, resize_align_multi_scale, get_multi_stage_outputs, aggregate_results,
get_final_preds)


class SimpleHigherHRNet:
Expand All @@ -30,7 +31,8 @@ def __init__(self,
filter_redundant_poses=True,
max_nof_people=30,
max_batch_size=32,
device=torch.device("cpu")):
device=torch.device("cpu"),
enable_tensorrt=False):
"""
Initializes a new SimpleHigherHRNet object.
HigherHRNet is initialized on the torch.device("device") and
Expand Down Expand Up @@ -60,6 +62,9 @@ def __init__(self,
Default: 16
device (:class:`torch.device` or str): the higherhrnet (and yolo) inference will be run on this device.
Default: torch.device("cpu")
enable_tensorrt (bool): Enables tensorrt inference for HigherHRnet.
If enabled, a `.engine` file is expected as `checkpoint_path`.
Default: False
"""

self.c = c
Expand All @@ -74,6 +79,7 @@ def __init__(self,
self.max_nof_people = max_nof_people
self.max_batch_size = max_batch_size
self.device = device
self.enable_tensorrt = enable_tensorrt

# assert nof_joints in (14, 15, 17)
if self.nof_joints == 14:
Expand All @@ -90,33 +96,39 @@ def __init__(self,
else:
raise ValueError('Wrong model name.')

checkpoint = torch.load(checkpoint_path, map_location=self.device)
if 'model' in checkpoint:
checkpoint = checkpoint['model']
# fix issue with official high-resolution weights
checkpoint = OrderedDict([(k[2:] if k[:2] == '1.' else k, v) for k, v in checkpoint.items()])
self.model.load_state_dict(checkpoint)
if not self.enable_tensorrt:
checkpoint = torch.load(checkpoint_path, map_location=self.device)
if 'model' in checkpoint:
checkpoint = checkpoint['model']
# fix issue with official high-resolution weights
checkpoint = OrderedDict([(k[2:] if k[:2] == '1.' else k, v) for k, v in checkpoint.items()])
self.model.load_state_dict(checkpoint)
if 'cuda' in str(self.device):
print("device: 'cuda' - ", end="")

if 'cuda' == str(self.device):
# if device is set to 'cuda', all available GPUs will be used
print("%d GPU(s) will be used" % torch.cuda.device_count())
device_ids = None
else:
# if device is set to 'cuda:IDS', only that/those device(s) will be used
print("GPU(s) '%s' will be used" % str(self.device))
device_ids = [int(x) for x in str(self.device)[5:].split(',')]

if 'cuda' in str(self.device):
print("device: 'cuda' - ", end="")
self.model = torch.nn.DataParallel(self.model, device_ids=device_ids)

if 'cuda' == str(self.device):
# if device is set to 'cuda', all available GPUs will be used
print("%d GPU(s) will be used" % torch.cuda.device_count())
device_ids = None
elif 'cpu' == str(self.device):
print("device: 'cpu'")
else:
# if device is set to 'cuda:IDS', only that/those device(s) will be used
print("GPU(s) '%s' will be used" % str(self.device))
device_ids = [int(x) for x in str(self.device)[5:].split(',')]
raise ValueError('Wrong device name.')

self.model = torch.nn.DataParallel(self.model, device_ids=device_ids)
elif 'cpu' == str(self.device):
print("device: 'cpu'")
self.model = self.model.to(device)
self.model.eval()
else:
raise ValueError('Wrong device name.')

self.model = self.model.to(device)
self.model.eval()
if device.type == 'cpu':
raise ValueError('TensorRT does not support cpu device.')
from misc.tensorrt_utils import TRTModule_HigherHRNet
self.model = TRTModule_HigherHRNet(path=checkpoint_path, device=self.device)

self.output_parser = HeatmapParser(num_joints=self.nof_joints,
joint_set=self.joint_set,
Expand Down
Loading