Repository navigation
Open
Labels
backend: TensorRTstory: Performance & BenchmarkingPerformance gaps vs ONNX-TRT, engine size, reformatting overhead, profiling tools, and throughput re
Description
Problem
A TensorRT reduce-sum over a short axis of a bf16 tensor is about 8x slower than torch.sum. fp16 and fp32 inputs are much faster.
This shape is the "sum over the top-k experts" step of every mixture-of-experts layer exported from PyTorch, out.reshape(T, k, C).sum(dim=1), so it shows up in MoE models compiled with Torch-TensorRT.
Setup
H100, TensorRT 11.4.0.106, PyTorch 2.15.0 (CUDA 13.2). One network with a single IReduceLayer (SUM over axis 1), strongly typed.
Results
Sum over axis 1 of a [3500, 8, 3072] tensor:
| dtype | torch.sum | IReduceLayer | Same sum as 8 slices + 7 adds |
|---|---|---|---|
| bf16 | 0.100 ms | 0.790 ms | 0.141 ms |
| fp16 | 0.099 ms | 0.215 ms | 0.493 ms |
| fp32 | 0.185 ms | 0.217 ms | 0.552 ms |
- The bf16 kernel (
__myl_Sum_*) costs about 70 ns per output element, for a reduced length from 2 to 16. - The time is the same whether the axis is innermost, middle or outermost, with or without keep_dims, and with an fp32 cast placed before the reduce (the cast is fused into the same kernel).
- In a full MoE layer at 3500 tokens, the fused combine kernel takes 0.81 ms instead of about 0.1 ms. TensorRT sometimes rewrites the reduce into adds by itself inside larger engines, so the speed also depends on the surrounding layers.
Ask
Make the bf16 reduce over a short axis run near memory bandwidth, as it already does for fp32.
Possibly related: NVIDIA/TensorRT#4922 (fp32 ReduceSum slow when fused with its neighbours).
Repro
Needs only tensorrt and torch: python repro_reduce.py [A K C]
repro_reduce.py
"""TensorRT: IReduceLayer SUM over a short axis of a 16-bit tensor runs far below memory bandwidth.
One network with a single IReduceLayer (SUM over axis 1 of [3500, 8, 3072], the "sum over top-k experts" step of a
mixture-of-experts layer). Compares bf16, fp16 and fp32 inputs, and the same sum written as 7 elementwise adds of
8 slices. Needs tensorrt and torch (torch only allocates buffers and times with CUDA events).
python repro_reduce.py [A K C]
"""
import statistics, sys
import tensorrt as trt
import torch
A, K, C = (int(v) for v in sys.argv[1:4]) if len(sys.argv) > 3 else (3500, 8, 3072)
LOG = trt.Logger(trt.Logger.ERROR)
TRT_DT = {torch.bfloat16: trt.bfloat16, torch.float16: trt.float16, torch.float32: trt.float32}
def engine(dtype, as_adds):
b = trt.Builder(LOG)
net = b.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
x = net.add_input("x", TRT_DT[dtype], (A, K, C))
if as_adds:
y = None
for k in range(K):
s = net.add_slice(x, (0, k, 0), (A, 1, C), (1, 1, 1)).get_output(0)
s = net.add_cast(s, trt.float32).get_output(0)
y = s if y is None else net.add_elementwise(y, s, trt.ElementWiseOperation.SUM).get_output(0)
sh = net.add_shuffle(net.add_cast(y, TRT_DT[dtype]).get_output(0)); sh.reshape_dims = (A, C)
y = sh.get_output(0)
else:
y = net.add_reduce(x, trt.ReduceOperation.SUM, 1 << 1, False).get_output(0)
y.name = "y"; net.mark_output(y)
plan = b.build_serialized_network(net, b.create_builder_config())
eng = trt.Runtime(LOG).deserialize_cuda_engine(plan)
return eng, eng.create_execution_context()
def time_ms(fn, n=50):
for _ in range(10):
fn()
torch.cuda.synchronize()
ts = []
for _ in range(n):
s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
s.record(); fn(); e.record(); torch.cuda.synchronize(); ts.append(s.elapsed_time(e))
return statistics.median(ts)
print(f"TensorRT {trt.__version__}, {torch.cuda.get_device_name()}, sum over axis 1 of [{A}, {K}, {C}]")
for dtype in (torch.bfloat16, torch.float16, torch.float32):
x = torch.randn(A, K, C, device="cuda", dtype=dtype)
want = x.float().sum(1)
gb = (x.numel() + A * C) * x.element_size() / 1e9
t = time_ms(lambda: x.sum(1))
row = [f"{str(dtype)[6:]:9s} torch.sum {t:6.3f} ms ({gb / t:4.2f} TB/s)"]
for as_adds in (False, True):
eng, ctx = engine(dtype, as_adds)
y = torch.empty(A, C, device="cuda", dtype=dtype)
ctx.set_tensor_address("x", x.data_ptr()); ctx.set_tensor_address("y", y.data_ptr())
run = lambda: ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream)
run(); torch.cuda.synchronize()
err = ((y.float() - want).norm() / want.norm()).item()
t = time_ms(run)
row.append(f"{'adds' if as_adds else 'IReduceLayer'} {t:6.3f} ms ({gb / t:4.2f} TB/s, rel err {err:.0e})")
print(" | ".join(row), flush=True)Metadata
Metadata
Assignees
Labels
backend: TensorRTstory: Performance & BenchmarkingPerformance gaps vs ONNX-TRT, engine size, reformatting overhead, profiling tools, and throughput re
Activity