AI State of the Art
SOTA/Inference & Optimization/25 min
Section 126

TensorRT-LLM: NVIDIA Compilation and Optimization

Listen as a podcast →

One word explains everything: compiler

TensorRT-LLM, usually shortened to TRT-LLM, is NVIDIA's tool for running a large language model (LLM) on NVIDIA graphics cards (graphics processing units, or GPUs).

A single word captures how it works, where its gains come from, and what its drawbacks are: it is a compiler.

Here is the analogy. There are two ways to deliver a text. You can read it aloud as you go, working out each sentence on the fly, that is what an ordinary inference library does: it receives the model and, for each operation, calls the matching routine. Or you can spend time up front preparing a final version of the text, reworked so that one specific speaker can deliver it as fast as possible in one specific room. That takes longer to prepare, nothing can be changed afterwards, and the result suits only that speaker, but it is faster.

TensorRT-LLM does the second thing. It takes the model description and produces a frozen program, called an engine, cut to fit one model, one card and one configuration. Everything else on this page follows from that.

Two families of tools, two philosophies

A serving engine such as vLLM interprets the model at run time: you can switch cards, context lengths or batch sizes without rebuilding anything. TensorRT-LLM compiles first and runs second. The first is flexible, the second is fast. This is not a ranking but a trade, and it is spelled out below.

What "compiling" means here

The chain has two stages: first the model weights are converted into the format TensorRT-LLM expects, then the engine build is launched. The build is the expensive step: it can take anywhere from a few minutes to several hours depending on model size and how many optimizations are requested.

Three-stage NVIDIA diagram, left to right. On the left, a small neural network labelled Trained Neural Network. In the centre, a large green arrow passes through a ring of optimizations surrounding a window named TensorRT Optimizer; five badges around the ring are labelled Precision Calibration, Layer and Tensor Fusion, Kernel Auto-Tuning, Dynamic Tensor Memory and Multi-Stream Execution. On the right, a TensorRT Runtime window with a play button, labelled Optimized Inference Engine.
The trip through the mill. The already-trained network goes in on the left, TensorRT applies the five families of optimizations in the central ring (precision calibration, layer fusion, automatic kernel selection, memory management, multi-stream execution) and it comes out on the right as a compiled engine, frozen for one specific GPU.Source : NVIDIA Technical Blog, TensorRT 3: Faster TensorFlow Inference

Four things happen during that build.

Kernel fusion. A kernel is a small program the GPU runs over a block of data. In an uncompiled model, every elementary operation is its own kernel: a matrix multiplication, then a bias addition, then an activation function. Between two kernels, the intermediate result makes a round trip through the card's memory. Fusing means rewriting the three as a single kernel that keeps the intermediate result in place. The round trips disappear, and that is where most of the speed is won, for the underlying reason set out in Quantization: the concepts: inference is limited by memory bandwidth, meaning the throughput of the pipe that feeds the compute units, not by the power of those units.

Two computation graphs side by side for the same network module. On the left, under the title Un-Optimized Network, each branch stacks separate boxes: 1x1 conv., then bias, then relu, and likewise for the 3x3 conv. and 5x5 conv. branches, about twenty small boxes joined by arrows, plus a max pool. On the right, under the title TensorRT Optimized Network, the same branches contain only a few large boxes labelled 1x1 CBR, 3x3 CBR, 5x5 CBR and max pool: each convolution-bias-activation triplet has been merged into a single box, and the two identical 1x1 convolutions have been merged into one wide box.
Kernel fusion in one picture. On the left, the graph as it comes out of the framework: every convolution, every bias, every activation is a separate operation, so one more round trip to GPU memory. On the right, the compiled graph: each convolution-bias-activation triplet is melted into a single box labelled CBR, and the number of kernel launches collapses.Source : NVIDIA Technical Blog, TensorRT 3: Faster TensorFlow Inference

Automatic kernel selection. For one and the same matrix multiplication there are dozens of possible implementations, and the fastest one depends on the exact dimensions and on the card model. The compiler tries them and keeps the best for the dimensions it was told about. That choice is measured on the target machine, which is also why the result is only valid on that machine.

Precision selection. TensorRT-LLM can run layers in FP8, INT8 or INT4 where the card supports it. The principle and the trade-offs are covered in Quantization: the concepts.

Optimized attention. Attention is handed to FlashAttention-style kernels that avoid writing the full attention matrix to memory. See FlashAttention.

The trade-off, stated plainly: portability versus speed

This is the point to take away. The compiled engine is fast because it is specialized, and it is brittle for the same reason. An engine is tied to:

  • a card model, an engine built for an H100 will not run on an A100;
  • a version of TensorRT-LLM;
  • a configuration: maximum batch size, maximum context length, number of cards.

Change any of these and you must rebuild. There is no run-time flexibility: whatever was not planned at compile time does not exist.

The practical consequence

TensorRT-LLM requires sizing decisions up front. If real traffic exceeds the batch size or context length you planned for, you have to run another build and redeploy. That is acceptable for a stable, high-volume service; it is a blocker while you are still exploring.

Conversely, a model exported to the ONNX format (Open Neural Network Exchange, a file format readable by many engines, see ONNX Runtime) runs on almost any hardware, more slowly. The two pages describe the two ends of the same trade-off.

FP8 on Hopper cards

FP8 is an 8-bit floating-point number format. The E4M3 variant splits those 8 bits into 1 sign bit, 4 exponent bits and 3 mantissa bits; the E5M2 variant gives one more bit to the exponent, so a wider range and lower precision.

The format has a precise hardware payoff on NVIDIA's Hopper architecture (H100, H200 cards). The Tensor Cores (the units specialized in matrix multiplication) process FP8 at twice the peak throughput of FP16, according to NVIDIA's published H100 specifications. Half as many bytes per weight also means half as much data to push through the memory pipe.

Peak throughput is not an end-to-end gain

The factor of 2 applies to the theoretical maximum speed of the compute units, not to the response time of a real service. That depends on model size, sequence lengths, how many requests are processed together, and how much time is spent outside matrix multiplications. The observed gain is always below 2x, by an amount that depends on the deployment.

A word on quality: unlike INT8, FP8 keeps an exponent. The range of representable values is therefore wide, which makes the conversion less delicate than with integers. In practice the NVIDIA toolchain still goes through a calibration step, a small dataset is pushed through the model to measure the typical magnitude of values and derive scaling factors from it. How much quality is lost depends on the model and the task, and has to be measured case by case.

In-flight batching

TensorRT-LLM calls in-flight batching what the rest of the ecosystem calls continuous batching. The principle, the numbers behind the tipping point, and the reason this is the highest-return lever in served inference are all in Continuous batching: a single request exploits less than 1% of the card's compute, and it takes roughly 150 requests processed together before the chip stops waiting on data.

Comparison of two batching modes shown as timeline grids whose columns are the time steps T1 to T8. On top, Dynamic Batching: three requests R1, R2 and R3 occupy three rows; R1 and R3 reach a red cell marked END as early as T4, but their rows then stay empty, and the new requests R4, R5 and R6 only appear in the very last column T8. At the bottom, In-flight Batching: as soon as R1 and R3 reach END at T4, requests R4 and R6 start immediately in the freed cells and the grid stays full to the end.
What in-flight batching avoids. On top, a request that finishes early leaves its row empty until the whole batch is done: the GPU computes on nothing. At the bottom, the freed slot is picked up by a new request at the very next iteration, so the batch never thins out.Source : NC Research blog (NCSOFT)

What TensorRT-LLM adds is a matter of execution: mixing input-text processing and generation in one batch, choosing dynamically which requests get served, and forcibly suspending a request when memory runs short.

Spreading a model over several cards

Two ways to cut it up, both handled by TensorRT-LLM.

Tensor parallelism (TP) slices each layer across cards: card 0 takes some of the columns of the weight matrix, card 1 the rest. Each computes its slice, then the cards exchange and sum their partial results, the collective operation that does this is called AllReduce. This cut reduces response time, since the work of one layer is done in parallel, but by less than the number of cards: AllReduce happens several times per layer and its cost grows with the number of participants. See Tensor parallelism.

Pipeline parallelism (PP) slices the model into groups of layers: card 0 takes the first layers, card 1 the next ones. A request crosses the cards in series, so its response time does not drop; on the other hand several requests can occupy different stages at once, which raises the number of requests served per second. See Pipeline parallelism.

In short: tensor parallelism buys latency, pipeline parallelism buys throughput. They are often combined.

About the exact commands

The TensorRT-LLM build chain is driven from the command line in two steps: convert the model checkpoint into the internal format, then build the engine with the number of cards, the maximum batch size and the maximum context length. The precise option names have changed several times across versions; we do not reproduce them here rather than print a command that would be wrong. What matters for the pages that follow is the two-stage structure, and the fact that those three parameters are frozen at build time.

What Triton adds on top

A compiled engine is not yet a service. NVIDIA ships Triton Inference Server separately: the layer that puts the engine behind a network interface and adds what production requires, a request queue, load balancing across instances, handling of several models and of several versions of the same model, and metrics reporting. The division of labour is clean: TensorRT-LLM produces the fast program, Triton operates it. What such a layer must provide is detailed in Deploying a model in production.

When to reach for it, when not to

The favourable case: a stable, high-volume service on homogeneous NVIDIA hardware, whose context length and load are known in advance, and where a few milliseconds of latency carry measurable value. On Hopper cards, access to native FP8 strengthens the case.

The unfavourable case: exploration and prototyping, where the model and the configuration change daily; a heterogeneous or multi-vendor fleet; low volume, where engineering time costs more than the cards it saves.

What to take away

TensorRT-LLM is an inference compiler. It trades flexibility for speed, and the trade is explicit: the engine it produces is faster because it can only do one thing, on one machine, in one configuration. When those three are stable, it is the right tool. When they move, the cost of rebuilding erases the gain.

Check your understanding0 / 5

1. Where does most of the speed gained by TensorRT-LLM compilation come from?

2. Your TensorRT-LLM-compiled service suddenly receives requests longer than the context length planned at build time. What happens?

3. On the H100, Tensor Cores process FP8 at twice the peak throughput of FP16. Will your service run twice as fast by switching to FP8?

4. What does the in-flight batching promoted by TensorRT-LLM refer to?

5. When spreading a model across several cards, what should you expect from tensor parallelism and pipeline parallelism?