Builder picks a slower bf16 GEMM kernel on Orin (sm_87): the 160x128x32 tiles run about 24% slower than the builder measured

Abierto
#4,937 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 6 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
12/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
cpp, python

Línea de trabajo

Start by running repro_gemm.py with --builds 9 to see the kernel choice vary, then with the --force options to pin each tactic and compare build-time timing with run time. The mismatch is in the builder's timing of the 160x128x32 tactics on sm_87, which lives in TensorRT's C++ kernel selection code, not in the script. Done means build-time timing matches run time for these kernels, or the near-tie choice is stable and documented.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Module:Performance

What is wrong

For one bf16 GEMM, the builder sees a near tie between kernels and picks a different one from build to build. One of the candidates runs much slower in the finished engine than the builder measured. So most builds of the same network are slower.

Who hits it: anyone who builds a bf16 GEMM of this shape on Jetson Orin.

What this blocks

pi05 on the Jetson Orin Nano (pytorch/executorch#24353) has GEMMs of this shape, and its time per chunk changes from export to export with the kernel the builder picks.
In the results below, 9 of 10 builds pick the slower kernel, so most builds run slower than they could.
A fix gives the fast kernel in every build, and makes timings repeatable.

Results

GEMM bf16 [1, 574, 16384] x [1, 16384, 2048], a fresh empty timing cache per build.

Jetson Orin Nano (sm_87), 10 fresh builds (9 in one run, 1 in a second run):

kernel builds build-time ms run ms
160x128x32, stage 3, warps 2x2x1 6 5.025 to 5.044 6.26
160x128x32, stage 4, warps 2x2x1 3 5.037 to 5.043 6.26
192x128x32, stage 3, warps 4x2x1 1 5.047 5.037

Forcing each tactic with an editable timing cache gives the same run times (5.038, 6.260, 6.259 ms). So the 160x128x32 kernels run 24% slower than their build-time timing, while 192x128x32 is timed correctly.

Expected

Build-time timing that matches run time for these kernels, or a stable, documented choice between near ties.

Versions

TensorRT 11.4.0.106, torch 2.15.0 (CUDA 13.2, buffers and timing only). Orin Nano Super, JetPack 7.2.1, MAXN_SUPER, driver 595.78.

Repro

python repro_gemm.py --m 574 --k 16384 --n 2048 --builds 9
python repro_gemm.py --m 574 --k 16384 --n 2048 --builds 1 \
    --force auto:0x585df2ecfe17f --force auto:0x4506b6dcf033e --force auto:0x2f80246d912f6   # Orin tactic hashes
repro_gemm.py
import argparse, json, statistics, sys, time

import tensorrt as trt
import torch

ap = argparse.ArgumentParser()
ap.add_argument("--m", type=int, required=True)
ap.add_argument("--k", type=int, required=True)
ap.add_argument("--n", type=int, required=True)
ap.add_argument("--builds", type=int, default=8)
ap.add_argument("--runs", type=int, default=300)
ap.add_argument("--warmup", type=int, default=30)
ap.add_argument("--force", action="append", default=[], help="KEY_HEX:TACTIC_HEX, KEY_HEX 'auto' = the GEMM entry")
a = ap.parse_args()
log = trt.Logger(trt.Logger.WARNING)

torch.manual_seed(0)
W = (torch.randn(a.k, a.n) * 0.02).to(torch.bfloat16)
X = (torch.randn(1, a.m, a.k) * 0.5).to(torch.bfloat16).cuda()


def network(builder):
    net = builder.create_network(0)
    x = net.add_input("x", trt.bfloat16, (1, a.m, a.k))
    w = net.add_constant((1, a.k, a.n), trt.Weights(trt.bfloat16, W.data_ptr(), W.numel()))
    mm = net.add_matrix_multiply(x, trt.MatrixOperation.NONE, w.get_output(0), trt.MatrixOperation.NONE)
    net.mark_output(mm.get_output(0)); mm.get_output(0).name = "y"
    return net


def build(force=None):
    builder = trt.Builder(log); net = network(builder); cfg = builder.create_builder_config()
    cfg.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
    cfg.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 30)
    if force:
        cfg.set_flag(trt.BuilderFlag.EDITABLE_TIMING_CACHE)
    tc = cfg.create_timing_cache(b""); cfg.set_timing_cache(tc, False)
    if force:  # update() only edits an existing entry: build once to fill the cache, then pin the tactic
        key_hex, tac_hex = force
        assert builder.build_serialized_network(net, cfg) is not None
        keys = tc.queryKeys()
        key = max(keys, key=lambda k: tc.query(k).timingMSec) if key_hex == "auto" else \
            next(k for k in keys if str(k) == key_hex)
        tc.update(key, trt.TimingCacheValue(int(tac_hex, 16), 1e-3))
    plan = builder.build_serialized_network(net, cfg)
    eng = trt.Runtime(log).deserialize_cuda_engine(plan)
    info = json.loads(eng.create_engine_inspector().get_engine_information(trt.LayerInformationFormat.JSON))
    kernels = [L.get("TacticName") for L in info.get("Layers", []) if isinstance(L, dict)]
    cache = {str(k): (hex(tc.query(k).tacticHash), round(tc.query(k).timingMSec, 4)) for k in tc.queryKeys()}
    ctx = eng.create_execution_context()
    Y = torch.empty(1, a.m, a.n, dtype=torch.bfloat16, device="cuda")
    ctx.set_tensor_address("x", X.data_ptr()); ctx.set_tensor_address("y", Y.data_ptr())
    s = torch.cuda.Stream()
    for _ in range(a.warmup):
        ctx.execute_async_v3(s.cuda_stream)
    s.synchronize(); ts = []
    for _ in range(a.runs):
        e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        e0.record(s); ctx.execute_async_v3(s.cuda_stream); e1.record(s); e1.synchronize()
        ts.append(e0.elapsed_time(e1))
    return statistics.median(ts), kernels, cache


print(f"TensorRT {trt.__version__}, {torch.cuda.get_device_name()} cc {torch.cuda.get_device_capability()}")
for i in range(a.builds):
    ms, kernels, cache = build()
    print(f"build {i}: run median {ms:.4f} ms; build-time cache {cache}; kernels {kernels}")
for f in a.force:
    ms, kernels, cache = build(tuple(f.split(":")))
    print(f"forced {f}: run median {ms:.4f} ms; kernels {kernels}")

Actual

Orin Nano Super, JetPack 7.2.1, MAXN_SUPER, driver 595.78 (cache keys shortened to the tactic and its time):

TensorRT 11.4.0.106, Orin cc (8, 7)
build 0: run median 6.2593 ms; build-time ('0x2f80246d912f6', 5.0403); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 1: run median 6.2584 ms; build-time ('0x2f80246d912f6', 5.0332); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 2: run median 6.2566 ms; build-time ('0x2f80246d912f6', 5.0353); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 3: run median 6.2588 ms; build-time ('0x4506b6dcf033e', 5.0393); kernels [...tilesize160x128x32_stage4_warpsize2x2x1...]
build 4: run median 6.2600 ms; build-time ('0x2f80246d912f6', 5.038); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 5: run median 6.2618 ms; build-time ('0x4506b6dcf033e', 5.0431); kernels [...tilesize160x128x32_stage4_warpsize2x2x1...]
build 6: run median 6.2577 ms; build-time ('0x2f80246d912f6', 5.0247); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 7: run median 6.2608 ms; build-time ('0x2f80246d912f6', 5.0443); kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
build 8: run median 6.2607 ms; build-time ('0x4506b6dcf033e', 5.0372); kernels [...tilesize160x128x32_stage4_warpsize2x2x1...]

Forced run (--builds 1 --force auto:0x585df2ecfe17f --force auto:0x4506b6dcf033e --force auto:0x2f80246d912f6):

build 0: run median 5.0369 ms; build-time ('0x585df2ecfe17f', 5.0472); kernels [...tilesize192x128x32_stage3_warpsize4x2x1...]
forced auto:0x585df2ecfe17f: run median 5.0380 ms; kernels [...tilesize192x128x32_stage3_warpsize4x2x1...]
forced auto:0x4506b6dcf033e: run median 6.2603 ms; kernels [...tilesize160x128x32_stage4_warpsize2x2x1...]
forced auto:0x2f80246d912f6: run median 6.2592 ms; kernels [...tilesize160x128x32_stage3_warpsize2x2x1...]
Lenguaje dominante
C++
Estrellas
13.5k
Forks
2.4k
Merge medio
6 d 21 h
PR fusionados (30 d)
3

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de NVIDIA/TensorRT

Todos los issues de NVIDIA/TensorRT

Issues similares

Más issues de C++

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.