Skip to content

feat(recompute): add mamba to recompute_modules - #5463

Open
yuchenwang3 wants to merge 3 commits into
NVIDIA:mainfrom
yuchenwang3:feat/mamba-selective-recompute
Open

yuchenwang3 wants to merge 3 commits into
NVIDIA:mainfrom
yuchenwang3:feat/mamba-selective-recompute

Conversation

@yuchenwang3

@yuchenwang3 yuchenwang3 commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor
  • I, the PR author, have personally reviewed every line of this PR.

What

Add mamba as a selective activation-recompute target. With --recompute-granularity selective --recompute-modules '[mamba]', MambaLayer checkpoints the mixer (convolution plus selective SSM/SSD compute) instead of retaining its activations.

Why

In Mamba-hybrid models the mixer activations can be a material part of long-sequence memory. Megatron already lets selective recompute target attention, MLP, MoE, and several GDN components, but not Mamba, leaving full-layer recompute as the only way to trade compute for this activation memory.

Implementation

  • Add mamba to the recompute_modules validation and documentation.
  • Warn when mamba is selected with moe_shortcut_connection: shortcut MoE uses two-stage mixer execution and does not enter this checkpoint path.
  • Use tensor_parallel.checkpoint for BF16/FP16/FP32.
  • Use Transformer Engine checkpointing for FP8/FP4 so recomputation does not update amax/scaling history twice.
  • Preserve inference_context and packed_seq_params through both paths.
  • Keep eval and inference on the direct mixer path.
  • Bypass activation checkpointing during local CUDA-graph warmup/capture, matching the existing tensor-parallel checkpoint contract and avoiding TE checkpoint's .grad() incompatibility.

The option is default-off and does not change existing runs unless mamba is explicitly selected.

Tests

October 27 fixture correction (e2cb2ac21f)

test_mamba_residual_state.py builds its ordinary and wide-residual layers with __new__, bypassing MambaLayer.__init__. Its shared fixture now initializes recompute_mamba_mixer = False, matching the default eager path before the inherited forward reads that field.

On macOS with PyTorch 2.14.1, a source-isolated CPU harness reproduced the same 36 failures (8 passes) without the fixture initialization; all 44 residual-state cases pass with it. The existing 14 source-method recompute routing checks also pass. These exercise the actual schedules and CPU residual/autograd operators while bypassing the GPU framework imports; they are not a normal-package or CUDA test run.

tools/autoformat.sh passes Black, isort, Pylint and Ruff; its optional mypy step could not run because mypy is not installed. Normal package collection on this host is blocked by missing Triton. Full CI for the updated commit remains pending; the prior /ok to test covered a683e8e, not this follow-up.

Earlier validation

The focused suite retains the 12 routing/bypass cases and adds three shortcut-MoE warning cases. Six new tests build a real HybridModel with MambaMixer, compare recompute-off versus selective logits and all parameter gradients, and verify that the mixer runs again during backward. The matrix covers TP1, TP2, TP2 with sequence parallelism, and both memory-efficient and explicit Mamba paths. The mixer and checkpoint functions are not mocked in these model tests.

On the preceding head 6f88cf61288a, NVIDIA CI passed the focused suite and H100 integration jobs; the SSM bucket passed 387 tests with 9 skips. Those results do not cover the new tests.

For the October 5 review update, Black, isort, Ruff, Pylint, py_compile, and git diff --check pass. The repository formatter script exits successfully; its non-blocking mypy step still reports missing dependencies/stubs and an existing normalization override type error. The local macOS pytest attempt stopped during normal Core import because Triton is unavailable; no test cases ran. Linux CPU and CUDA validation of the new cases remain pending, and CI needs authorization for the updated head.

An earlier 8×B200 run covered packed BF16 and FP8 training plus local Mamba CUDA-graph capture/replay. At sequence length 16K (CP1/DP8), selective and full FP8 recompute both completed without NaNs or OOMs and differed by about 1e-5 relative loss. A 20-step BF16 selective/full comparison had a maximum absolute difference of 2.37e-3; repeating selective with the same seed produced 2.24e-3 run-to-run variation, so the cross-mode difference was within the measured baseline nondeterminism.

At the 24K BF16 boundary with the same model/topology, no recompute OOMed before completing its first step, while selective Mamba recompute completed both steps without NaNs (10.58632 → 10.09310) with rank-0 peak allocated memory of 96.13 GiB and 102.09 GiB. At 32K both modes OOMed before a complete step. Because the failed baseline has no common completed step, this is capacity evidence rather than a like-for-like percentage-memory comparison.

The intended CP8 matrix could not run because this environment did not expose a compatible deterministic attention backend, so these results are explicitly CP1/DP8 rather than CP8. Raw numbers and the CUDA-graph baseline comparison are in the PR discussion.
Assisted-by: OpenAI Codex

@copy-pr-bot

copy-pr-bot Bot commented Jun 23, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@yuchenwang3
yuchenwang3 force-pushed the feat/mamba-selective-recompute branch from e7519a9 to 741c3ba Compare June 23, 2026 23:02
@yuchenwang3
yuchenwang3 marked this pull request as ready for review July 6, 2026 21:21
@yuchenwang3
yuchenwang3 requested review from a team as code owners July 6, 2026 21:21
@svcnvidia-nemo-ci
svcnvidia-nemo-ci requested a review from a team July 6, 2026 21:21
@Phlip79

Phlip79 commented Jul 6, 2026

Copy link
Copy Markdown
Member

/ok to test 741c3ba

@Phlip79

Phlip79 commented Jul 6, 2026

Copy link
Copy Markdown
Member

/claude strict-review

@yuchenwang3 yuchenwang3 changed the title feat(recompute): add "mamba" to selective recompute_modules for Mamba-hybrid long-context feat(recompute): add mamba to recompute_modules Jul 6, 2026
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Strict Review Summary — Findings by severity: CRITICAL: 0 · IMPORTANT: 1 · SUGGESTION: 0.

The change is small, follows the established selective-recompute pattern, correctly gates to training-only (self.training and inference_context is None, so the stateful SSM update is never re-executed in inference), and tensor_parallel.checkpoint already bypasses recomputation during CUDA-graph warmup/capture (random.py:647). The config allow-list, docstring, and validation updates are consistent. The mandatory unused-identifier check passes: recompute_mamba_mixer is read in forward, and the new functools/tensor_parallel imports are both used.

Most impactful finding — [IMPORTANT] fp8/fp4 recompute path: The Mamba mixer runs fp8/fp4 GEMMs (in_proj/out_proj are TE linear modules; mamba_mixer.py:227 has an explicit fp8 assertion), but the new code unconditionally uses tensor_parallel.checkpoint. The established selective-recompute pattern (transformer_layer.py:824-842) branches on config.fp8 or config.fp4 and routes through te_checkpoint, which enters TE activation-recompute phase so fp8 amax/scaling state is not double-updated during the backward-pass recompute. Without this branch, fp8 Mamba-hybrid training re-runs the mixer fp8 GEMMs under a plain enable_grad context, double-updating amax history and silently corrupting fp8 scaling — invisible at bf16, harmful under fp8. Recommend mirroring the transformer-layer fp8 branch.

Risk assessment — Low-to-moderate. For the common bf16/CP long-context case this is a clean, well-scoped memory/speed trade-off and is a no-op unless "mamba" is explicitly added to recompute_modules (fully backward compatible). The one gap is fp8/fp4, where fp8-scaling correctness is at risk. As the PR notes, it is still a draft pending convergence/loss-parity and peak-memory validation vs full recompute — that validation should include an fp8 run to exercise the path above.

Comment thread megatron/core/ssm/mamba_layer.py Resolved
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Jul 9, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@Phlip79 Thanks for the quick vetting and the strict review. The fp8/fp4 finding is addressed in 20eeb77 (mirrors the te_checkpoint branch from transformer_layer.py). Could you /ok to test 20eeb77 so CI runs on the updated SHA?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Jul 10, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@Phlip79 following up on my Jul 10 comment — the fp8/fp4 gating your strict-review flagged is fixed in 20eeb77, and that SHA is still waiting on /ok to test (only DCO and check-approval have run). Could you authorize CI on it so this can move to review?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Aug 6, 2026
@yuchenwang3
yuchenwang3 force-pushed the feat/mamba-selective-recompute branch from 20eeb77 to 4811efa Compare August 25, 2026 08:32
@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-customer Waiting on the original author to respond labels Oct 6, 2026
@yuchenwang3

Copy link
Copy Markdown
Contributor Author

@janEbert The CI run for 414aed890 has been waiting at cicd-wait-in-queue since October 6. Could you check what is holding the test environment gate?

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Oct 9, 2026
Checkpoint the prepared mixer input while preserving the current residual scheduling and packed CP metadata.

Assisted-by: OpenAI Codex
Signed-off-by: Yuchen Wang <[email protected]>
@yuchenwang3
yuchenwang3 force-pushed the feat/mamba-selective-recompute branch from 414aed8 to a683e8e Compare October 26, 2026 23:58
@janEbert

Copy link
Copy Markdown
Contributor

/ok to test a683e8e

The residual-state tests bypass MambaLayer.__init__ with __new__. Set the default-off recompute flag in their shared fixture before the inherited forward path reads it.

Assisted-by: OpenAI Codex
Signed-off-by: Yuchen Wang <[email protected]>

Copy link
Copy Markdown
Contributor Author

@janEbert Fixed in e2cb2ac: the residual-state fixture bypasses MambaLayer.__init__, so it now initializes recompute_mamba_mixer = False.

Source-isolated CPU validation reproduced the 36 failures before the fix; all 44 cases pass afterward. The 14 recompute-routing checks and Black/isort/Pylint/Ruff also pass. Full package/CUDA validation remains pending because local collection is blocked by missing Triton. Could you run /ok to test e2cb2ac21f53836d3c22fea0cfc9fcbd15d9545a for the updated head?

Assisted-by: OpenAI Codex

@janEbert

Copy link
Copy Markdown
Contributor

/ok to test e2cb2ac

Copy link
Copy Markdown
Contributor Author

@NVIDIA/core-adlr and @NVIDIA/core-nemo, could you review mamba_layer.py and transformer_config.py? @NVIDIA/transformer, could you review transformer_config.py? The owner check already counted Jan’s approval. CODEOWNERS log

e2cb2ac21f initializes recompute_mamba_mixer = False in the residual-state fixture, which bypasses MambaLayer.__init__. On H100, all 44 residual-state cases and all 24 Mamba recompute cases passed, including six forward/backward parity cases. The SSM shard reported 369 passed and 7 skipped. H100 test log

Of 103 checks, 88 passed and 13 were skipped, including GB200 unit and integration tests and the Megatron-Bridge and NeMo RL downstream jobs. The two failures are codeowners-approval and multi-approval-bot-summary. Current main also conflicts on the gdn/mamba docstring line in transformer_config.py. Checks for this commit

Assisted-by: OpenAI Codex

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@janEbert The current head is 5f90cab, which includes the November 5 main merge. The earlier /ok to test and H100 results cover e2cb2ac; this revision currently has only DCO, check-approval, and a skipped CodeRabbit check. Could you authorize the full CI on this SHA and continue the pending code-owner review?

/ok to test 5f90cab

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Nov 20, 2026

This branch was previously deployed

2 inactive (outdated) deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-request Expert Review [deprecated] Apply this label to indicate that your PR is ready for expert review. waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants