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

未关闭
#4,937 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 6 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
12/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
cpp, python

调研方向

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.

由索引模型根据 Issue 内容生成。

描述

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...]
主要语言
C++
星标
13.5k
派生
2.4k
平均合并
6 天 21 小时
30 天内合并 PR
3

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

NVIDIA/TensorRT 的其他 Issue

查看 NVIDIA/TensorRT 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。