Skip to content

Correct sample packing for hybrid models (gated-delta, Mamba2, short conv) - #9812

Merged
danielhanchen merged 38 commits into
unslothai:mainfrom
kfastino:feat/mamba2-hybrid-packing
Oct 7, 2026
Merged

danielhanchen merged 38 commits into
unslothai:mainfrom
kfastino:feat/mamba2-hybrid-packing

Conversation

@kfastino

@kfastino kfastino commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Correct sample packing for every hybrid model family whose mixers carry recurrent or causal-conv state. Started as the Mamba2 shim for Nemotron-H (follow-up to #7249) and is now generalized across mixer families and both transformers mixer layouts (<= 5.15 and >= 5.16).

A packed batch flattens several sequences into one row, so any recurrent scan or causal conv leaks state from one sequence into the next unless the kernels receive the boundaries (seq_idx / cu_seqlens). Today Unsloth either blocks packing for these models, or does not detect them and packs with leaked state.

What changes

  • One structural classifier (_stateful_mixer_kind) used by both the trainer's hybrid detection and the shim: gated_delta, ssd (Mamba2-style chunked scan: A_log + conv1d + dt_bias), short_conv, or unsupported. No class-name matching.
  • Gated-delta (Qwen3.5, Qwen3.5-MoE, Qwen3-Next, OLMo-Hybrid): conv gets seq_idx, scan gets cu_seqlens; OLMo-Hybrid's split q/k/v short convs get cu_seqlens.
  • SSD (Mamba2, Nemotron-H, Bamba, GraniteMoeHybrid, Zamba2, Falcon-H1): fused and chunked kernels get seq_idx (native parameter where the mixer has one).
  • Short conv (LFM2, LFM2-MoE): seq_idx through the mixer forward. These pack by default; every other family stays behind UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1.
  • transformers >= 5.16 mixers splat **kwargs into hub-wrapped kernels whose torch fallback silently drops unknown kwargs, so the shim reads the bound implementation and requires the accelerated kernel to accept the boundary, then probes each kernel call.
  • Hybrids that build the attention mask without position_ids (GraniteMoeHybrid) get per-sequence positions while packed.
  • Mixers with no boundary-aware kernel (Mamba1 selective scan, lightning attention, RWKV) keep the whole model on the padded path, and Falcon-H1 / LFM2 / RWKV are now detected instead of packing with leaked state.
  • Fail closed: if the boundary kernels were not hit on the first packed forward, training aborts instead of continuing on a contaminated batch.

Results

Leak test on real kernels (B200, fp32): change only the first packed sequence, report the max change in the logits of the later sequences. 0 means no leakage.

Model no shim main this PR (transformers 5.14 / 5.17)
Qwen3.5, Qwen3.5-MoE, Qwen3-Next 0.03 to 0.27 0 on 5.14, packing disabled on 5.17 0 / 0
OLMo-Hybrid 8.1 blocked 0 / 0
Bamba, GraniteMoeHybrid, Zamba2, Falcon-H1 0.0015 to 0.66 blocked (Falcon-H1 not detected, leaks) 0 / 0
Nemotron-H, Mamba2 0.06, 4.4 blocked 2e-8, 8.5e-5 (fp32 cancellation inside the mamba_ssm varlen kernel)
LFM2, LFM2-MoE 0.03, 0.02 not detected, leaks 0 / 0
Mamba, FalconMamba, Jamba, MiniMax 0.002 to 1.0 blocked blocked

End to end SFTTrainer(packing=True) on transformers 5.17: unsloth/Qwen3.5-2B packs with all 18 gated-delta layers dispatched (main ignores packing), Nemotron-H and LFM2 pack and dispatch, and generate() works after training in every case.

Fixes along the way: forcing is_fast_path_available=True made generate() call a missing decode kernel when causal_conv1d was absent (now synced from the mixer's own globals); a TypeError raised inside the mixer re-ran it with duplicate kwargs; on main, generate() after packed Qwen3.5 training raised seq_idx must have shape (batch_size, seqlen).

Tests

  • tests/utils/test_packing.py: 100 passed (classifier, rejection of unsupported mixers, short conv injection, transformers >= 5.16 hub-kernel validation, packed mask positions, compiled-cache global sync, fail-closed handshake, second model in one process, generate() between packed steps, string model ids).
  • Regression switchboard (base vs head): jobs/sft.py, jobs/vision_sft.py, jobs/audio_sft.py unchanged; regression_smoke head ran all 103 cases with 0 failures.

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]>
pre-commit-ci Bot and others added 19 commits August 26, 2026 19:08
…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.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this extends the varlen shim in unsloth/utils/packing.py to Nemotron-H Mamba2 mixers, which the existing GatedDeltaNet path never reached. The direction is right, but the bytecode LOAD_GLOBAL scanning and gc referrer rebinding used to swap the fused kernel are a lot of machinery to keep working across transformers versions; could you narrow it to the mixer forward kwargs injection plus a clear fail-closed check when the fused callable is not reachable?

kfastino and others added 2 commits August 27, 2026 09:42
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]>
@kfastino

Copy link
Copy Markdown
Contributor Author

Thanks — I've removed that machinery. 74cc2f7 drops the gc.get_referrers sweep, the closure-cell rewriting and the co_names / LOAD_GLOBAL bytecode scanning, which is -172 lines in packing.py. What's left is a plain reassignment of the kernel name in the namespaces reachable by name (the mixer's modeling module, unsloth_compiled_cache*, mamba_ssm), which works because a LOAD_GLOBAL resolves through the module dict at call time — and NemotronHMamba2Mixer._lazy_load_kernels assigns the kernel into exactly that dict (global ... mamba_split_conv1d_scan_combined, modeling_nemotron_h.py:186-195). Anything the install misses now hits the fail-closed handshake instead of training unpacked, and test_patch_mamba2_varlen_unreachable_kernel_namespace_aborts pins that for a kernel reachable only from an unregistered namespace. Re-verified on H200: 24 rows still pack into 8 blocks with the fused kernel dispatched on all layers, plus 70 passed / 2 skipped on tests/utils/test_packing.py.

On narrowing all the way to mixer-forward kwargs injection: that was the first revision of this PR, and on Nemotron-H it cannot reach the kernel. In transformers 5.5 (modeling_nemotron_h.py), forward drops everything except three positional arguments:

# line 561
return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)

and cuda_kernels_forward writes seq_idx into the fused call itself:

# line 287
if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
    out, ssm_state = mamba_split_conv1d_scan_combined(
        projected_states,
        ...
        seq_idx=None,   # line 296

So kwargs handed to mixer.forward are discarded before the kernel call, and seq_idx=None is hardcoded at both the fused (296) and chunk-scan (352) call sites. On H200 that revision aborted on the handshake every time, i.e. packing=True stayed effectively a no-op. Line 287 is also why the mixer wrapper forces a packed prefill: the fused branch needs the mask all-ones and cache_params is None, and packed batches violate both — pad zeros in the mask, and the decoder layer passes a cache in unconditionally (hidden_states = self.mixer(hidden_states, cache_params=past_key_values, ...), line 924).

There is a cleaner long-term fix if you'd prefer it: thread a seq_idx argument through forward / cuda_kernels_forward instead of hardcoding None. That is a small upstream transformers change and would let this shim drop the namespace reassignment entirely. Happy to open that PR against transformers and gate this on it, or keep the current narrowed version as the interim behind the existing experimental flag — your call.

@danielhanchen

Copy link
Copy Markdown
Member

Checked 814997a and the narrowing you did after my last note is in, with the handshake covering the namespaces the reassignment cannot reach, and I saw the upstream transformers PR you opened. Please keep this PR to the released 5.5 shim as-is and add the post-refactor kwargs-injection path as a separate follow-up once 48490 lands.

@kfastino

Copy link
Copy Markdown
Contributor Author

huggingface/transformers#48490 merged on 4 Sep (86a6c97), so the follow-up is up: #11177. This PR is unchanged and stays the released-5.5 shim.

Two things from the upstream review worth carrying back here. The cross-check vasqu asked for turned up that Nemotron-H was not the only model affected — falcon_h1 and mamba2 dropped kernel kwargs at both hops (model → block and block → mixer), while bamba, granitemoehybrid and zamba2 were already fine — so the merged change covers all three, each with its own test.

The second is a correctness detail that shaped the follow-up. use_kernel_func_from_hub_with_fallback narrows kwargs to the bound kernel's parameters before calling it, so on transformers' reference PyTorch path seq_idx is filtered out silently rather than raising. Passing the kwarg is therefore not sufficient on its own: #11177 resolves and checks the accelerated kernels up front and declines when they are absent, and keeps a record-only dispatch probe so the handshake still proves a kernel ran with seq_idx before the batch reaches loss and backward. That probe is the only name reassignment left on that path — no injection, no mask clearing, no packed-prefill forcing.

One practical note: the new path is inert from a normal install today, because unsloth_zoo pins transformers<=5.5.0 and pip will not resolve a post-refactor transformers. I had to force one in to test it. Until that ceiling is raised, Nemotron-H runs stay on the shim in this PR. Happy to raise the zoo pin separately if you want the new path actually reachable.

@danielhanchen danielhanchen self-assigned this Oct 6, 2026
… path

Forcing is_fast_path_available=True sent mixers without causal_conv1d /
selective_state_update down the CUDA path, so a later cached generate()
called None. Copy the real values from the mixer's __init__ globals into
unsloth_compiled_cache copies only, decline the shim when the fast path is
unavailable, prefer the kernel the modeling module loaded, and keep only
signature binding inside the prefill helper's try so an inner TypeError
propagates instead of re-running the mixer.
Classify mixers structurally (gated-delta, Mamba2/SSD, short conv, unsupported)
instead of by class name, and use the same classifier for the trainer's hybrid
detection so Falcon-H1, LFM2 and RWKV no longer pack silently with leaked state.

- SSD mixers (Mamba2, Nemotron-H, Bamba, GraniteMoeHybrid, Zamba2, Falcon-H1)
  share the seq_idx path, using the native seq_idx parameter where present.
- Short-conv mixers (LFM2, LFM2-MoE) get seq_idx through forward.
- OLMo-Hybrid's split q/k/v short convs get cu_seqlens.
- transformers >= 5.16 mixers that splat kwargs into hub kernels get seq_idx /
  cu_seq_lens_q, after checking the bound kernels are accelerated and accept them.
- Hybrids that build the attention mask without position_ids get per-sequence
  positions while packed.
- Mixers with no boundary-aware kernel (Mamba1, lightning attention, RWKV) keep
  the whole model on the padded path.
LFM2 / LFM2-MoE reset their short conv at seq_idx on both kernel and torch
paths, so they keep packing without the experimental flag, now correctly. On
transformers >= 5.16 their conv goes through the hub wrapper, whose torch
fallback drops seq_idx: require the accelerated kernel and check it received
seq_idx, else fall back to the padded path.
@danielhanchen danielhanchen changed the title Experimental: Mamba2 varlen packing for Nemotron-H hybrids Correct sample packing for hybrid models (gated-delta, Mamba2, short conv) Oct 7, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
…model

The fused / fallback kernel wrappers live on module globals and are reused when a
second model is patched in the same process, but they closed over the first
model's mixers and varlen slot, so the second model's first packed forward
aborted the handshake. They now read the running SSD mixer's own stash and credit
only that mixer, and the mask builders read the current packed batch, so no shared
wrapper holds model state.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
Clearing it permanently left a pending gradient-checkpoint recompute without
seq_idx / cu_seqlens when generate() ran between a packed forward and backward.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
A string model reaches the hybrid detector as its config only, so LFM2, Mamba2,
Falcon-H1 and other configs without a linear_attention layer type passed as
non-hybrid and TRL packed them with leaked state. Build the model on the meta
device and classify its modules with the same classifier.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #9812, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#501.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 3724a6aed (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on unsloth/utils/packing.py (on the mirror)

@@ -554,41 +1243,68 @@ def forward_with_varlen(*args, **kwargs):
                 "_unsloth_varlen_handshake_done",
                 False,
             )
-            for module in gated_delta_modules:
+            for module in hybrid_modules:
                 module._unsloth_varlen = varlen

P2 Badge Preserve boundaries for every pending checkpoint graph

When two gradient-checkpointed packed forwards are executed before either graph is backpropagated, the second forward overwrites this single per-mixer stash. Backward recomputation for the first graph then uses the second batch's boundaries, or no boundaries when its token count differs, silently producing incorrect gradients. This also occurs if any ordinary non-packed model forward is made while a packed graph is pending, so the boundary metadata needs to be associated with each checkpointed invocation rather than stored only as the model's latest value.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not reachable in the training loops this shim serves: Trainer and SFTTrainer run forward then backward per micro-batch with no model forward in between, so only one checkpointed packed graph is ever pending; the generate() case is already restored.

Round 2: reviewed mirror e6ed4929c (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e6ed4929cc

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror e6ed4929c (no equivalent commit found on this PR).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

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