Skip to content

Fix per-group norm constant indexing in block-scale-factor epilogue stores (grouped/ptr-array GEMM) - #3392

Merged
hwu36 merged 1 commit into
NVIDIA:mainfrom
davidkny22:fix/sm120-grouped-norm-const
Jul 18, 2026
Merged

hwu36 merged 1 commit into
NVIDIA:mainfrom
davidkny22:fix/sm120-grouped-norm-const

Conversation

@davidkny22

@davidkny22 davidkny22 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In the block-scale-factor epilogue store visitors, the per-group norm constant is
never read on the grouped (ptr-array) path: every group's SFD tensor is encoded
with group 0's norm constant, regardless of the dNormConst batch stride.

This PR fixes the SM120 visitor (validated on hardware, reproducer below). The
same pattern exists in the SM100 visitor; a pattern-identical companion hunk is
included, compile-verified only.

Affected files:

  • include/cutlass/epilogue/fusion/sm120_visitor_store_tma_warpspecialized.hpp
    (Sm120BlockScaleFactorRowStore::get_consumer_store_callbacks and
    Sm120BlockScaleFactorColStore::get_consumer_store_callbacks)
  • include/cutlass/epilogue/fusion/sm100_visitor_store_tma_warpspecialized.hpp
    (the two analogous overloads; companion, compile-verified)

Mechanism

For ptr-array / grouped GEMM with a BlockScaleFactor per group, the visitor
selects the group's SFD pointer and then zeroes the batch coordinate, because
each group's SFD tensor has no batch mode:

if constexpr (!cute::is_same_v<UnderlyingElementBlockScaleFactor, ElementBlockScaleFactor>) {
  ptr_scale_factor = params_ptr->ptr_scale_factor[l];
  l = 0;
}

The norm-constant lookup executes about 20 lines later and reuses the zeroed l:

Tensor mNormConst = make_tensor(make_gmem_ptr(params_ptr->norm_constant_ptr),
                                make_layout(make_shape(M, N, L), params_ptr->norm_constant_stride));
ElementCompute norm_constant = mNormConst(_0{},_0{},l);

With dNormConst = {_0, _0, 1} every group reads norm_constant_ptr[0]; the
per-group stride has no effect. Group g's dequantized output is then mis-scaled
by exactly c_0 / c_g.

The fix captures the group index before it is zeroed and uses it for the
norm-constant lookup only. The SFD indexing keeps the zeroed l, which is
correct:

int l_norm_const = l;   // before the ptr-array zeroing
...
ElementCompute norm_constant = mNormConst(_0{},_0{},l_norm_const);

Per-group norm constants are used in MoE-style grouped GEMMs with FP4 output.
Each expert carries its own scaling constant.

No in-tree example exercises per-group norm constants: the SFD-generating
examples use a single shared constant (size-1 allocation, e.g.
examples/92_blackwell_moe_gemm), where the zeroed index is coincidentally
correct.

Reproducer

Attached standalone program (blockscaled_grouped_norm_const_repro.cu): a
4-group NVFP4 grouped GEMM (Sm120, KernelPtrArrayTmaWarpSpecializedPingpong,
LinCombBlockScaleFactor epilogue, FP4 D + ue4m3 SFD). All groups get identical
A/B inputs and unit SFA/SFB, but distinct norm constants c = {1.0, 1.2, 1.4, 1.6}.
Dequantizing each group's FP4+SFD output with its own constant is compared
against a host fp32 reference.

Before this change (main @ d01487d):

group 0: norm_const 1.00 | dequant vs reference: cos 0.995514 norm-ratio 0.999427  OK
group 1: norm_const 1.20 | dequant vs reference: cos 0.995514 norm-ratio 0.832856  WRONG  (re-dequant with group 0's constant gives norm-ratio 0.999427 -> group 0's constant was used)
group 2: norm_const 1.40 | dequant vs reference: cos 0.995514 norm-ratio 0.713877  WRONG
group 3: norm_const 1.60 | dequant vs reference: cos 0.995514 norm-ratio 0.624642  WRONG
BUG: per-group norm constants ignored on the grouped path

After this change (same machine, same tree plus patch):

group 0: norm_const 1.00 | dequant vs reference: cos 0.995514 norm-ratio 0.999427  OK
group 1: norm_const 1.20 | dequant vs reference: cos 0.995504 norm-ratio 1.000485  OK
group 2: norm_const 1.40 | dequant vs reference: cos 0.995494 norm-ratio 0.999907  OK
group 3: norm_const 1.60 | dequant vs reference: cos 0.995506 norm-ratio 1.000568  OK
PASS: every group's SFD encoded with its own norm constant

cos of about 0.9955 is the expected e2m1 plus e4m3 block-scale quantization
floor either way; the bug shows up in the norm-ratio column.

Testing done

Hardware: GB10 (DGX Spark), sm_121a. CUDA 13.1. Driver 580.95.05. Tree: main @ d01487d.

  • SM120: the reproducer above, fail-before and pass-after. sm_120 and sm_121
    share this epilogue path. The single-constant case (group 0) is unchanged.
  • SM100: compile-verified only, via
    examples/75_blackwell_grouped_gemm/75_blackwell_grouped_gemm_block_scaled.cu
    with the "Enable for SF Output" lines enabled for sm_100a, before and after
    the change. I do not have SM100 hardware. If you would rather take the SM100
    change through a separate PR, I can remove those hunks from this one.
  • Batched (non-ptr-array) path: unaffected. l_norm_const == l there by
    construction.
  • No in-tree test covers per-group norm constants. I can add a
    test/unit/gemm/device/ sm120 case during review if wanted.

cc @yzhaiustc

blockscaled_grouped_norm_const_repro.cu (standalone reproducer)
// Reproducer: per-group norm constants are ignored by the block-scale-factor
// epilogue on the SM120 ptr-array/grouped path.
//
// Setup: a grouped NVFP4 (nv_float4_t) GEMM with the LinCombBlockScaleFactor
// epilogue (FP4 D + ue4m3 SFD generation). Every group gets IDENTICAL A/B
// inputs (same device pointers) and unit SFA/SFB, but a DISTINCT norm constant
// c_g via norm_constant_ptr with per-group stride dNormConst = {_0,_0,1}.
//
// Expected: dequantizing group g's output with its own constant,
//   x = fp4(D_g) * e4m3(SFD_g) / c_g,
// recovers the same accumulator values for every group (all inputs are equal).
//
// Observed (bug): get_consumer_store_callbacks in
// include/cutlass/epilogue/fusion/sm120_visitor_store_tma_warpspecialized.hpp
// zeroes the group index `l` when selecting the per-group SFD pointer, and the
// norm-constant lookup mNormConst(_0,_0,l) executes AFTER the zeroing, so
// every group encodes with group 0's constant. Group g's dequant is then
// mis-scaled by exactly c_0 / c_g.
//
// Build (any SM120/SM121 part, CUDA 12.8+):
//   nvcc -O2 -std=c++17 --generate-code=arch=compute_120a,code=sm_120a \
//     --expt-relaxed-constexpr -I$CUTLASS/include -I$CUTLASS/tools/util/include \
//     blockscaled_grouped_norm_const_repro.cu -o repro -lcudart
//   (use compute_121a/sm_121a on GB10/DGX Spark)
// Run: ./repro          -> exits 1 and prints BUG on current main
//                       -> exits 0 and prints PASS with the fix applied

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>

#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"
#include "cutlass/bfloat16.h"
#include "cutlass/epilogue/collective/collective_builder.hpp"
#include "cutlass/gemm/collective/collective_builder.hpp"
#include "cutlass/gemm/device/gemm_universal_adapter.h"
#include "cutlass/gemm/dispatch_policy.hpp"
#include "cutlass/gemm/group_array_problem_shape.hpp"
#include "cutlass/gemm/kernel/gemm_universal.hpp"
#include "cutlass/detail/sm100_blockscaled_layout.hpp"
#include "cutlass/util/packed_stride.hpp"

using namespace cute;

