Megatron-LM icon indicating copy to clipboard operation
Megatron-LM copied to clipboard

[BUG] BF16 Mamba/GDP multi-token decode and rollback states differ from serial decode

Open Waterpine opened this issue 2 months ago • 1 comments

Describe the bug

With BF16 persistent recurrent state, production Mamba and GDP multi-token decode produce different state snapshots from normal one-token-at-a-time decode of the same projected inputs. Restoring the accepted snapshot with mamba_state_selective_copy preserves this difference, and the next decode output differs even when both paths receive identical next-step inputs.

The first input matches exactly; differences begin at the second input. Convolution states match throughout. FP32 recurrent-state controls match exactly for both mixers.

Reproduced on unmodified current main, ef8cd10b8e34a94c9ad7452e7851f58337f353a0, on October 4, 2026 UTC (October 3 PDT). The checkout was clean before and after the run.

@NVIDIA/mcore-oncall

Steps/Code to reproduce bug

  1. Use a clean checkout at the commit above in the Megatron GPU development environment, with the normal Mamba/GDP test dependencies installed (PyTorch, Triton, Transformer Engine, Mamba-SSM, causal-conv1d and FLA).
  2. Save the self-contained code below as repro_n1_bf16_ssm_state.py in the repository root.
  3. Run with one GPU worker:
export NVTE_ALLOW_NONDETERMINISTIC_ALGO=0 NCCL_ALGO=Ring
export CUBLAS_WORKSPACE_CONFIG=:4096:8 TRITON_CACHE_AUTOTUNING=0
export MAMBA_DETERMINISTIC=1
uv run --no-sync python -m torch.distributed.run --standalone --nproc-per-node=1 \
  repro_n1_bf16_ssm_state.py

The script compares one four-input decode with four single-input decodes, using identical initial state and identical projected inputs. It then calls the production rollback-copy kernel with accepted draft counts [0, 3, 1] in request slots [4, 0, 3], and compares the next decode outputs. Snapshot index K contains the mandatory base input plus K accepted drafts; zero accepted drafts therefore selects snapshot zero.

# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
"""Compare production multi-token SSM snapshots/rollback with serial decode.

Run from an unmodified Megatron-LM checkout using torch.distributed.run, TP=PP=1.
All projected inputs, initial states, slots, and retained prefixes are identical.
Exit 2 records a reproduced mismatch; exit 0 means all comparisons passed.
"""

import json
import os

import torch

from megatron.core.inference.text_generation_controllers.mtp_utils_triton import (
    mamba_state_selective_copy,
)
from megatron.core.models.hybrid.hybrid_layer_specs import (
    gated_delta_product_stack_spec,
    hybrid_stack_spec,
)
from megatron.core.process_groups_config import ProcessGroupCollection
from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
from megatron.core.transformer import TransformerConfig
from tests.unit_tests.test_utilities import Utils


def make_mixer(kind):
    torch.manual_seed(123)
    model_parallel_cuda_manual_seed(123)
    config = TransformerConfig(
        hidden_size=256,
        num_layers=1,
        num_attention_heads=8,
        use_cpu_initialization=True,
        params_dtype=torch.bfloat16,
        bf16=True,
        normalization="RMSNorm",
        mamba_num_heads=8,
        mamba_head_dim=32,
        mamba_num_groups=2,
        mamba_state_dim=32,
        gdp_num_householder=3,
        is_hybrid_model=True,
    )
    stack = gated_delta_product_stack_spec if kind == "gdp" else hybrid_stack_spec
    spec = stack.submodules.mamba_layer.submodules.mixer
    groups = ProcessGroupCollection.use_mpu_process_groups(required_pgs=["tp", "cp"])
    return (
        spec.module(config, spec.submodules, 256, layer_number=1, pg_collection=groups)
        .cuda()
        .eval()
    )


def max_error(a, b):
    return float((a.float() - b.float()).abs().max())


def compare(mixer, dtype):
    torch.manual_seed(77)
    conv_shape, ssm_shape = mixer.mamba_state_shapes_per_request()
    conv = torch.randn(6, *conv_shape, device="cuda", dtype=torch.bfloat16)
    state = torch.randn(6, *ssm_shape, device="cuda", dtype=torch.float32).to(dtype)
    serial_conv, serial_state = conv.clone(), state.clone()
    slots = torch.tensor([4, 0, 3], device="cuda", dtype=torch.int32)
    projected = torch.randn(
        3, 4, mixer.in_proj.weight.shape[0], device="cuda", dtype=torch.bfloat16
    )
    conv_snapshots = torch.empty(6, 4, *conv_shape, device="cuda", dtype=conv.dtype)
    state_snapshots = torch.empty(6, 4, *ssm_shape, device="cuda", dtype=dtype)
    multi_output = mixer.ssm_decode(
        projected, conv, state, slots, conv_snapshots, state_snapshots
    )
    saved, steps = [], []
    for step in range(4):
        output = mixer.ssm_decode(
            projected[:, step : step + 1].contiguous(), serial_conv, serial_state, slots
        )
        saved.append((serial_conv.clone(), serial_state.clone()))
        steps.append(
            {
                "step": step,
                "output_error": max_error(multi_output[:, step : step + 1], output),
                "state_error": max_error(
                    state_snapshots[slots.long(), step], serial_state[slots.long()]
                ),
                "conv_error": max_error(
                    conv_snapshots[slots.long(), step], serial_conv[slots.long()]
                ),
            }
        )
    # Four verifier inputs = one mandatory base input + three proposed drafts.
    # K accepted drafts selects snapshot K, after the base and those K drafts.
    accepted = torch.tensor([0, 3, 1], device="cuda", dtype=torch.int64)
    for snapshots, live in ((conv_snapshots, conv), (state_snapshots, state)):
        mamba_state_selective_copy(
            snapshots.unsqueeze(0),
            live.unsqueeze(0),
            torch.zeros(3, device="cuda", dtype=torch.int32),
            slots,
            accepted,
            1,
        )
    expected_conv, expected_state = conv.clone(), state.clone()
    for row, depth in enumerate(accepted.tolist()):
        slot = int(slots[row])
        expected_conv[slot] = saved[depth][0][slot]
        expected_state[slot] = saved[depth][1][slot]
    state_error = max_error(state, expected_state)
    conv_error = max_error(conv, expected_conv)
    next_input = torch.randn_like(projected[:, :1])
    next_output = mixer.ssm_decode(next_input, conv, state, slots)
    reference_output = mixer.ssm_decode(
        next_input, expected_conv, expected_state, slots
    )
    return {
        "state_dtype": str(dtype),
        "steps": steps,
        "accepted_drafts": accepted.tolist(),
        "request_slots": slots.tolist(),
        "rollback_state_error": state_error,
        "rollback_conv_error": conv_error,
        "next_output_error": max_error(next_output, reference_output),
    }


def main():
    torch.cuda.set_device(int(os.environ.get("LOCAL_RANK", 0)))
    Utils.initialize_model_parallel(1, 1)
    results = []
    try:
        with torch.inference_mode():
            for kind in ("mamba", "gdp"):
                mixer = make_mixer(kind)
                for dtype in (torch.float32, torch.bfloat16):
                    results.append({"mixer": kind, **compare(mixer, dtype)})
    finally:
        Utils.destroy_model_parallel()
    mismatch = any(
        row["rollback_state_error"] != 0
        or row["rollback_conv_error"] != 0
        or row["next_output_error"] > 1e-6
        or any(
            step["state_error"] != 0 or step["output_error"] > 1e-6
            for step in row["steps"]
        )
        for row in results
    )
    print(
        json.dumps(
            {"status": "MISMATCH" if mismatch else "PASS", "results": results}, indent=2
        )
    )
    raise SystemExit(2 if mismatch else 0)


if __name__ == "__main__":
    main()

Observed maximum absolute differences on the clean checkout:

Mixer Recurrent-state dtype Per-input snapshot state State after rollback Next decode output
Mamba FP32 0 0 0
Mamba BF16 0.03125 0.03125 0.03125
GDP FP32 0 0 0
GDP BF16 0.03125 0.015625 0.04296875

All convolution-state differences are zero. The script prints MISMATCH and exits nonzero. Under torch.distributed.run, its deliberate child exit code 2 is wrapped in ChildFailedError; the JSON above that wrapper is the measured comparison result.

Expected behavior

For the same initial state, projected inputs, and persistent-state dtype, multi-token verification should follow the same recurrent-state semantics as ordinary serial decode. Every accepted-prefix snapshot, including a snapshot restored after partial rejection, should represent the state obtained by serially consuming that same retained prefix.

If BF16 state cannot provide that equivalence, the speculative-inference configuration should explicitly require FP32 state instead of accepting a configuration whose state arithmetic changes when speculation is enabled.

Additional context

  • This reproduction exercises actual mixer decode and rollback kernels. It uses no checkpoint, attention layer, CUDA graph, prefix cache, or chunked prefill, and requires no production patch.
  • BF16 state is an accepted configuration: MambaInferenceStateConfig.from_model defaults recurrent state to model parameter dtype unless explicitly overridden or batch-invariant mode requires FP32.
  • Serial BF16 decode writes the state after each input and reloads that rounded state for the next input. The multi-token kernels retain an FP32 accumulator across inputs; writing a BF16 snapshot does not round the accumulator used for the next input. For GDP, a complete input includes all of its Householder updates.
  • The rollback kernel selects the intended snapshot in this reproduction. The inconsistency originates in how that snapshot was computed.
  • Environment: NVIDIA GB300, ARM64 Python 3.12.3, CUDA 13.4, PyTorch 2.14.0a0+4fdf77b940.nv26.08, Transformer Engine 2.19.0+5e52befd, Triton 3.8.0+git4c7e62b7.nv26.8, Mamba-SSM 2.3.2.post1, causal-conv1d 1.6.2.post1, FLA 0.5.1; TP=1, PP=1.
  • Relevant source: Mamba recurrence, GDP recurrence, rollback copy.
  • Related numerical-parity work is tracked in #7831. This report isolates BF16 serial-versus-speculative recurrent-state arithmetic; it does not establish the same cause as the attention/graph discrepancy in #7845.

Waterpine avatar Oct 04 '26 02:10 Waterpine

Reproduced on main @ 97b50bdd9 (single GPU; TE-linear-free mixer spec — the projections are immaterial since the script drives ssm_decode with pre-projected inputs).

Root cause

The multi-token decode kernels keep the recurrent state in an fp32 accumulator across all tokens of the step, and only round when a value is stored:

  • _selective_scan_update_kernel (megatron/core/ssm/ops/mamba2/mamba_ssm.py): state is loaded to fp32 once, updated for every token of seqlen, and the per-token snapshot + the final store each round the stored copy only — the accumulator keeps the unrounded value.
  • fused_recurrent_gated_delta_rule_fwd_kernel (megatron/core/ssm/ops/gdp/fused_recurrent.py): same shape: b_h accumulates all T recurrence steps (all draft tokens x Householder steps) in fp32; snapshots at (i_t + 1) % STEPS_PER_TOKEN == 0 and the final store round only what they write.

Serial decode — one ssm_decode per token — rounds the state to the cache dtype once per token, and the next token consumes the rounded state. The snapshot contract ("snapshot[i] == the state a serial decode would hold after token i, so rollback restores exactly that prefix") therefore breaks in BF16: snapshot[i] holds round(fp32 chain), while a serial chain after i tokens holds round(...round(round(fp32 step))) — the drift compounds per token, which is why the first input matches and every later one does not, and why FP32 (round = identity) is exact.

Symptoms match the report exactly: FP32 controls equal throughout, BF16 diverges from the second input on, convolution states equal in every arm.

Fix + verification

Round the accumulator itself at each token boundary. Then snapshots, the final state and every later token's output are bit-identical to serial decode; FP32 is a no-op round-trip and single-token decode is unchanged bit for bit.

  • Issue reproducer (both mixers x {FP32, BF16}): MISMATCH -> PASS, all snapshot / rollback / next-output errors 0.0 (one FP32 output delta of 1.2e-07, under the script's 1e-6 gate).
  • GDP + Mamba2 kernel suites: 40/40 pass, including two new BF16 snapshot-contract tests. Both replay the batch one token per launch and compare bitwise; without the fix the four BF16 cases fail on draft token 1 while the four FP32 ones pass — the existing tests missed this because they only ever use an FP32 state cache, where the missing rounding is a no-op.

Opened #9401 with the fix and the regression tests.

YYuJLiu avatar Nov 13 '26 02:11 YYuJLiu