Repository navigation
Description
What is wrong
PyTorch computes a bfloat16 layer norm in float32 and rounds once, after the scale and shift. Its bfloat16 GELU also computes in float32. Torch-TensorRT converts each op to one TensorRT layer in bfloat16, with no cast. In a strongly typed network TensorRT may then compute in bfloat16, and it does:
- Layer norm (
__myl_CastMeanSubMulMeanAddSqrtDivMulCastMulAdd): the mean and variance are in float32, but the normalized value is rounded to bfloat16 before the scale and shift. Emulating that rounding in PyTorch gives the same error exactly. - GELU tanh (
__myl_MoveMulMulMulAddMulTanhAddMulMul): the fused kernel has no cast to float32, and its error is higher than PyTorch's.
Error against float32 on the same bfloat16 input (relative L2):
| Op | PyTorch bf16 | Torch-TensorRT bf16 | Torch-TensorRT, op in float32 |
|---|---|---|---|
| layer norm | 0.00166 | 0.00286 | 0.00166 |
| layer norm, outlier channels | 0.00189 | 0.00341 | 0.00189 |
| GELU (tanh) | 0.00082 | 0.00100 | 0.00082 |
On these inputs layer norm has 1.7x the error of PyTorch and GELU 1.2x. A vision transformer runs both in every layer. I found this in Alpamayo 2 Edge (pytorch/executorch#25253). In plain bfloat16 its predicted path drifts several times more than PyTorch's own noise. With these ops forced to float32 it matches float32 accuracy.
TensorRT allows this: its docs say the accumulation type is the input type or wider, and advise casting the inputs to float32 for float32 normalization. The TensorRT 11 normalization layer has no compute precision setting. Torch-TensorRT's autocast can keep these ops in float32 for a float32 model, but a model that is already bfloat16 has no such switch.
Expected
The bfloat16 native_layer_norm and gelu converters cast to float32 around the TensorRT layer and cast back once, as PyTorch does. There is precedent: the batch_norm converter already switches to float32 when its weights would lose precision. Casting inside the engine gave exactly PyTorch's error in my runs.
Repro
repro.py
"""Layer norm and GELU inside a bfloat16 TensorRT engine, against PyTorch bfloat16.
Every op gets the same bfloat16 input. The reference is the same op in float32 on that
input. Error is relative: ||out - ref|| / ||ref||. Shapes follow a SigLIP-style vision
tower (hidden 1152, MLP 4304, 364 tokens). "in fp32" is the op wrapped as
op(x.float()).bfloat16(), compiled with TensorRT.
"""
import copy
import torch
import torch.nn as nn
import torch_tensorrt
class InFp32(nn.Module):
def __init__(self, op):
super().__init__()
self.op = op
def forward(self, x):
return self.op(x.float()).bfloat16()
def rel(a, ref):
return ((a.float() - ref).norm() / ref.norm()).item()
def trt_kernel(fn):
with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof:
fn()
torch.cuda.synchronize()
return max((e for e in prof.key_averages() if e.device_time_total > 0), key=lambda e: e.device_time_total).key.split("_0x")[0]
def compile_trt(m, x):
return torch_tensorrt.dynamo.compile(torch.export.export(m, (x,)), inputs=[x], min_block_size=1)
print(torch_tensorrt.__version__, torch.__version__, torch.cuda.get_device_name())
torch.manual_seed(0)
ln = nn.LayerNorm(1152, eps=1e-6).cuda()
with torch.no_grad():
ln.weight.normal_(1, 0.2), ln.bias.normal_(0, 0.2)
# Residual streams in vision transformers have a few channels with large values.
outliers = torch.randn(1152, device="cuda") * (torch.rand(1152, device="cuda") < 0.02) * 50
x = torch.randn(1, 364, 1152, device="cuda")
cases = [
("layer norm", ln.bfloat16(), x),
("layer norm, outlier channels", ln.bfloat16(), x + outliers),
("GELU (tanh)", nn.GELU(approximate="tanh"), torch.randn(1, 364, 4304, device="cuda") * 3),
]
with torch.no_grad():
for name, op, x32 in cases:
x = x32.bfloat16()
ref = copy.deepcopy(op).float()(x.float())
trt = compile_trt(op, x)
trt32 = compile_trt(InFp32(copy.deepcopy(op).float()), x)
print(f"{name}: PyTorch bf16 {rel(op(x), ref):.5f} | TensorRT bf16 {rel(trt(x), ref):.5f} "
f"[{trt_kernel(lambda: trt(x))}] | TensorRT in fp32 {rel(trt32(x), ref):.5f}", flush=True)Output:
$ python repro.py
2.15.0+cu132 2.15.0+cu132 NVIDIA PG509-210
layer norm: PyTorch bf16 0.00166 | TensorRT bf16 0.00286 [__myl_CastMeanSubMulMeanAddSqrtDivMulCastMulAdd] | TensorRT in fp32 0.00166
layer norm, outlier channels: PyTorch bf16 0.00189 | TensorRT bf16 0.00341 [__myl_CastMeanSubMulMeanAddSqrtDivMulCastMulAdd] | TensorRT in fp32 0.00189
GELU (tanh): PyTorch bf16 0.00082 | TensorRT bf16 0.00100 [__myl_MoveMulMulMulAddMulTanhAddMulMul] | TensorRT in fp32 0.00082
Environment
NVIDIA A100 80GB, TensorRT 11.4.0.106, torch 2.15.0+cu132, Torch-TensorRT 2.15.0.
Activity