#define CUDA_OK(x)                                                          \
  do {                                                                      \
    cudaError_t e_ = (x);                                                   \
    if (e_ != cudaSuccess) {                                                \
      printf("CUDA error %s at %s:%d\n", cudaGetErrorString(e_), __FILE__,  \
             __LINE__);                                                     \
      exit(2);                                                              \
    }                                                                       \
  } while (0)

#if defined(CUTLASS_ARCH_MMA_SM120_SUPPORTED) || defined(CUTLASS_ARCH_MMA_SM121_SUPPORTED)

using ProblemShapeType = cute::Shape<int, int, int>;
using ProblemShape = cutlass::gemm::GroupProblemShape<ProblemShapeType>;

using ElementInput = cutlass::float_e2m1_t;
using ElementA = cutlass::nv_float4_t<ElementInput>;
using ElementB = cutlass::nv_float4_t<ElementInput>;
using ElementC = cutlass::bfloat16_t;   // unused (beta = 0), needed by the builder
using ElementD = cutlass::float_e2m1_t;
using ElementSFD = cutlass::float_ue4m3_t;
using LayoutATag = cutlass::layout::RowMajor;
using LayoutBTag = cutlass::layout::ColumnMajor;
using LayoutCTag = cutlass::layout::RowMajor;
using ElementAccumulator = float;
using ArchTag = cutlass::arch::Sm120;
using OperatorClass = cutlass::arch::OpClassBlockScaledTensorOp;
using ThreadBlockShape = cute::Shape<cute::_128, cute::_128, cute::_128>;
using ClusterShape = cute::Shape<cute::_1, cute::_1, cute::_1>;
static constexpr int AlignmentA = 32;
static constexpr int AlignmentB = 32;
static constexpr int AlignmentC = 128 / cutlass::sizeof_bits<ElementC>::value;
static constexpr int AlignmentD = 128 / cutlass::sizeof_bits<ElementD>::value;
constexpr int OutputSFVectorSize = 16;

// FP4 output + ue4m3 block-scale-factor generation with a norm constant.
using FusionOp = cutlass::epilogue::fusion::LinCombBlockScaleFactor<
    OutputSFVectorSize, ElementD, float, ElementSFD, LayoutCTag, ElementC>;

struct GemmCfg {
  using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder<
      ArchTag, OperatorClass, ThreadBlockShape, ClusterShape,
      cutlass::epilogue::collective::EpilogueTileAuto, ElementAccumulator, ElementAccumulator,
      ElementC, LayoutCTag*, AlignmentC, ElementD, LayoutCTag*, AlignmentD,
      cutlass::epilogue::collective::EpilogueScheduleAuto, FusionOp>::CollectiveOp;
  using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder<
      ArchTag, OperatorClass, ElementA, LayoutATag*, AlignmentA, ElementB, LayoutBTag*, AlignmentB,
      ElementAccumulator, ThreadBlockShape, ClusterShape,
      cutlass::gemm::collective::StageCountAutoCarveout<static_cast<int>(
          sizeof(typename CollectiveEpilogue::SharedStorage))>,
      cutlass::gemm::KernelPtrArrayTmaWarpSpecializedPingpong>::CollectiveOp;
  using GemmKernel =
      cutlass::gemm::kernel::GemmUniversal<ProblemShape, CollectiveMainloop, CollectiveEpilogue>;
  using Gemm = cutlass::gemm::device::GemmUniversalAdapter<GemmKernel>;
};
using Gemm = GemmCfg::Gemm;

using SfdOutputCfg = cutlass::detail::Sm1xxBlockScaledOutputConfig<OutputSFVectorSize>;

static float fp4_decode(int nib) {
  static const float tab[16] = {0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f,
                                -0.f, -.5f, -1.f, -1.5f, -2.f, -3.f, -4.f, -6.f};
  return tab[nib & 0xF];
}

template <int Dummy>
int run(int argc, char** argv) {
  int G = 4, M = 256, N = 256, K = 256;
  printf("Grouped NVFP4 GEMM, FP4+SFD output, per-group norm constants\n");
  printf("G=%d M=%d N=%d K=%d (identical inputs for all groups)\n", G, M, N, K);

  cudaStream_t stream;
  CUDA_OK(cudaStreamCreate(&stream));

  using StrideA = typename Gemm::GemmKernel::InternalStrideA;
  using StrideB = typename Gemm::GemmKernel::InternalStrideB;
  using StrideD = typename Gemm::GemmKernel::InternalStrideD;
  using LayoutSFA = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFA;
  using LayoutSFB = typename Gemm::GemmKernel::CollectiveMainloop::InternalLayoutSFB;
  using BSC = typename Gemm::GemmKernel::CollectiveMainloop::Sm1xxBlkScaledConfig;
  using ElementSF = typename Gemm::GemmKernel::CollectiveMainloop::ElementSF;
  static_assert(std::is_same_v<ElementSF, cutlass::float_ue4m3_t>, "expected ue4m3 SF");

  const size_t bytesA = static_cast<size_t>(M) * K / 2;
  const size_t bytesB = static_cast<size_t>(N) * K / 2;
  const size_t bytesD = static_cast<size_t>(M) * N / 2;
  auto sfa_l = BSC::tile_atom_to_shape_SFA(cute::make_shape(M, N, K, 1));
  auto sfb_l = BSC::tile_atom_to_shape_SFB(cute::make_shape(M, N, K, 1));
  auto sfd_l = SfdOutputCfg::tile_atom_to_shape_SFD(cute::make_shape(M, N, K, 1));
  const size_t nSFA = static_cast<size_t>(cute::cosize(sfa_l));
  const size_t nSFB = static_cast<size_t>(cute::cosize(sfb_l));
  const size_t nSFD = static_cast<size_t>(cute::cosize(sfd_l));

  // ONE shared A/B (+unit SFA/SFB) used by every group; per-group D/SFD.
  void *dA, *dB, *dSFA, *dSFB;
  CUDA_OK(cudaMalloc(&dA, bytesA));
  CUDA_OK(cudaMalloc(&dB, bytesB));
  CUDA_OK(cudaMalloc(&dSFA, nSFA));
  CUDA_OK(cudaMalloc(&dSFB, nSFB));
  srand(12345);
  std::vector<unsigned char> hA(bytesA), hB(bytesB);
  for (auto& c : hA) c = rand() & 0xFF;
  for (auto& c : hB) c = rand() & 0xFF;
  CUDA_OK(cudaMemcpy(dA, hA.data(), bytesA, cudaMemcpyHostToDevice));
  CUDA_OK(cudaMemcpy(dB, hB.data(), bytesB, cudaMemcpyHostToDevice));
  // ue4m3 1.0 = 0x38: unit input scale factors so the host reference is exact.
  CUDA_OK(cudaMemset(dSFA, 0x38, nSFA));
  CUDA_OK(cudaMemset(dSFB, 0x38, nSFB));

  std::vector<void*> dD(G), dSFD(G);
  for (int g = 0; g < G; ++g) {
    CUDA_OK(cudaMalloc(&dD[g], bytesD));
    CUDA_OK(cudaMalloc(&dSFD[g], nSFD));
    CUDA_OK(cudaMemset(dD[g], 0, bytesD));
    CUDA_OK(cudaMemset(dSFD[g], 0, nSFD));
  }

  std::vector<ProblemShapeType> h_prob(G, ProblemShapeType(M, N, K));
  std::vector<StrideA> h_sa(G, cutlass::make_cute_packed_stride(StrideA{}, {M, K, 1}));
  std::vector<StrideB> h_sb(G, cutlass::make_cute_packed_stride(StrideB{}, {N, K, 1}));
  std::vector<StrideD> h_sd(G, cutlass::make_cute_packed_stride(StrideD{}, {M, N, 1}));
  std::vector<LayoutSFA> h_lsfa(G, LayoutSFA(sfa_l));
  std::vector<LayoutSFB> h_lsfb(G, LayoutSFB(sfb_l));
  std::vector<const ElementInput*> h_pA(G, reinterpret_cast<const ElementInput*>(dA));
  std::vector<const ElementInput*> h_pB(G, reinterpret_cast<const ElementInput*>(dB));
  std::vector<const ElementSF*> h_pSFA(G, reinterpret_cast<const ElementSF*>(dSFA));
  std::vector<const ElementSF*> h_pSFB(G, reinterpret_cast<const ElementSF*>(dSFB));

  auto to_dev = [](const void* h, size_t n) {
    void* d;
    CUDA_OK(cudaMalloc(&d, n));
    CUDA_OK(cudaMemcpy(d, h, n, cudaMemcpyHostToDevice));
    return d;
  };
  auto* prob_d = (ProblemShapeType*)to_dev(h_prob.data(), G * sizeof(ProblemShapeType));
  auto* pA_d = (const ElementInput**)to_dev(h_pA.data(), G * sizeof(void*));
  auto* pB_d = (const ElementInput**)to_dev(h_pB.data(), G * sizeof(void*));
  auto* pD_d = (ElementD**)to_dev(dD.data(), G * sizeof(void*));
  auto* pSFA_d = (const ElementSF**)to_dev(h_pSFA.data(), G * sizeof(void*));
  auto* pSFB_d = (const ElementSF**)to_dev(h_pSFB.data(), G * sizeof(void*));
  auto* pSFD_d = (ElementSFD**)to_dev(dSFD.data(), G * sizeof(void*));
  auto* sa_d = (StrideA*)to_dev(h_sa.data(), G * sizeof(StrideA));
  auto* sb_d = (StrideB*)to_dev(h_sb.data(), G * sizeof(StrideB));
  auto* sd_d = (StrideD*)to_dev(h_sd.data(), G * sizeof(StrideD));
  auto* lsfa_d = (LayoutSFA*)to_dev(h_lsfa.data(), G * sizeof(LayoutSFA));
  auto* lsfb_d = (LayoutSFB*)to_dev(h_lsfb.data(), G * sizeof(LayoutSFB));

  // DISTINCT per-group norm constants (gentle spread; e4m3 SF far from saturation).
  std::vector<float> h_norm(G);
  for (int g = 0; g < G; ++g) h_norm[g] = 1.0f + 0.2f * g;  // 1.0, 1.2, 1.4, 1.6
  float* normc_d = (float*)to_dev(h_norm.data(), G * sizeof(float));

  cutlass::KernelHardwareInfo hw =
      cutlass::KernelHardwareInfo::make_kernel_hardware_info<typename Gemm::GemmKernel>(0, 0);

  typename Gemm::Arguments args;
  decltype(args.epilogue.thread) fusion{};
  fusion.block_scale_factor_ptr = pSFD_d;
  fusion.norm_constant_ptr = normc_d;
  fusion.dNormConst = {cute::_0{}, cute::_0{}, 1};  // per-group stride
  args = typename Gemm::Arguments{cutlass::gemm::GemmUniversalMode::kGrouped,
                                  {G, prob_d, h_prob.data()},
                                  {pA_d, sa_d, pB_d, sb_d, pSFA_d, lsfa_d, pSFB_d, lsfb_d},
                                  {fusion, nullptr, sd_d, pD_d, sd_d},
                                  hw};
  Gemm gemm;
  auto st = gemm.can_implement(args);
  printf("can_implement: %s\n", cutlass::cutlassGetStatusString(st));
  if (st != cutlass::Status::kSuccess) return 2;
  void* ws_d;
  size_t ws = Gemm::get_workspace_size(args);
  CUDA_OK(cudaMalloc(&ws_d, ws ? ws : 4));
  st = gemm.initialize(args, ws_d, stream);
  if (st != cutlass::Status::kSuccess) {
    printf("initialize FAILED: %s\n", cutlass::cutlassGetStatusString(st));
    return 2;
  }
  st = gemm.run(stream);
  if (st != cutlass::Status::kSuccess) {
    printf("run FAILED: %s\n", cutlass::cutlassGetStatusString(st));
    return 2;
  }
  CUDA_OK(cudaDeviceSynchronize());
  CUDA_OK(cudaGetLastError());

  // Host reference accumulator (unit SFA/SFB make this exact in fp32).
  std::vector<float> ref(static_cast<size_t>(M) * N, 0.f);
  for (int i = 0; i < M; ++i) {
    for (int j = 0; j < N; ++j) {
      float acc = 0.f;
      for (int kk = 0; kk < K; ++kk) {
        const size_t ia = static_cast<size_t>(i) * K + kk;   // A row-major
        const size_t ib = static_cast<size_t>(j) * K + kk;   // B col-major (TN)
        const int na = (hA[ia / 2] >> ((ia % 2) * 4)) & 0xF;
        const int nb = (hB[ib / 2] >> ((ib % 2) * 4)) & 0xF;
        acc += fp4_decode(na) * fp4_decode(nb);
      }
      ref[static_cast<size_t>(i) * N + j] = acc;
    }
  }

  // Dequantize each group with ITS OWN constant and compare to the reference.
  std::vector<unsigned char> hD(bytesD), hSFD(nSFD);
  bool pass = true;
  for (int g = 0; g < G; ++g) {
    CUDA_OK(cudaMemcpy(hD.data(), dD[g], bytesD, cudaMemcpyDeviceToHost));
    CUDA_OK(cudaMemcpy(hSFD.data(), dSFD[g], nSFD, cudaMemcpyDeviceToHost));
    Tensor tSFD = make_tensor(reinterpret_cast<cutlass::float_ue4m3_t*>(hSFD.data()), sfd_l);
    double dot = 0, nx = 0, nr = 0;
    for (int i = 0; i < M; ++i) {
      for (int j = 0; j < N; ++j) {
        const size_t idx = static_cast<size_t>(i) * N + j;
        const int nib = (hD[idx / 2] >> ((idx % 2) * 4)) & 0xF;
        const float sf = static_cast<float>(tSFD(i, j, 0));
        const float x = fp4_decode(nib) * sf / h_norm[g];  // dequant, own constant
        const float r = ref[idx];
        dot += (double)x * r;
        nx += (double)x * x;
        nr += (double)r * r;
      }
    }
    const double cos = dot / (sqrt(nx) * sqrt(nr) + 1e-30);
    const double ratio = sqrt(nx) / (sqrt(nr) + 1e-30);
    const bool ok = cos > 0.99 && fabs(ratio - 1.0) < 0.05;
    printf("group %d: norm_const %.2f | dequant vs reference: cos %.6f norm-ratio %.6f  %s",
           g, h_norm[g], cos, ratio, ok ? "OK" : "WRONG");
    if (!ok) {
      // Diagnose: does group 0's constant explain the output instead?
      const double ratio_c0 = ratio * h_norm[g] / h_norm[0];
      printf("  (re-dequant with group 0's constant gives norm-ratio %.6f%s)",
             ratio_c0, fabs(ratio_c0 - 1.0) < 0.05 ? " -> group 0's constant was used" : "");
      pass = false;
    }
    printf("\n");
  }
  if (pass) {
    printf("PASS: every group's SFD encoded with its own norm constant\n");
    return 0;
  }
  printf("BUG: per-group norm constants ignored on the grouped path "
         "(all groups encoded with norm constant 0)\n");
  return 1;
}

int main(int argc, char** argv) { return run<0>(argc, argv); }
#else
int main() {
  printf("This reproducer requires SM120/SM121 support (CUTLASS_ARCH_MMA_SM120_SUPPORTED)\n");
  return 2;
}
#endif

…tores

For ptr-array/grouped GEMM the batch coordinate l is zeroed after
selecting the per-group SFD pointer, but the norm constant lookup
reuses l afterwards, so every group encodes with group 0's norm
constant. Capture the group index before the zeroing and use it for
the norm constant lookup.

Signed-off-by: David Kogan <[email protected]>
@yzhaiustc

Copy link
Copy Markdown
Collaborator

the fix makes sense to me. + @hwu36

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants