Skip to content

[None][fix] Stabilize Mamba replay state update - #14509

Merged
sunnyqgg merged 6 commits into
NVIDIA:mainfrom
sunnyqgg:mamba_replay_stabilize_pr_0524
Jun 1, 2026
Merged

[None][fix] Stabilize Mamba replay state update#14509
sunnyqgg merged 6 commits into
NVIDIA:mainfrom
sunnyqgg:mamba_replay_stabilize_pr_0524

Conversation

@sunnyqgg

@sunnyqgg sunnyqgg commented May 25, 2026

Copy link
Copy Markdown
Collaborator

Description

This PR stabilizes the Mamba replay selective state-update path for MTP decoding with stochastic rounding and fp16 SSM cache.

The failure mode seen in long/high-concurrency replay runs was that stale or non-finite replay/cache values could poison the SSM state, then propagate through downstream layers into <unk>/token-id-0 collapse or over-generation. The fix keeps replay enabled and makes the replay path more robust instead of falling back to the non-replay path.

Key changes:

  • Sanitize/clamp replay kernel intermediates, cached dt / dA_cumsum, SSM state, and SSM output before they can persist or escape the kernel.
  • Use fp32 dot products for replay CB/state/output accumulation to reduce overflow sensitivity.
  • Reset replay double buffers, SSM/conv state stripes, PNAT, buffer index, and per-slot Philox seeds when context cache slots are reused.
  • Use per-cache-slot Philox seeds for replay stochastic rounding so CUDA graph replay gets fresh draws while remaining indexed by the actual cache slot.

Test Coverage

  • python3 -m py_compile tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py
  • git diff --check refs/tmp/nvidia_main_latest...HEAD -- tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py
  • pre-commit run --files tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py
  • Agent-flow B300 validation with replay enabled at concurrency 32: replay-on full SciCode 80-sample runs reached 80/80 completed rows without <unk>/token-id-0 collapse; replay-off remained clean as a control.

PR Checklist

  • PR description clearly explains what and why.
  • PR follows TRT-LLM coding guidelines to the best of my knowledge.
  • Test coverage is listed above.
  • No new dependencies.
  • CODEOWNERS update not needed.
  • Documentation update not needed.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced numerical stability in Mamba inference by sanitizing NaN/Inf values and adding protective clamping during state updates.
    • Improved consistency of stochastic rounding in speculative decoding replay paths.
  • Improvements

    • Refined random seed management for speculative Mamba state replay to prevent stale randomness across slot reuse.
    • Added runtime validation for random seed parameters in cache operations.

Review Change Stack

Signed-off-by: qgai <qgai@nvidia.com>
@sunnyqgg
sunnyqgg requested review from a team as code owners May 25, 2026 02:16

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50125 [ run ] triggered by Bot. Commit: c7f3249 Link to invocation

@coderabbitai

coderabbitai Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR hardens the Mamba speculative replay path against numerical instability by introducing per-slot stochastic random seeding and defensive sanitization throughout the Triton replay kernel. It allocates and manages a new mamba_ssm_rand_seed tensor across cache manager lifecycle, upgrades kernel precision and masks to prevent NaN/Inf propagation, and integrates seed selection in the mixer for stochastic rounding.

Changes

Mamba Speculative Replay with Hardened Randomization

Layer / File(s) Summary
Per-slot random seed cache state management
tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py
Introduces mamba_ssm_rand_seed as a new optional shared tensor field in SpeculativeState, allocates and resets it per-slot in PythonMambaCacheManager and CppMambaHybridCacheManager, threads it through mamba_layer_cache to the kernel, and clears it on shutdown to release references.
Replay kernel NaN/Inf sanitization and precision upgrades
tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py
Sanitizes intermediate tensors (dt, A, state, dA_cumsum, coeff, outputs) and clamps to prevent overflow, upgrades raw_CB and state/output dot products to float32 with ieee precision, updates token masking to use valid ranges, expands rand_seed docstring, and adds runtime validation for dtype, shape, and length.
Mixer stochastic rounding seed selection
tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py
Selects rand_seed from layer_cache.mamba_ssm_rand_seed with in-place increment when replay is enabled; falls back to torch.randint for flashinfer path. Added inline comments clarifying replay SSM-cache semantics.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • NVIDIA/TensorRT-LLM#14471: Both PRs modify the Mamba replay execution flow in mamba2_mixer.py and control how speculative replay is invoked; this PR's rand_seed seeding is directly coupled with how replay is triggered and parameterized.

Suggested reviewers

  • symphonylyh
  • danielafrimi
  • lancelly
  • Tabrizian
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: stabilizing the Mamba replay state update mechanism for improved robustness.
Description check ✅ Passed The description comprehensively explains the issue, solution, and test coverage, following the template structure with detailed technical context.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py (1)

1399-1403: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't clear restored conv/SSM snapshots for every context slot.

Lines 1399-1400 can already queue recurrent-state restores for prefix-cache hits / chunked-prefill contexts. Lines 1431-1434 then zero those same live state stripes unconditionally, so prefill loses the restored initial state and falls back to all-zero conv/SSM state. Keep resetting the replay scratch buffers, but gate the live-state clear to truly fresh slots only.

Also applies to: 1431-1434

🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py (1)

545-547: ⚡ Quick win

Avoid a host sync in the slot-allocation loop.

Lines 546-547 allocate a CPU tensor and call .item(), which forces a sync for every newly assigned request slot. Seed the selected CUDA element in place instead, or batch-generate seeds outside the loop.

♻️ Suggested change
                 if self.mamba_cache.mamba_ssm_rand_seed is not None:
-                    self.mamba_cache.mamba_ssm_rand_seed[block] = torch.randint(
-                        1, 2**62, (1, ), dtype=torch.int64).item()
+                    self.mamba_cache.mamba_ssm_rand_seed[block].random_(
+                        1, 2**62
+                    )

Based on learnings: "In files under tensorrt_llm/_torch/pyexecutor, avoid accessing torch.Tensor objects inside for-loops when iterating over requests."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py` around lines 545 -
547, The loop currently calls torch.randint(...).item() and stores a Python int
into self.mamba_cache.mamba_ssm_rand_seed[block], causing a host sync for each
slot; instead generate seeds on the tensor device and write them in-place (or
batch-generate them before the loop). Concretely, replace the per-iteration
.item() pattern for self.mamba_cache.mamba_ssm_rand_seed (referenced as
mamba_cache.mamba_ssm_rand_seed and index variable block) with a device-aware
assignment using torch.randint(...,
device=self.mamba_cache.mamba_ssm_rand_seed.device,
dtype=self.mamba_cache.mamba_ssm_rand_seed.dtype) and assign directly (or call
torch.randint once to create a 1-D tensor of seeds for all blocks and then
index/assign from that), avoiding any .item() calls inside the allocation loop.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py`:
- Around line 545-547: The loop currently calls torch.randint(...).item() and
stores a Python int into self.mamba_cache.mamba_ssm_rand_seed[block], causing a
host sync for each slot; instead generate seeds on the tensor device and write
them in-place (or batch-generate them before the loop). Concretely, replace the
per-iteration .item() pattern for self.mamba_cache.mamba_ssm_rand_seed
(referenced as mamba_cache.mamba_ssm_rand_seed and index variable block) with a
device-aware assignment using torch.randint(...,
device=self.mamba_cache.mamba_ssm_rand_seed.device,
dtype=self.mamba_cache.mamba_ssm_rand_seed.dtype) and assign directly (or call
torch.randint once to create a 1-D tensor of seeds for all blocks and then
index/assign from that), avoiding any .item() calls inside the allocation loop.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f5bd5139-e083-4aca-89b1-48ef6088dc07

📥 Commits

Reviewing files that changed from the base of the PR and between f49ac56 and c7f3249.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/modules/mamba/mamba2_mixer.py
  • tensorrt_llm/_torch/modules/mamba/replay_selective_state_update.py
  • tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50125 [ run ] completed with state SUCCESS. Commit: c7f3249
/LLM/main/L0_MergeRequest_PR pipeline #39678 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

Signed-off-by: qgai <qgai@nvidia.com>
@sunnyqgg
sunnyqgg requested a review from a team as a code owner May 26, 2026 04:54
@sunnyqgg
sunnyqgg requested a review from lancelly May 26, 2026 04:54

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50274 [ run ] triggered by Bot. Commit: 9663fb0 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50274 [ run ] completed with state FAILURE. Commit: 9663fb0
/LLM/main/L0_MergeRequest_PR pipeline #39805 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

Comment thread tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py Outdated
Comment thread tensorrt_llm/_torch/pyexecutor/mamba_cache_manager.py Outdated
sunnyqgg and others added 3 commits May 26, 2026 22:01
Signed-off-by: qgai <qgai@nvidia.com>
Signed-off-by: qgai <qgai@nvidia.com>
Signed-off-by: qgai <sunnyqgg@users.noreply.github.com>
@sunnyqgg

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50533 [ run ] triggered by Bot. Commit: 11e8ae2 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50533 [ run ] completed with state FAILURE. Commit: 11e8ae2
/LLM/main/L0_MergeRequest_PR pipeline #40040 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

Signed-off-by: sunnyqgg <159101675+sunnyqgg@users.noreply.github.com>
@sunnyqgg

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50992 [ run ] triggered by Bot. Commit: 2c65024 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #50992 [ run ] completed with state SUCCESS. Commit: 2c65024
/LLM/main/L0_MergeRequest_PR pipeline #40443 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@sunnyqgg

sunnyqgg commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #51293 [ run ] triggered by Bot. Commit: 2c65024 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #51293 [ run ] completed with state SUCCESS. Commit: 2c65024
/LLM/main/L0_MergeRequest_PR pipeline #40710 completed with status: 'SUCCESS'

CI Report

Link to invocation

@Funatiq Funatiq left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Executor changes look fine.

@sunnyqgg
sunnyqgg merged commit 2e6f602 into NVIDIA:main Jun 1, 2026
7 checks passed
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.

5 participants