Model Conversion Workflow from Hugging Face to TensorRT Checkpoints
TensorRT-LLM requires models to be converted from Hugging Face format into a TensorRT-specific checkpoint before engine building. For Meta's Llama 3.1 8B Instruct, begin by cloning the TensorRT-LLM repository at the v0.12.0 release tag, which supports Llama 3.1 native RoPE scaling and grouped-query attention out of the box.
git clone --branch v0.12.0 https://github.com/NVIDIA/TensorRT-LLM.git
cd TensorRT-LLM
git submodule update --init --recursive
python3 scripts/build_wheel.py --trt_root=/usr/local/tensorrt
pip install build/tensorrt_llm-0.12.0-cp310-cp310-linux_x86_64.whl
With the wheel installed, use the official conversion script. The command below converts the 8B model using FP16 weights and saves a checkpoint optimized for tensor parallelism of size 1:
python examples/llama/convert_checkpoint.py \
--model_dir ./Meta-Llama-3.1-8B-Instruct \
--output_dir ./trt-llama-3.1-8b-fp16 \
--dtype float16 \
--tp_size 1 \
--use_parallel_embedding
This step performs weight transposition, consolidates the 32 attention heads for Llama 3.1's GQA configuration (8 KV heads), and stores the result in a safetensors format. Conversion of the 70B variant on a system with 1TB of host memory takes approximately 18 minutes. The resulting checkpoint directory contains config.json, rank0.safetensors (approximately 38 GB for FP16 70B), and a tokenizer.model file that must match the original Llama 3.1 tokenizer vocabulary of 128256 tokens.
A common pitfall is mismatched RoPE theta values. Llama 3.1 uses theta=500000.0 for extended context; the conversion script reads this automatically from the HF config.json, but manually overriding with --rope_theta 500000.0 is required if using an older checkpoint.
Building TensorRT Engines with Precise Configuration Flags
After checkpoint conversion, the build.py script generates the optimized CUDA kernels and engine plan file. For an A100 80GB system targeting Llama 3.1 8B with in-flight batching enabled, the following command produces a usable engine:
python examples/llama/build.py \
--checkpoint_dir ./trt-llama-3.1-8b-fp16 \
--output_dir ./engine-8b-fp16 \
--max_batch_size 128 \
--max_input_len 4096 \
--max_output_len 2048 \
--max_num_tokens 16384 \
--use_inflight_batching \
--paged_kv_cache \
--kv_cache_free_gpu_mem_fraction 0.85 \
--use_gemm_plugin auto \
--use_rmsnorm_plugin \
--use_flash_attention \
--dtype float16 \
--remove_input_padding
The --max_num_tokens parameter controls the total tokens processed in one forward pass and should be set to roughly 80% of GPU memory capacity in tokens. On an A100 80GB, 16384 tokens is a safe starting point for FP16. The build process for 8B takes 9 minutes on A100 and produces an engine of 47 GB that includes fused attention, fused FFN, and GEMM plugins tuned for SM80 architecture.
For the 70B model on two H100 GPUs, add --tp_size 2 and --pp_size 1. Tensor parallelism splits the QKV and FFN weights across GPUs using NCCL, reducing per-GPU activation memory from 68 GB to 37 GB. The resulting engine directory contains rank0.engine and rank1.engine files plus a unified config.json that the runtime reads to coordinate communication.
In-Flight Batching Mechanics and Request Scheduling
In-flight batching (also called continuous or dynamic batching) allows the engine to add newly arrived requests to the current batch without waiting for all requests in the previous batch to finish. This eliminates the head-of-line blocking present in static batching. TensorRT-LLM implements this through a C++ runtime scheduler that tracks sequence lengths and KV cache usage per request.
The key configuration parameters are --max_num_tokens and --max_batch_size. The scheduler fills the token budget first, then respects the batch size limit. Setting --max_num_tokens 16384 on an 8B model typically yields 95% GPU utilization under a mixed 512-2048 token workload, compared to 62% with static batching at batch size 32.
When a request finishes generation, its KV cache pages are immediately marked for reuse by the paged manager. New requests are inserted into the same CUDA graph iteration if sufficient pages remain. This mechanism is controlled by the kv_cache_free_gpu_mem_fraction flag; 0.85 leaves 15% headroom for fragmentation, which in practice keeps allocation failures below 0.3% even at 95% load.
The difference is most pronounced with variable-length outputs. A production trace with 70% short (≤64 token) responses sees 2.4× higher throughput with in-flight batching versus static batching at the same latency SLO.
Paged KV Cache Implementation and Memory Math
TensorRT-LLM's paged KV cache borrows the block table concept from vLLM but implements it in a custom CUDA kernel fused with the attention plugin. Each page is 16 tokens by default (configurable via --tokens_per_block). For a 70B model with 80 layers, FP16 precision, and 8 KV heads, one page consumes 80 × 2 × 16 × 128 bytes = 327680 bytes (320 KB).
An H100 with 80 GB can therefore hold roughly 240000 pages after reserving space for model weights. This translates to approximately 3.84 million tokens of KV cache. The runtime maintains a per-request block table stored in pinned host memory and updated via cudaMemcpyAsync each scheduling step. The overhead of this indirection is 0.8% additional latency according to NVIDIA's internal profiling.
To observe cache usage in production, enable the metrics server by passing --metrics to the C++ runtime binary and scrape the kv_cache_used_percent Prometheus gauge. When this gauge exceeds 92%, the scheduler begins pre-empting the longest-running requests to maintain latency SLOs.
Quantization Techniques: FP8, INT4 AWQ, and SmoothQuant
TensorRT-LLM supports multiple post-training quantization formats. For Llama 3.1, the most practical combination in 2024 is INT4 AWQ with per-group scaling. The workflow requires first quantizing the HF model with the AutoAWQ library at version 0.2.5, then converting the AWQ weights:
python examples/quantization/quantize.py \
--model_dir ./Meta-Llama-3.1-8B-Instruct \
--output_dir ./awq-llama-3.1-8b \
--quant_method awq \
--bits 4 \
--group_size 128
Then build with the quantized checkpoint:
python examples/llama/build.py \
--checkpoint_dir ./awq-llama-3.1-8b \
--output_dir ./engine-8b-int4-awq \
--use_inflight_batching \
--paged_kv_cache \
--use_weight_only \
--weight_only_precision int4 \
--per_group
AWQ preserves perplexity within 0.15 points of FP16 on the Llama 3.1 8B model for the WikiText-2 benchmark. Memory footprint drops from 16 GB (FP16) to 5.2 GB for the 8B weights, freeing headroom for larger batch sizes or longer contexts. On H100, the INT4 engine achieves 185 tokens/second for batch size 64 input-1024/output-256, compared with 97 tokens/second for the FP16 engine under identical conditions.
FP8 is simpler—no calibration dataset required—but currently only supported on H100 and H200 GPUs via the --use_fp8 flag. Activation scaling factors are computed at build time using max-abs calibration. Accuracy loss is higher than AWQ (0.4-0.6 perplexity increase) but kernel speed is 12% faster than INT4 due to native Tensor Core support.
Multi-GPU Tensor and Pipeline Parallelism Patterns
For the 70B model, tensor parallelism (TP) of 2 on two H100 GPUs is the minimum viable configuration. Adding --tp_size 2 during both conversion and build steps automatically shards the 8192-dimensional FFN layers. NCCL all-reduce operations for the final logits projection add 180 µs of latency per forward pass at 4k context.
Pipeline parallelism becomes useful only beyond 4 GPUs for the 405B model. With --pp_size 2, the engine splits layers into two stages, reducing per-GPU activation memory by 48% at the cost of 1.2× higher latency due to pipeline bubbles. The optimal configuration for latency-sensitive workloads remains TP=4 on four H100s with no pipeline parallelism.
Expert parallelism for future MoE variants of Llama is enabled with --moe_num_experts 8 --moe_top_k 2, routing tokens via a fused CUDA kernel that achieves 91% GPU utilization on 8×H100 systems.
Production Serving with the C++ Runtime and FastAPI Wrapper
The recommended production path is the C++ runtime wrapped by a lightweight Python/FastAPI service. Compile the runtime with:
cd cpp
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DTRT_ROOT=/usr/local/tensorrt
make -j16
Launch the engine with:
./trtllm-runtime \
--engine_dir ../../engine-8b-int4-awq \
--max_batch_size 128 \
--max_num_tokens 16384 \
--port 8000
A minimal FastAPI wrapper that adds OpenAI-compatible endpoints looks like this:
from fastapi import FastAPI
from trtllm import TRTLLMClient
app = FastAPI()
client = TRTLLMClient("http://localhost:8000")
@app.post("/v1/chat/completions")
async def chat(request: ChatCompletionRequest):
result = await client.generate(
prompt=request.messages,
max_tokens=request.max_tokens,
temperature=0.7,
streaming=request.stream
)
return result
This wrapper adds less than 400 µs of overhead per request. For high-QPS deployments, bypass Python entirely and use the gRPC interface exposed by the C++ binary directly from Node.js or Rust services.
Accuracy, Latency and Throughput Trade-offs
INT4 AWQ on Llama 3.1 70B reduces peak memory by 68% compared with FP16, enabling batch size 128 instead of 48 on a single H100. However, MMLU score drops from 81.4 to 80.7. For most customer support and internal tooling use cases this regression is imperceptible.
FP8 offers a middle ground: 1.9× throughput versus FP16 with only 0.3 point MMLU loss, but requires H100 hardware. On A100 systems, INT4 remains the only viable path for 70B models.
Context length also interacts with quantization. At 32k context, the KV cache dominates memory. INT4 weights free enough space to support 2.1× more concurrent 16k-context users than FP16 before hitting memory limits. The accuracy cost appears mainly in long-context needle-in-haystack tests, where FP16 retains 94% retrieval accuracy at 32k while INT4-AWQ drops to 87%.
Development velocity trade-off is significant. Building a new engine after any hyperparameter change takes 14 minutes for 8B and 47 minutes for 70B on 8×H100. Teams therefore maintain a matrix of 4-6 pre-built engines (FP16 short context, INT4 long context, FP8 high throughput) and route traffic at the load-balancer level using model tags.
Observability, Metrics and Cost Calculations
Enable detailed profiling by building with -DENABLE_TRITON=ON and using NVIDIA Nsight Systems to capture CUDA graphs. The runtime exports Prometheus metrics on port 9001 including:
trtllm_inflight_requeststrtllm_kv_cache_utilizationtrtllm_tokens_per_secondbroken down by request type
Integrate these into Grafana dashboards with alerts at 85% KV cache utilization. In practice, a 70B INT4 deployment on 4×H100 processes 850 requests per minute at p95 latency of 680 ms. At $2.80 per H100 hour in the cloud, this equates to $0.0009 per 1k output tokens—approximately 11× cheaper than the same workload on FP16 with smaller batch sizes.
Power consumption also improves with quantization. An INT4 engine on H100 draws 310W under load versus 395W for FP16, extending the feasible density in data centers with power-per-rack constraints.
Integration Patterns with LangChain.js and Next.js Applications
Connect a Next.js 15 application to the TensorRT-LLM backend using the OpenAI compatible client. The following code snippet demonstrates streaming responses directly to the browser:
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "dummy",
baseURL: "https://your-trtllm-host/v1",
});
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await openai.chat.completions.create({
model: "llama-3.1-70b-int4",
messages,
stream: true,
max_tokens: 1024,
});
return new StreamingTextResponse(stream);
}
Because the TensorRT-LLM backend supports the exact OpenAI /v1/chat/completions contract including tool calls, migration from GPT-4o to self-hosted Llama 3.1 requires only a baseURL change. For RAG workloads, embed documents with the same tokenizer (sentence-transformers/all-MiniLM-L6-v2 quantized to INT8) and retrieve before calling the completion endpoint. The low latency (average 45 ms to first token on H100) makes this suitable for interactive web UIs without artificial loading states.
When combining with LangGraph.js for agent workflows, wrap the TRTLLMClient in a custom LangChain tool. The deterministic execution time of the engine (no Python GIL) improves agent step predictability compared to Hugging Face text-generation-inference servers.
Common Pitfalls and Debugging Techniques
The most frequent build failure is OOM during engine compilation when --max_num_tokens is set too high. Reduce by 2048 tokens and retry. Another common issue is tokenizer mismatch; Llama 3.1 uses a tiktoken-derived vocabulary—always copy tokenizer.model and tokenizer_config.json from the original HF repo into the engine directory.
Debug KV cache fragmentation by enabling --debug_mode in the runtime; this logs block table state to stdout. If you observe frequent "cannot allocate page" errors despite low average utilization, lower --tokens_per_block from 16 to 8 at the cost of 4% additional management overhead.
For production fleets, implement canary deployments by running two engine versions side-by-side and routing 5% of traffic to the new quantization or context-length configuration. Monitor MMLU-style offline eval scores and p95 latency before full rollout.
TensorRT-LLM at v0.12.0 represents a mature production-grade inference stack for Llama 3.1. The combination of in-flight batching, paged KV cache, and AWQ INT4 delivers throughput and cost numbers that make self-hosting competitive with API providers for steady-state workloads above 200 queries per minute. Teams willing to manage GPU infrastructure and rebuild engines when new model versions appear gain full control over latency, privacy, and unit economics.
