Repository navigation
Correct sample packing for hybrid models (gated-delta, Mamba2, short conv) - #9812
Conversation
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.
|
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? |
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]>
|
Thanks — I've removed that machinery. 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 ( # line 561
return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)and # 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 296So kwargs handed to There is a cleaner long-term fix if you'd prefer it: thread a |
|
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. |
|
huggingface/transformers#48490 merged on 4 Sep ( 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 — The second is a correctness detail that shaped the follow-up. One practical note: the new path is inert from a normal install today, because |
… 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.
…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.
Clearing it permanently left a pending gradient-checkpoint recompute without seq_idx / cu_seqlens when generate() ran between a packed forward and backward.
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.
|
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
|
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
_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, orunsupported. No class-name matching.seq_idx, scan getscu_seqlens; OLMo-Hybrid's split q/k/v short convs getcu_seqlens.seq_idx(native parameter where the mixer has one).seq_idxthrough the mixer forward. These pack by default; every other family stays behindUNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1.**kwargsinto 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.position_ids(GraniteMoeHybrid) get per-sequence positions while packed.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.
End to end
SFTTrainer(packing=True)on transformers 5.17:unsloth/Qwen3.5-2Bpacks with all 18 gated-delta layers dispatched (main ignores packing), Nemotron-H and LFM2 pack and dispatch, andgenerate()works after training in every case.Fixes along the way: forcing
is_fast_path_available=Truemadegenerate()call a missing decode kernel whencausal_conv1dwas absent (now synced from the mixer's own globals); aTypeErrorraised inside the mixer re-ran it with duplicate kwargs; on main,generate()after packed Qwen3.5 training raisedseq_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).jobs/sft.py,jobs/vision_sft.py,jobs/audio_sft.pyunchanged;regression_smokehead ran all 103 cases with 0 failures.