Skip to content

Experimental: Mamba2 packing via mixer kwargs on refactored transformers - #11177

Closed
kfastino wants to merge 29 commits into
unslothai:mainfrom
kfastino:feat/mamba2-packing-kwargs-path
Closed

kfastino wants to merge 29 commits into
unslothai:mainfrom
kfastino:feat/mamba2-packing-kwargs-path

Conversation

@kfastino

@kfastino kfastino commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #9812, as agreed there. That PR stays the transformers 5.5 shim; this adds the path for the refactored mixer now that huggingface/transformers#48490 has merged (86a6c97).

Stacked on #9812. It is branched off feat/mamba2-hybrid-packing, and GitHub will not accept a fork branch as the base, so this PR is against main and its diff shows #9812's 26 commits as well. The follow-up is only the last two commits — 6f803ac plus a pre-commit autofix — which are unsloth/utils/packing.py +197 and tests/utils/test_packing.py +240. Merge #9812 first and the diff here reduces to exactly that.

Why there are two paths

transformers collapsed the Mamba2 mixer into a single forward(..., **kwargs) that splats those kwargs into all three kernel calls (fused conv1d+scan, conv, chunk scan) and dropped the hardcoded seq_idx=None. 48490 then made NemotronHBlock pass kwargs through to it. On that shape seq_idx only has to reach mixer.forward, so this path needs none of the 5.5 machinery: no kernel rebinding to inject, no mask clearing, no packed-prefill forcing. The fused branch now only asks for self.training and cache_params is None, and when a cache does arrive the conv and chunk-scan fallbacks receive the same kwargs, so correctness no longer depends on steering transformers onto one branch.

The shape is chosen per module by feature marker, never by transformers version: no cuda_kernels_forward, no kernel exposed as an attribute to wrap, and a forward that collects **kwargs. The refactor and the block fix shipped apart, so a version check would be wrong for the window in between — and that window fails closed, see below.

Two things that are load-bearing

The torch reference drops seq_idx silently. use_kernel_func_from_hub_with_fallback narrows kwargs to the bound implementation's parameters before calling it:

kwargs = {k: v for k, v in kwargs.items() if k in applicable_params}
return implementation(*args, **kwargs)

On the reference PyTorch path seq_idx is therefore filtered out with no error, which would leave state bleeding across packed boundaries and no way to notice. The wrapper cannot be introspected for this either — functools.wraps gives it the reference signature whichever implementation is bound — so the accelerated kernels are resolved and checked directly, and the shim declines when they are missing.

A transformers with the refactor but without 48490 still drops the kwargs at the block. Nothing raises in that case, so the handshake carries the guarantee: the probes record a hit only when a kernel is called with seq_idx, which means transformers itself carried it end to end. If no kernel did, the first packed forward aborts before loss and backward, as on the 5.5 path. This is the only reason a name is reassigned at all here, and the probes inject nothing.

Test plan

Four tests against a faithful post-refactor namespace (kernels as module globals, forward splatting kwargs), plus one against a real NemotronHModel so a future refactor that stops carrying kwargs surfaces here rather than on an H200. The real-model test skips on a pre-refactor transformers.

transformers result
released 5.5 74 passed, 3 skipped, 4 pre-existing failures (real-model test skips: "predates the Mamba2 mixer refactor")
main (post-refactor + 48490) 73 passed, 2 skipped, same 4 pre-existing failures + 2 pre-existing errors; all 5 new-path tests pass

The 4 failures and 2 errors reproduce on origin/main unchanged (56 passed there), so they are pre-existing and unrelated.

Note for review

This path is not reachable from a normal install yet: unsloth_zoo pins transformers<=5.5.0, so pip refuses a post-refactor transformers, and I had to force one in to test it. Until that ceiling is raised, a Nemotron-H run stays on the 5.5 shim from #9812 and this code is inert. That is why it sits behind the same experimental flag with no separate switch, and why the H200 smoke test is still the 5.5 one — happy to run a post-refactor smoke test once the pin allows it.

Made with Cursor

kfastino and others added 26 commits August 26, 2026 12:03
unslothai#7249 only wraps GatedDeltaNet seq_idx/cu_seqlens, so packing=True stayed
ignored on Nemotron-H. Inject seq_idx into the fused mamba2 split-scan
kernel (same UNSLOTH_EXPERIMENTAL_HYBRID_PACKING flag) and fail closed
when that kernel is a **kwargs-only stub or never dispatched.

Co-authored-by: Cursor <[email protected]>
…y hits seq_idx

Unsloth's Fast Nemotron-H compile binds mamba_split_conv1d_scan_combined in unsloth_compiled_cache, so wrapping only the transformers modeling import left the handshake aborting on a real packed 8k train.
Walking sys.modules with getattr tripped transformers lazy image processors and never patched unsloth_compiled_cache, so packed Nemotron-H still aborted the varlen handshake.
…its the wrap

transformers 5.5 Nemotron-H calls mamba_split_conv1d_scan_combined(..., seq_idx=None). Unsloth compiles that into unsloth_compiled_cache; patch the function globals/closure, not just module getattr aliases.
…'s export

Nemotron-H on transformers 5.5 resolves mamba_split_conv1d_scan_combined via lazy_load_kernel and hardcodes seq_idx=None. The H200 packed train never called the mamba_ssm object we wrapped, so the varlen handshake aborted.
Unsloth compiles cuda_kernels_forward into unsloth_compiled_cache. Wrap kernels found by bytecode, rebind gc dict referrers, and inject seq_idx from the outer packed forward so the handshake sees the real call.
The compiler snapshots mamba_split_conv1d_scan_combined into unsloth_compiled_cache at import time, so wrapping the live mamba_ssm object never changed the LOAD_GLOBAL packed training actually calls.
transformers 5.5 only calls mamba_split_conv1d_scan_combined when the mask is
all-ones; packed pad zeros diverted to mamba_chunk_scan_combined and aborted
the hybrid packing handshake.

Co-authored-by: Cursor <[email protected]>
Nemotron-H layers pass an empty Cache into the mixer, so transformers skips
mamba_split_conv1d_scan_combined even after the attention_mask is cleared.

Co-authored-by: Cursor <[email protected]>
…erence

The alias rebind rewrote the wrapper's own __wrapped__ / closure cell to point
at itself, so the first packed forward recursed until the interpreter limit.

Co-authored-by: Cursor <[email protected]>
generate() reaches the decoder without the wrapped model.forward, so mixers
still held the last training step's boundaries and the conv kernel rejected
them. Clear the stash around generate and only inject when seq_idx covers the
tokens the kernel actually sees.

Co-authored-by: Cursor <[email protected]>
The dump of mixer source and globals existed to diagnose the H200 aborts.
Keep only the class, fast-path availability and the per-kernel hit flags.
A forward that merely collects **kwargs may splat them into the kernel while
also passing seq_idx itself, which is a duplicate-keyword TypeError. The
kernel-level wrappers already inject it in that case.

Co-authored-by: Cursor <[email protected]>
…ecode

Drop the gc referrer sweep, closure rewriting and LOAD_GLOBAL bytecode
scanning used to swap the fused kernel. A LOAD_GLOBAL resolves through the
module dict at call time, so reassigning the name in the compiled/modeling
namespaces is enough, and anything missed now fails closed on the dispatch
handshake instead of silently training unpacked.

Co-authored-by: Cursor <[email protected]>
…cking

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	unsloth/trainer.py
#	unsloth/utils/packing.py
…cking

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	studio/backend/tests/test_anthropic_messages.py
transformers collapsed the Mamba2 mixer into a single forward(**kwargs) that
carries those kwargs to the fused conv1d+scan, the conv and the chunk scan,
dropping the hardcoded seq_idx=None, and huggingface/transformers#48490 made
the Nemotron-H block pass kwargs through to it. On that shape seq_idx only has
to be handed to mixer.forward, so none of the 5.5 kernel rebinding, mask
clearing or packed-prefill forcing is needed.

The shape is chosen per module by feature marker, never by version, since the
refactor and the block fix shipped apart. Kernels are still validated up front
because transformers narrows kwargs to the bound kernel's parameters, which
means the torch reference drops seq_idx silently rather than raising, and the
dispatch handshake still has to see a kernel run with seq_idx before the batch
reaches loss and backward.

Co-authored-by: Cursor <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member

Checked this against main, where unsloth/utils/packing.py still only has the GatedDeltaNet varlen path, so the base for this is #9812 rather than anything merged, and the diff here currently carries all 26 of its commits. Could you rebase once #9812 lands so this reduces to the packing.py and test_packing.py follow-up, and confirm whether the transformers pin in unsloth_zoo needs raising for this path to be reachable?

@danielhanchen

Copy link
Copy Markdown
Member

Thank you for the follow-up and for getting huggingface/transformers#48490 landed upstream, that was the piece that made this possible.

We are going to close this one because #9812 as merged into main (7320e09) already carries the post-refactor path this PR adds:

  • _is_kwargs_mixer picks the refactored mixer per module by feature (no cuda_kernels_forward, a forward(**kwargs), and a hub-wrapped causal_conv1d_fn module global), never by transformers version.
  • _kwargs_kernels_available reads the bound implementation out of the use_kernel_func_from_hub_with_fallback closure and rejects the torch reference or a kernel whose applicable_params lack seq_idx / cu_seqlens, which covers the silent kwarg narrowing you described, and checks what transformers actually bound rather than what mamba_ssm exports.
  • _install_kwargs_probes plus _wrap_kwargs_mixer_forward inject seq_idx into mixer.forward and only mark the dispatch handshake when every boundary-capable kernel received it, so a transformers with the refactor but without #48490 still fails closed before loss and backward.

Checked on transformers 5.17.0: a real NemotronHMamba2Mixer is classified as a kwargs mixer on main, and without mamba_ssm / causal_conv1d the patch declines with causal_conv1d_fn has no accelerated kernel. The kwargs-path tests in tests/utils/test_packing.py on main pass (21 passed). Rebasing this branch would mostly duplicate that code with a second, parallel Mamba2 kwargs path.

Thanks again for all the work on hybrid packing, it is much appreciated.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants