Skip to content

About

ResNet-50 served via TensorRT FP16 + C++ Crow HTTP server. 3.55x FPS, 4.3x P99 latency reduction, zero accuracy loss vs PyTorch baseline.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

TensorRT Vision Server

Production-style C++/TensorRT inference server for ResNet-50 (CIFAR-10), with a Python training/export pipeline, HTTP API, client, and benchmarking suite. Built and tested on WSL2 Ubuntu 24.04, CUDA 12.4, TensorRT 11.0, and an RTX 3060 Laptop GPU (6 GB).

Architecture

┌──────────────┐     HTTP POST       ┌─────────────────────────────────────┐
│ client.py    │ ──────────────────► │  Crow C++ Server (main.cpp)         │
│ benchmark.py │   multipart/image   │  ┌────────────┐   ┌───────────────┐ │
└──────────────┘                     │  │ preprocess │──►│  TRTEngine    │ │
                                     │  │  (224×224) │   │ enqueueV3()   │ │
                                     │  └────────────┘   │ setTensorAddr │ │
                                     │                   └───────┬───────┘ │
                                     │  GET /health /metrics         │     │
                                     └───────────────────────────────┼─────┘
                                                                     ▼
                                                          model/resnet50.engine
                                                                     ▲
                                     ┌───────────────────────────────┴─────┐
                                     │  model/quantize.py                  │
                                     │  ORT QDQ quant → TRT engine build   │
                                     │  (FP16 fallback on TRT 11)          │
                                     └───────────────────────────────▲─────┘
                                                                     │
                                     ┌───────────────────────────────┴─────┐
                                     │  model/export.py                    │
                                     │  Fine-tune ResNet-50 → ONNX         │
                                     └─────────────────────────────────────┘

Hardware & Software

Component Requirement
GPU NVIDIA CUDA-capable GPU (6 GB+ VRAM recommended)
OS WSL2 Ubuntu 24.04 (or native Linux)
CUDA 12.4 (/usr/local/cuda-12.4)
TensorRT 11.0 — pip install tensorrt-cu12 (not default tensorrt, which pulls CUDA 13)
Python 3.12 venv recommended (~/tensorrt-env)
Compiler GCC 13+, CMake 3.18+
Crow Header-only HTTP library at /usr/local/include/crow

Quickstart

# Enter project (WSL)
cd /mnt/c/Users/prohi/OneDrive/Documents/Desktop/ml-engineering/tensorRT/tensorrt-vision-server

# Activate Python env
source ~/tensorrt-env/bin/activate

# Install Python deps (uses tensorrt-cu12 for CUDA 12.4)
pip install -r requirements.txt

# One-time full pipeline (train, export, engine, compile server)
chmod +x setup.sh scripts/run_server.sh
./setup.sh

If artifacts already exist, rebuild only what you need:

source ~/tensorrt-env/bin/activate

# Engine (FP16, or auto: try INT8 QDQ then fall back to FP16)
python model/quantize.py --precision fp16

# C++ server — activate venv first so CMake finds pip tensorrt_libs
cd build && cmake .. && make -j$(nproc) && cd ..

Run the server

From the project root:

./build/trt_server
# or
./scripts/run_server.sh

Server binds to 0.0.0.0:8080 but you must connect via:

  • http://127.0.0.1:8080/health
  • http://localhost:8080/health

(0.0.0.0 is invalid in browsers.)

Test & benchmark

# New terminal — same cd + source activate
curl http://127.0.0.1:8080/health
python client/client.py --image model/calibration_data/calib_000.jpg

# Server must stay running
python benchmark/benchmark.py

API

POST /predict

Multipart form field: image (JPEG/PNG).

{
  "class_id": 6,
  "confidence": 0.61,
  "latency_ms": 25.65
}

GET /health

{"status": "ok", "model": "resnet50"}

GET /metrics

{
  "requests_total": 128,
  "avg_latency_ms": 5.12,
  "p99_latency_ms": 8.44
}

POST /predict_raw

Binary body: 150528 float32 values in CHW order (1 × 3 × 224 × 224, ImageNet-normalized). Skips JPEG decode and preprocessing — calls engine.infer() directly. latency_ms in the response is pure TRT inference time only (no HTTP, no data transfer).

Used by benchmark/benchmark.py so that both sides time the same operation: model forward pass on an already-preprocessed input tensor.

{
  "class_id": 6,
  "confidence": 0.61,
  "latency_ms": 2.84
}

GET /memory

Returns server PID, engine file size, and the GPU memory delta measured across the TRT engine constructor at startup. Used by the benchmark to identify the server process for NVML per-process memory isolation.

{
  "server_pid": 12345,
  "engine_file_mb": 90.26,
  "engine_memory_delta_mb": 287.4
}

class_id is 0–9 (CIFAR-10: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck).

Engine build (model/quantize.py)

Mode Command Output
FP16 (recommended on TRT 11) python model/quantize.py --precision fp16 model/resnet50_fp16.engine + model/resnet50.engine
Auto python model/quantize.py Tries INT8 Q/DQ ONNX → engine; falls back to FP16 if build fails
INT8 only python model/quantize.py --precision int8 Fails on TRT 11 for this ResNet graph (conv tactic error)

Pipeline details:

  1. export.py — fine-tune ResNet-50 on CIFAR-10 for 1 epoch (ImageNet pretrained weights; one epoch is sufficient to adapt the classifier head under transfer learning; keeps setup time under 10 minutes), save resnet50.pth, export resnet50.onnx.
  2. quantize.py — ONNX Runtime static INT8 Q/DQ calibration (100 images in calibration_data/), then TensorRT build_serialized_network().
  3. Default server engine: model/resnet50.engine (copy of the built engine).

INT8 Q/DQ ONNX is generated for experimentation; on TensorRT 11 + this model, the TRT build currently succeeds only for FP16.

Benchmark Results

Measured on RTX 3060 Laptop GPU (6 GB VRAM), WSL2 Ubuntu 24.04, CUDA 12.4, TensorRT 11.0. 100 random 224×224 images (seed 42).

FPS and latency measure pure model inference — preprocessing (resize, normalize) is excluded from both sides. Both backends receive the same preprocessed float32 tensor. TensorRT latency is the engine.infer() time reported by the server via POST /predict_raw, not the HTTP round-trip.

Metric PyTorch Baseline TensorRT FP16
FPS [2] 97.64 347.12
P50 Latency 8.59 ms 2.60 ms
P99 Latency 21.44 ms 4.94 ms
GPU Memory [1] 158.7 MB 108.0 MB
Model Size 90.06 MB 90.26 MB

[1] Memory methodology:

  • PyTorch: torch.cuda.max_memory_allocated() after model.to(device) + one forward pass — FP32 model weights + peak activation memory. Excludes CUDA runtime context overhead (~150 MB).
  • TensorRT: cudaMemGetInfo() delta across the engine constructor (free_before − free_after). The first cudaMemGetInfo call initialises the CUDA context, so the delta captures only the engine-specific allocation: FP16 weights + TRT workspace + I/O buffers. Context overhead is excluded on both sides for a symmetric comparison. On WSL2 NVML per-process memory is unavailable; this delta is the next-best device-side proxy.

[2] FPS = N / Σ(per-image inference latency). Both sides computed the same way from pure inference times.

Artifacts:

  • benchmark/results.json
  • benchmark/plots/fps_comparison.png
  • benchmark/plots/latency_distribution.png
  • benchmark/plots/memory_comparison.png

Accuracy vs Speed Trade-off

Evaluated on the full CIFAR-10 test set (10,000 images). Both models receive identical preprocessed float32 tensors; logit delta measures only precision/kernel differences, not preprocessing variation. Run python model/evaluate.py (server must be running) to reproduce.

Metric PyTorch FP32 TensorRT FP16
Top-1 Accuracy 95.02% 95.03%
Accuracy Delta — +0.01%
Max Logit Delta — 0.1229
Avg Logit Delta — 0.0060

Evaluated on 10,000 CIFAR-10 test images. See benchmark/accuracy_results.json for raw data.

Why FP16 accuracy is acceptable: The +0.01% delta is within measurement noise — TRT FP16 produces effectively the same predictions as FP32. The average per-logit difference is 0.006, negligible relative to the logit range for a 10-class softmax. FP16 on Ampere Tensor Cores does not introduce the numerical instability risk that FP16 training does; inference only multiplies fixed weights by activations, so the mantissa loss is bounded and benign. See docs/adr/0001-fp16-over-int8.md for the full decision record.

Known Measurement Caveats

  • PyTorch memory excludes CUDA runtime context overhead (~150 MB). torch.cuda.max_memory_allocated() only tracks allocations made through the PyTorch caching allocator. The CUDA driver context that the Python process holds is not counted.
  • TensorRT memory source depends on platform. On bare-metal Linux, NVML nvmlDeviceGetComputeRunningProcesses() returns per-process usedGpuMemory (process-isolated; includes CUDA context + engine + buffers). On WSL2, usedGpuMemory is None because the hypervisor virtualises the GPU — the benchmark automatically falls back to engine_memory_delta_mb (cudaMemGetInfo free-before minus free-after across the engine constructor), which is the next-best device-side proxy.
  • Raw model size on disk: PyTorch .pth 90.06 MB vs TRT .engine 90.26 MB. The engine is FP16 (half-precision weights) but similar size because TensorRT adds layer fusion metadata, calibration data, and tactic selection tables.
  • Latency numbers use 100-sample P99. The top-1 value of 100 samples is a statistically weak P99 estimate; treat it as an indicative upper bound, not a precise tail latency.

Known Simplifications

  • Latency ring buffer capped at 10,000 samples. GET /metrics P99 is computed from the first 10,000 requests; new observations are silently dropped after the cap. Production systems would use Welford's online algorithm for running mean and reservoir sampling or t-digest for approximate percentiles without memory growth. See docs/adr/0002-latency-ring-buffer.md.
  • Training reproducibility seeded at 42. model/export.py sets torch, numpy, and random seeds plus cudnn.deterministic = True before training. DataLoader shuffle uses a fixed Generator. GPU non-determinism (some CUDA kernels are stochastic) means results may still differ across hardware or driver versions.

Why TensorRT?

TensorRT fuses layers, picks GPU kernels, and serializes a plan into a .engine file. Compared to eager PyTorch inference, you typically get:

  • Higher throughput and lower latency
  • Lower GPU memory during inference
  • Stable production serving via a small C++ binary and HTTP API

This project uses FP16 engines on TensorRT 11 (INT8 implicit calibration was removed in TRT 11; Q/DQ ONNX for this ResNet still hits builder limitations).

Project Layout

tensorrt-vision-server/
├── CMakeLists.txt          # Links pip tensorrt_libs via RPATH when venv is active at configure time
├── requirements.txt
├── setup.sh
├── scripts/
│   └── run_server.sh       # Sets LD_LIBRARY_PATH + default engine path
├── model/
│   ├── export.py
│   ├── quantize.py
│   ├── resnet50.engine     # Default server engine (FP16)
│   └── calibration_data/
├── server/
│   ├── main.cpp
│   ├── trt_engine.hpp / trt_engine.cpp
│   ├── preprocess.hpp
│   └── stb_image_impl.cpp
├── benchmark/
│   └── benchmark.py
├── client/
│   └── client.py
└── build/
    └── trt_server

Environment Variables

Variable Default Description
TRT_ENGINE_PATH model/resnet50.engine Path to serialized TensorRT engine

Troubleshooting

Symptom Fix
CUDA initialization failure with error: 35 in Python Install tensorrt-cu12, not default tensorrt (CUDA 13).
Same error in ./build/trt_server Rebuild with venv active: source ~/tensorrt-env/bin/activate && cd build && cmake .. && make. CMake must embed RPATH to tensorrt_libs.
Failed to open engine file: resnet50_int8.engine Rebuild server (cmake .. && make) or run python model/quantize.py --precision fp16.
Browser ERR_ADDRESS_INVALID on 0.0.0.0:8080 Use http://localhost:8080/health.
Slow training on OneDrive path Copy repo to ~/tensorrt-vision-server for faster I/O.

Notes

  • C++ server uses enqueueV3() and setTensorAddress() (TensorRT 10+/11 API).
  • Inference is mutex-protected for safe concurrent HTTP requests.
  • Calibration images for ORT quantization are downloaded by setup.sh into model/calibration_data/.

About

ResNet-50 served via TensorRT FP16 + C++ Crow HTTP server. 3.55x FPS, 4.3x P99 latency reduction, zero accuracy loss vs PyTorch baseline.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages