TensorRT-LLM icon indicating copy to clipboard operation
TensorRT-LLM copied to clipboard

[Bug] calculate_nvfp4_global_scale returns wrong per-token scales for hidden sizes above 8192 that are not multiples of 8192

Open builtin-pb opened this issue 1 month ago • 2 comments

Summary. torch.ops.trtllm.calculate_nvfp4_global_scale returns wrong scales for many tokens when the hidden size is above 8192 and not a multiple of 8192, once a CTA handles more than one token (for a 2-D input, m above the SM count). Its kernel calls blockReduceMaxV2, which contains a __syncthreads(), inside a per-thread loop whose iteration count differs across threads, so one token's reduction gets joined with other tokens'. We suggest reducing once per token, after the loop, followed by a barrier.

System Info

  • TensorRT-LLM 1.2.1 wheel, torch 2.9.1+cu130, A100 80GB PCIe (driver 610.57).
  • The kernel is unchanged on main b031dbe: cpp/tensorrt_llm/kernels/quantization.cu and cpp/tensorrt_llm/common/reduceKernelUtils.cuh.

Who can help?

No response

Information

  • [ ] The official example scripts
  • [x] My own modified scripts

Tasks

  • [ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [x] My own task or dataset (give details below)

Reproduction

torch.ops.trtllm.calculate_nvfp4_global_scale(x, None) on a bf16 x of shape [m, n] should return 448 * 6 / max|x[i]| for each token. A minimal script:

import torch
import tensorrt_llm  # registers torch.ops.trtllm

m = 512
torch.manual_seed(0)
rows = torch.arange(m)
amp = 2.0 ** ((rows * 5) % 11 - 3) * (1 + (rows * 3 % 8) / 8)  # per-token maximum
for n in (12288, 8192):
    x = (torch.rand(m, n) - 0.5) * amp[:, None]
    x[rows, torch.randint(n, (m,))] = amp
    x = x.bfloat16().cuda()
    ref = 2688.0 / x.double().abs().amax(1, keepdim=True)
    got = torch.ops.trtllm.calculate_nvfp4_global_scale(x, None)
    bad = ((got.double() - ref).abs() > 1e-4 + 2e-6 * ref.abs()).sum().item()
    print(f"n={n}: {bad} of {m} tokens have a wrong global scale")

On an A100 (SXM4 80GB) it printed:

n=12288: 309 of 512 tokens have a wrong global scale
n=8192: 0 of 512 tokens have a wrong global scale

Results with the 1.2.1 wheel:

  • each call was checked in full against a float64 reference;
  • a call counts as wrong if any token's scale is non-finite or off by more than 1e-4 + 2e-6 · |ref|.
x shape (bf16) wrong calls wrong tokens in sampled calls
[512, 12288] 914302 / 914302 301–318 of 512
[256, 28672] 920766 / 920766 101–114 of 256
[512, 8192] 0 / 924832
[1024, 4096] 0 / 914518

For example, in the first call at [512, 12288], token 3 got 28.0 instead of 42.0.

Expected behavior

Each token's global scale is 2688 / max|x[i]|, for any n the operator accepts. The launcher checks only n % 256 == 0.

actual behavior

Cause

The loop in computePerTokenGlobalScaleForFP4QuantizationKernel (quantization.cu:351–374), where getMaxAbs calls blockReduceMaxV2:

for (int vecIdx = threadIdx.x; vecIdx < n / ElemsPerVec; vecIdx += blockDim.x)
{
    float4 vec = reinterpret_cast<float4 const*>(input + tokenIdx * n)[vecIdx];
    float maxAbsVal = getMaxAbs<T>(vec);   // blockReduceMaxV2 -> __syncthreads()
    perTokenMaxAbsVal = cuda_max(perTokenMaxAbsVal, maxAbsVal);
}

The launcher uses blockDim.x = min(n / 8, 1024). When n / 8 is above 1024 and not a multiple of it, threads with threadIdx.x < (n / 8) % 1024 run one more iteration per token than the others. CUDA requires a __syncthreads() in conditional code to be reached by all threads of the block, and here it is not.

The warps with fewer iterations run ahead. Each barrier instance then joins warp 0's reduction of one token with the other warps' reductions of later tokens handled by the same CTA. After those warps exit, it joins with the values they left in shared memory. The reduced maximum mixes tokens. In a standalone copy of the kernel, run without Compute Sanitizer, every wrong value matched the one predicted from this pairing.

A second, smaller problem: blockReduceMaxV2 has no barrier between warp 0's read of shared[lane] (reduceKernelUtils.cuh:281) and the next call's write of shared[wid] (line 269). On the standalone copy, Compute Sanitizer racecheck reports hazards between these two lines at every shape we tested, including n = 4096 and 8192. Under racecheck or synccheck, those two shapes also returned wrong scales (one launch each), though they were correct in every plain run.

additional notes

Suggested fix

@@ -343,7 +343,6 @@ __device__ float getMaxAbs(float4& vec)
     {
         absMaxVal = static_cast<float>(cuda_max(absMaxVec.x, absMaxVec.y));
     }
-    tensorrt_llm::common::blockReduceMaxV2<float, 1>(&absMaxVal);
     return absMaxVal;
 }
 
@@ -365,6 +364,11 @@ __global__ void computePerTokenGlobalScaleForFP4QuantizationKernel(
             float maxAbsVal = getMaxAbs<T>(vec);
             perTokenMaxAbsVal = cuda_max(perTokenMaxAbsVal, maxAbsVal);
         }
+        // Reduce once per token, outside the per-thread loop: threads make different numbers of loop iterations
+        // when n / ElemsPerVec is not a multiple of blockDim.x.
+        tensorrt_llm::common::blockReduceMaxV2<float, 1>(&perTokenMaxAbsVal);
+        // blockReduceMaxV2's shared slots are rewritten by the next token's reduction.
+        __syncthreads();
         float globalScaleVal = 448.f * 6.f / perTokenMaxAbsVal;
         if (threadIdx.x == 0)
         {

A standalone copy of the kernel with the equivalent change gave no wrong scales on A100 and A40, and is clean under racecheck and synccheck.

Scope

Callers in the tree:

  • the opt-in NVFP4 low-precision MoE combine in nccl_ep.py:460 (use_low_precision_moe_combine, default off). It requires NVFP4 and a hidden size that is a multiple of 512, so sizes such as 10240 or 12288 can reach it. Its input is [ep_size, max_tokens_per_rank, hidden], so a CTA handles several tokens once a rank receives more than SMs / ep_size tokens;
  • deep_ep_low_latency.py:386, which runs this combine only for hidden sizes 4096, 6144 and 7168, and is not affected;
  • visual_gen/.../cute_dsl/fmha.py:626, which caps rows at 8192 and is not affected; its comment calls 8192 "the largest dimension compatible with the same routine".

The operator's unit test (test_fp4_calculate_global_scale.py) uses only hidden size 7168.

The unequal barrier counts follow from n alone, so they occur on every architecture. We have not tested Hopper or Blackwell.

builtin-pb avatar Oct 08 '26 05:10 builtin-pb

Independent repro and a fix proposal for this one.

Setup: RTX 5090 (sm_120), CUDA 13.0, standalone harness built from current main (edfc6672) with the kernel, getMaxAbs and blockReduceMaxV2 code verbatim, plus a fixed variant. Result: confirmed, and the exposed range is wider than the title - there are two independent defects here.

D1 - divergent block collective. getMaxAbs() calls blockReduceMaxV2(), which contains __syncthreads(), from inside the per-thread vector loop. With blockDim = min(n/8, 1024) for bf16, per-thread trip counts are uniform only when n <= 8192 or n % 8192 == 0. Threads that finish early advance to the next token and enter the collective again, mispairing barriers and mixing data across tokens. The reported n=12288 case: 295-323 wrong of 512 over 50 runs here (A100 report: 301-318; consistent across machines).

D2 - shared-buffer reuse in the same helper. blockReduceMaxV2() stages warp maxima in a function-local static shared buffer, and warp 0 reads them with no barrier after those reads; the next call's lane-0 stores can overwrite slots while warp 0 is still reading. So uniform shapes fail as well: n=16384 (exactly 2 iterations for every thread) measured 108-171 wrong of 512 over 300 runs, while n=8192 (1 iteration) was clean over 300 runs. Measured criterion: all tested n <= 8192 clean; all tested n >= 16384 affected (11008, 12288, 16384, 24576, 28672, 32768), non-multiple shapes hit hardest.

Discriminating experiment: adding a trailing __syncthreads() inside blockReduceMaxV2 (experiment build only) makes 16384 and 24576 fully clean (0/0/0, 50 runs each) but leaves 12288 broken (256-273 wrong of 512) - the two defects are independent. Hoisting the collective out of getMaxAbs to once per token, uniformly reached by all threads, clears all of it: 0/0/0 on 11 shapes (4096, 8192, 11008, 12288, 16384, 24576, 28672, 32768 plus three gridDim.y = m variants), 50 runs each, plus 300-run stability at 12288 and 16384; max relative error 4.5e-08 against an fp64 reference.

Error shape (test data: uniform noise plus one planted per-token maximum): for n=16384 the wrong scales are exactly 2x the reference - the planted maximum is lost and the result falls back to the noise floor at half amplitude. For n=12288 the error goes both ways, including scales about 7x and 14x too small when a larger amplitude from another token leaks through the mismatched barrier

  • that direction pushes values outside the representable FP4 range, which is the more dangerous failure.

Proposed minimal change (getMaxAbs has a single call site in this file):

template <typename T>
__device__ float getMaxAbs(float4& vec)
{
    ... unchanged ...
    return absMaxVal;      // blockReduceMaxV2 call removed from here
}

// in the kernel, after the vector loop:
tensorrt_llm::common::blockReduceMaxV2<float, 1>(&perTokenMaxAbsVal);
float globalScaleVal = 448.f * 6.f / perTokenMaxAbsVal;
if (threadIdx.x == 0) { globalScale[tokenIdx] = globalScaleVal; }

Only thread 0 writes globalScale, and thread 0's value is the block maximum under both layouts (in blockReduceMaxV2, only warp 0 ends up with a meaningful value), so the write semantics are unchanged.

A trailing barrier inside blockReduceMaxV2 would close D2 as well, but by itself it does not fix D1 (measured above), and I have not audited its other call sites (kernels/unfusedAttentionKernels.cu has one), so I kept the change inside the kernel.

Is there any in-flight work on this? If not, I can send a PR with a regression test for n=12288 and n=16384 in tests/unittest/_torch/thop/parallel/test_fp4_calculate_global_scale.py.

peter941221 avatar Oct 09 '26 01:10 peter941221

Sent PR #20014 with the fix and the two regression cases: https://github.com/NVIDIA/TensorRT-LLM/pull/20014

Marked ready for review; happy to adjust or drop it if there is in-flight work on this kernel.

peter941221 avatar Oct 09 '26 02:10 peter941221