[Bug] GroupRMSNorm kernels: shared-memory init race inflates outputs; one-warp large-batch path never normalises input 1
Summary. Two bugs in the GroupRMSNorm kernels make torch.ops.trtllm.group_rms_norm_base, group_rms_norm_heuristic and group_rms_norm_large_batch write wrong outputs: a race on the shared-memory initialisation inflates outputs, and the large-batch kernel never normalises input 1 when it runs with one warp. We suggest a __syncthreads() after the initialisation in both kernels for the first; the second can be fixed in two ways, listed under additional notes.
System Info
- TensorRT-LLM 1.2.1 wheel, torch 2.9.1+cu130, A100 80GB PCIe (driver 610.57).
cpp/tensorrt_llm/kernels/groupRmsNormKernels/groupRmsNormKernels.cuis unchanged on mainb031dbe. The two device kernels in the 1.2.1 release are identical to main's.
Who can help?
No response
Information
- [ ] The official example scripts
- [x] My own modified scripts
Tasks
- [ ] An officially supported task in the
examplesfolder (such as GLUE/SQuAD, ...) - [x] My own task or dataset (give details below)
Reproduction
A minimal script:
import torch
import tensorrt_llm # registers torch.ops.trtllm
def run(name, batch, dims, calls=1000):
op = getattr(torch.ops.trtllm, name)
xs = [(torch.randn(batch, d) * (1 + i)).bfloat16().cuda() for i, d in enumerate(dims)]
ws = [(0.5 + torch.rand(d)).bfloat16().cuda() for d in dims]
refs = []
for x, w in zip(xs, ws):
xd = x.double()
refs.append(xd * torch.rsqrt(xd.square().mean(-1, keepdim=True) + 1e-6) * w.double())
wrong = [0] * len(dims)
for _ in range(calls):
outs = [torch.empty_like(x) for x in xs]
op(xs, outs, ws, 1e-6, 0.0)
for i, (y, ref) in enumerate(zip(outs, refs)):
wrong[i] += bool(((y.double() - ref).abs() > 1e-3 + 0.016 * ref.abs()).any())
print(f"{name} {batch}x{dims}: wrong calls per input {wrong} of {calls}")
torch.manual_seed(0)
run("group_rms_norm_base", 64, (1536, 512))
run("group_rms_norm_large_batch", 2048, (256, 256))
On an A100 (SXM4 80GB) it printed:
group_rms_norm_base 64x(1536, 512): wrong calls per input [1000, 991] of 1000
group_rms_norm_large_batch 2048x(256, 256): wrong calls per input [0, 1000] of 1000
Results with the 1.2.1 wheel, from a longer harness: each op ran for 120 s, cycling three input sets.
- Input 0 is
randnand input 1 is2 * randn, both rounded to bf16. - Weights are
0.5 + rand, rounded to bf16. eps = 1e-6andweight_bias = 0.- The reference is float64 from the same bf16 inputs.
- A call counts as wrong if any element of an output differs by more than 1e-3 + 0.016 · |ref|.
| Operator | Inputs | Wrong calls |
|---|---|---|
group_rms_norm_base |
[64, 1536] + [64, 512] | 397748 / 397774 |
group_rms_norm_heuristic (falls back to the base kernel on A100) |
[64, 1536] + [64, 512] | 368411 / 368440 |
group_rms_norm_large_batch |
[2048, 256] + [2048, 256] | input 1 wrong in 401268 / 401268; input 0 correct in every call |
Examples of the wrong values:
- 0.0262 for 0.0187 (base): one of input 1's two warp sums was lost;
- 2448.0 for 1.19 (heuristic): both were lost, so the kernel used
rsqrt(eps)= 1000; - −47.25 for −0.018 (large batch): input 1 was multiplied by its sum of squares.
Each of these logged values equals exactly what the mechanism below predicts.
Expected behavior
Each output row is x * rsqrt(mean(x²) + eps) * (w + weight_bias).
actual behavior
Cause
1. Race on the shared-memory initialisation. In GroupRMSNormBaseKernel, warp 0 initialises smem_input_mask[lane] and smem_warp_sum_sqs[lane] (lines 104–109). Lane 0 of every other warp k later writes its partial sum and input index to slot k of the same arrays (lines 179 and 188). No barrier separates the two; the first __syncthreads() is at line 191. If warp 0's initialising store lands after warp k's write, warp k's contribution to the sum of squares is lost. The row then comes out too large.
The __syncwarp() for sm < 900 before line 188 ("needed to avoid race condition on smem_input_mask write") orders only within a warp. In a standalone copy of the kernel, Compute Sanitizer racecheck reports this race. A __syncthreads() after the initialisation removed both the report and the wrong outputs on A100 and A40. In an sm_80 build we compiled with CUDA 12.6, the initialising stores are scheduled after the loads. We have not run on Hopper or Blackwell.
GroupRMSNormKernelLargeBatch has the same pattern:
- warps 0 and 1 initialise rows 0 and 1 of
smem_rsqrts(lines 286–289); - lane 0 of each warp writes
smem_rsqrts[0][warp_idx]andsmem_rsqrts[1][warp_idx](lines 388 and 429), before the first barrier (line 433).
Racecheck reports it as well, and the one launch we ran under racecheck gave inflated outputs. In about 9,000 normal launches each on A100 and A40, we saw no wrong output from it.
2. Input 1 is never normalised when the large-batch kernel runs with one warp. The large-batch kernel converts each input's sum of squares to a reciprocal RMS in a dedicated warp:
if (warp_idx == 0) { ... smem_rsqrts[0][0] = rsqrtf(block_sum / input_dim_0 + params.eps); }
else if (warp_idx == 1) { ... smem_rsqrts[1][0] = rsqrtf(block_sum / input_dim_1 + params.eps); }
When each input has at most 256 bf16 or fp16 elements (128 fp32), calculateNumWarpsLargeBatch launches a single warp, and the warp_idx == 1 branch never runs. smem_rsqrts[1][0] keeps the sum of squares of input 1's row that warp 0 stored at line 429, and input 1 is multiplied by it (lines 523 and 529). Input 1 is wrong in every call; input 0 is correct.
By our reading of the heuristic model in groupRmsNormKernels.h, group_rms_norm_heuristic also picks this one-warp kernel for two 256-wide inputs at batch sizes from about 1034 on SM90 and 1387 on SM100. We did not run it there.
additional notes
Suggested fix for 1
@@ -108,6 +108,8 @@ __global__ void GroupRMSNormBaseKernel(GroupRMSParams<n> params, int rounds)
smem_input_mask[lane_idx] = 33;
smem_warp_sum_sqs[lane_idx] = 0.0f;
}
+ // Order warp 0's initialisation before other warps write the same slots below.
+ __syncthreads();
float warp_acc = 0.0f;
PackedType const* __restrict__ weight_ptr = nullptr;
@@ -287,6 +289,8 @@ __global__ void GroupRMSNormKernelLargeBatch(
{
smem_rsqrts[warp_idx][lane_idx] = 0.0f;
}
+ // Order the initialisation before other warps write the same slots below.
+ __syncthreads();
const uint32_t round_offset = warp_size * kPackedSize;
Options for 2
Make sure both reciprocals are computed when the block has one warp:
- Launch at least two warps, in
calculateNumWarpsLargeBatch, so the heuristic sees the same count. This needs fix 1 as well: otherwise warp 1's initialisation ofsmem_rsqrts[1][0]races with warp 0's write at line 429. - Let warp 0 also reduce input 1 when there is one warp. This needs row 1 of
smem_rsqrtsinitialised first.
Scope
Outside its unit test (tests/unittest/_torch/modules/test_group_rmn_norm.py), we found no in-tree caller of group_rms_norm or these ops. That test's large-batch shapes always launch at least two warps, so it does not exercise bug 2.
One more bug in the same kernels, separate from the race and the large-batch warp count, and not covered by #20109: for some pairs of last dims, group_rms_norm_base / group_rms_norm_heuristic never write the tail of each row of one input, and also leave those elements out of that input's sum of squares.
Examples: fp32 (8192, 4096) and (7168, 5120), 128 elements per row missing; fp32 (160, 11936), 32 missing; bf16/fp16 (7712, 16160), 32 missing.
Cause. The base launcher (groupRmsNormKernels.cu, v1.2.1, lines ~595-615) caps the block at 32 warps and splits them with round(rounded_input_dims[i] * warps_per_token); each warp covers 32 * kPackedSize * rounds elements. For fp32 (kPackedSize = 4) and (8192, 4096): 96 warps needed, 32 launched, rounds = 3, split 21/11, so input 0 gets 21 * 128 * 3 = 8064 of 8192 elements. (7168, 5120) splits 19/13 and input 1 is 128 short.
bf16/fp16 aren't safe either: they have enough slack at the sizes above, but not at every size. (7712, 16160) splits 10/22 warps × 3 rounds, so input 0 is 32 elements per row short; the installed wheel confirms this (output below). I also ran the launcher's split logic on the host for every pair of dims that are multiples of 32 up to 16384 (262,144 pairs per dtype): it leaves part of an input uncovered for 14,496 fp32 pairs and 2,176 bf16/fp16 pairs. For bf16/fp16 the error ratio can look small because the low-precision floor hides it, so the unwritten count is the real signal there.
# torch.ops.trtllm.group_rms_norm_base / _heuristic with two float32 inputs of last dims (8192, 4096) or (7168, 5120):
# the last 128 elements of each row of one input are never written and that input is scaled with a wrong RMS.
import torch
import tensorrt_llm # noqa: F401 (registers torch.ops.trtllm)
SENTINEL = 12345.0
torch.manual_seed(0)
def run(name, dims, dtype, batch=4, eps=1e-5):
op = getattr(torch.ops.trtllm, name)
xs = [torch.randn(batch, d, dtype=torch.float32).to(dtype).cuda() for d in dims]
ws = [(1.0 + 0.1 * torch.randn(d)).to(dtype).cuda() for d in dims]
outs = [torch.full_like(x, SENTINEL) for x in xs] # pre-filled so unwritten elements are visible
op(xs, outs, ws, eps, 0.0)
torch.cuda.synchronize()
for i, (x, w, y) in enumerate(zip(xs, ws, outs)):
xd = x.double()
ref = xd * torch.rsqrt(xd.square().mean(-1, keepdim=True) + eps) * w.double()
yt = (x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + eps) * w.float()).to(dtype)
unwritten = int((y == SENTINEL).sum().item()) // batch
written = y != SENTINEL
e_lib = (y.double() - ref)[written].abs().max().item()
e_torch = (yt.double() - ref).abs().max().item()
u = 2.0 ** -24 if dtype == torch.float32 else 2.0 ** -8
q = e_lib / max(e_torch, 2 * u * ref.abs().max().item())
print("%-24s %-8s dims=%s input %d: unwritten per row = %3d | written: max|err| = %.2e (torch fp32: %.2e), ratio = %.0f"
% (name, str(dtype).replace("torch.", ""), dims, i, unwritten, e_lib, e_torch, q))
run("group_rms_norm_base", (8192, 4096), torch.float32)
run("group_rms_norm_heuristic", (8192, 4096), torch.float32)
run("group_rms_norm_base", (7168, 5120), torch.float32)
run("group_rms_norm_base", (5120, 2560), torch.float32) # control
run("group_rms_norm_base", (8192, 4096), torch.bfloat16) # control
run("group_rms_norm_base", (160, 11936), torch.float32)
run("group_rms_norm_base", (7712, 16160), torch.bfloat16)
run("group_rms_norm_base", (7712, 16160), torch.float16)
Output (TensorRT-LLM 1.2.1 wheel, torch 2.9.1+cu130, RTX 5080 Laptop GPU sm_120; first 10 lines identical across 3 runs, last 6 lines from one run):
group_rms_norm_base float32 dims=(8192, 4096) input 0: unwritten per row = 128 | written: max|err| = 3.81e-02 (torch fp32: 3.38e-07), ratio = 69417
group_rms_norm_base float32 dims=(8192, 4096) input 1: unwritten per row = 0 | written: max|err| = 5.12e-07 (torch fp32: 5.12e-07), ratio = 1
group_rms_norm_heuristic float32 dims=(8192, 4096) input 0: unwritten per row = 128 | written: max|err| = 3.47e-02 (torch fp32: 4.46e-07), ratio = 69156
group_rms_norm_heuristic float32 dims=(8192, 4096) input 1: unwritten per row = 0 | written: max|err| = 3.49e-07 (torch fp32: 3.49e-07), ratio = 1
group_rms_norm_base float32 dims=(7168, 5120) input 0: unwritten per row = 0 | written: max|err| = 4.46e-07 (torch fp32: 4.46e-07), ratio = 1
group_rms_norm_base float32 dims=(7168, 5120) input 1: unwritten per row = 128 | written: max|err| = 5.64e-02 (torch fp32: 6.03e-07), ratio = 93542
group_rms_norm_base float32 dims=(5120, 2560) input 0: unwritten per row = 0 | written: max|err| = 4.17e-07 (torch fp32: 4.17e-07), ratio = 1
group_rms_norm_base float32 dims=(5120, 2560) input 1: unwritten per row = 0 | written: max|err| = 2.76e-07 (torch fp32: 2.76e-07), ratio = 1
group_rms_norm_base bfloat16 dims=(8192, 4096) input 0: unwritten per row = 0 | written: max|err| = 1.33e-02 (torch fp32: 1.33e-02), ratio = 0
group_rms_norm_base bfloat16 dims=(8192, 4096) input 1: unwritten per row = 0 | written: max|err| = 1.47e-02 (torch fp32: 1.47e-02), ratio = 0
group_rms_norm_base float32 dims=(160, 11936) input 0: unwritten per row = 0 | written: max|err| = 4.13e-07 (torch fp32: 4.13e-07), ratio = 1
group_rms_norm_base float32 dims=(160, 11936) input 1: unwritten per row = 32 | written: max|err| = 5.27e-03 (torch fp32: 3.43e-07), ratio = 9401
group_rms_norm_base bfloat16 dims=(7712, 16160) input 0: unwritten per row = 32 | written: max|err| = 2.62e-02 (torch fp32: 8.89e-03), ratio = 1
group_rms_norm_base bfloat16 dims=(7712, 16160) input 1: unwritten per row = 0 | written: max|err| = 1.48e-02 (torch fp32: 1.48e-02), ratio = 0
group_rms_norm_base float16 dims=(7712, 16160) input 0: unwritten per row = 32 | written: max|err| = 1.25e-02 (torch fp32: 1.11e-03), ratio = 0
group_rms_norm_base float16 dims=(7712, 16160) input 1: unwritten per row = 0 | written: max|err| = 1.37e-03 (torch fp32: 1.37e-03), ratio = 0
Suggested fix (host side only, in GroupRMSNormBaseKernel's launcher). Replace the proportional split with a per-input count:
- give each input
ceil(warps_needed_i / rounds)warps; - if the total exceeds the 32-warp budget, increase
roundsand recompute; - launch exactly the number of warps assigned.
On the host-side sweep this leaves 0 uncovered pairs for every dtype. I built v1.2.1's groupRmsNormKernels.cu with this change as a standalone torch extension (not a full TensorRT-LLM build); the unmodified build reproduces the wheel's output exactly. With the change, every case above writes every element and the fp32 cases give ratio 1. An adapted copy of test_group_rmn_norm.py with these shapes added passes 184/184 (12 fail without the change).
One thing to review: the launched warp count changes for many shapes, e.g. fp32 (8192, 4096) goes from 32 warps × 3 rounds to 24 × 4. I haven't measured performance. The C++ hunks of #20109 apply cleanly on top (git apply --check), so the two fixes are independent. Happy to share the diff or open a PR.