Skip to content

Pack Qwen3.5 / Qwen3-Next hybrids by default with document boundaries in the linear-attention kernels - #13383

Merged
danielhanchen merged 30 commits into
mainfrom
hybrid-packing-default-on
Oct 12, 2026
Merged

danielhanchen merged 30 commits into
mainfrom
hybrid-packing-default-on

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Stacked on #13326. Packed / padding-free SFT for the gated-delta hybrids (Qwen3.5, Qwen3.5-MoE, Qwen3-Next) is now on by default on CUDA, with document boundaries passed to the linear-attention kernels. Needs unslothai/unsloth-zoo#1707 (the Triton causal conv honouring seq_idx).

Why

These models mix full attention with GatedDeltaNet layers: a short causal conv and a recurrent scan. In a packed row both carry state from one document into the next unless the kernels are told where documents start. The fla scan already takes cu_seqlens and the conv takes seq_idx, and #9812 added an opt-in shim (UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1) that passes them, but it never engaged for real users: it is off by default, and its gate rejected unsloth-zoo's Triton conv (the conv almost everyone runs, since few install causal_conv1d) because that conv had no seq_idx. So every Qwen3.5 / Qwen3-Next SFT run trained on padded rows.

Change

  • UNSLOTH_EXPERIMENTAL_HYBRID_PACKING unset now means auto: on for models whose linear-attention layers are all conv1d gated-delta mixers, with every mixer on CUDA. 0 / false / no / off turns it off (the old padded path, bitwise); 1 keeps opting in Mamba2 and the q/k/v short-conv mixers as before. ROCm and other devices need 1.
  • The kernel gate accepts unsloth-zoo's Triton conv when its dispatch names seq_idx, and looks through the compiled module's torch_compiler_disable_unless_decode wrapper (which hid fla from the gate on Qwen3-Next under transformers 5.x, so it was rejected even with the flag set). Pure-torch fallbacks, which drop the boundaries, stay rejected.
  • An exactness probe runs at trainer init: one mixer, in eval mode under a forked RNG, on a packed row of documents of 5, 1, 70 and 7 tokens against each document alone. If the boundary kernels are not dispatched or the outputs differ, every patch is undone and training stays padded with a one-line reason. HYBRID_PACKING_STATS counts probes and patches.
  • Boundaries reach a kernel only on a call over the packed row (a stale stash never reaches a call of another length) and are moved to each mixer's device, so a model split over GPUs works.
  • Labels at packed document starts: since Mask packed document boundary labels for TRL older than 0.23.1 #13324, Unsloth's packing collators mask them on TRL older than 0.23.1, and that covers these models too (they run transformers' forward, which has no boundary guard of its own). Before that, each document's last token was trained to predict the next document on TRL 0.22 (loss about 1.45% high on Qwen3-Next with transformers 4.57.6).

Speed

unsloth/Qwen3.5-2B, bf16 LoRA r=16, alpaca-style short rows, SFTConfig(packing=True, max_length=4096), 25 steps, median after 5 warmup, one exclusive B200, base / head / head / base then padded batch 64 twice:

run supervised tokens/s (2 runs) step peak memory
main, batch 8 (packing ignored, padded rows) 4,377 / 3,753 0.34 / 0.39 s 5.31 GB
main, batch 64 (padded, well tuned) 29,642 / 30,210 0.39 s 7.55 GB
this PR, batch 8 packed into one row 52,852 / 54,848 0.61 / 0.59 s 9.04 GB

About 13x main at the same config and about 1.8x a well-tuned padded batch. Packed rows fill 99.5% of token slots against 59 to 67% padded; each packed step carries 2.7x the tokens of the batch 64 run, hence the memory. The probe passed on the real checkpoint with relative error 0.0.

Correctness

Tiny models through FastModel and FastLanguageModel, packing=True and padding-free, bf16 LoRA, unsloth-zoo's Triton conv and vendored fla (no causal_conv1d). Each packed document against the same document run alone; the yardstick is the same row with no boundaries, i.e. what a leak looks like:

model, transformers later-document logits (yardstick) LoRA grads relative (yardstick) change document 0 only: later logits
Qwen3.5, 5.17 0.008 (1.72) 0.009 (0.52) bitwise unchanged
Qwen3.5 ConditionalGeneration (real 0.8B config), 5.17 0.016 (1.71) 0.005 (0.39) bitwise unchanged
Qwen3.5-MoE, 5.17 0.012 (1.82) 0.010 (0.45) bitwise unchanged
Qwen3-Next, 5.17 0.008 (1.86) 0.006 to 0.014 (0.39) bitwise unchanged
Qwen3-Next, 4.57.6 + TRL 0.22.2 0.008 to 0.012, one cell 0.31 (1.91) 0.006 to 0.020 (0.58) bitwise unchanged
  • The GatedDeltaNet output and the whole first layer match per document bitwise; the full-attention layers differ by at most one bf16 step.
  • On main a packed row leaks (0.9 to 1.2 on later documents); main never packs these models, so its training runs are padded.
  • The MoE models' router auxiliary loss is computed over the packed row, as for every packed MoE model (documented, not changed); on Qwen3-Next an occasional token flips experts on bf16 noise, the first document included (the 0.31 cell: one region of the last document, with the packed and per-document loss sums equal to 2e-6 relative and the grads at 0.007).
  • With the kill switch, losses, eval logits and generate() before and after training equal the base commit bitwise. Generation and eval forwards never receive the boundaries; no new graph breaks or recompiles.

Tests

tests/utils/test_hybrid_packing_default.py: mode parsing and the kill switch; exact kernels pack; a conv or scan that names the boundary argument but ignores it is caught by the probe and every patch (mixers and modeling namespace) rolled back; a probe that fails to run or bypasses the kernels is a rejection; the probe under LoRA-style dropout leaves train mode and the RNG as they were; zoo's Triton conv accepted only when it names seq_idx; the compiled-module wrapper looked through; boundaries moved to the call's device; a stale stash never reaching a call of another length. Removing any one of these checks fails its tests. With tests/utils/test_packing.py: 141 passed on torch 2.14 + transformers 5.17 + TRL 1.13 and on torch 2.7.1 + transformers 4.57.6 + TRL 0.22.2.

ROCm

On a Radeon 8060S (gfx1151, torch 2.11 ROCm, transformers 5.5.0, TRL 0.23.1), main against this PR on a tiny Qwen3.5 packed SFT run: the default stays on the padded path ("default-on only on CUDA"), losses match main within its own run-to-run noise (2e-5 against 1.6e-3), =1 fails closed there (no accelerated kernels installed), and the PR's tests pass (169 passed, 0 failed; main fails 5 of the existing packed attention tests on that host, which #13326 fixes).

Not covered

Hopper, ROCm with =1 on real kernels, multi-GPU training runs, real Qwen3-Next-80B, real-checkpoint timing in 4-bit or on the MoE models. A forward whose backward runs after another packed forward of the same model (two pending graphs under gradient checkpointing) would replay with the newer boundaries; the trainer loop never does this.

danielhanchen and others added 23 commits October 11, 2026 05:40
Qwen3.5, Qwen3.5-MoE and Qwen3-Next now take padding-free / packed batches by
default on CUDA. The kernel checks accept unsloth-zoo's Triton causal conv when
its dispatch names seq_idx, look through compiled-module wrappers to the kernel
hub closure, and an exactness probe runs one mixer on a packed row of short
documents against each document alone before anything is enabled. A failed
check or probe restores the mixers and keeps the padded path with a one-line
reason. UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=0 (false/no/off) turns the default
off; =1 still opts in Mamba2 and the other mixers.
TRL before 0.24 leaves labels at each packed document's first token, and the
hybrid models run the transformers forward without the Llama-family boundary
guard, so the last token of one document was trained to predict the next
document while num_items_in_batch already excluded those targets. Mask them
out of place in the hybrid forward wrapper (a no-op on newer TRL).
…ls over the packed row, positional labels masked
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-12T13:24:30.771683Z f7a7b9a New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fe82d11bfb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/utils/packing.py Outdated
if mode == "auto" and not short_conv_only:
if probe_target is None:
return _hybrid_reject("no gated-delta mixer the exactness probe can run")
if not all(_auto_hybrid_device_ok(m) for m in gated_delta_modules):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply the CUDA gate to kwargs mixers

With Transformers 5.16+ gated-delta implementations, _is_kwargs_mixer places the Qwen mixers in kwargs_modules, after which they are removed from gated_delta_modules above. This all(...) therefore evaluates true for an empty list, allowing auto mode to probe and enable packing on CPU or ROCm whenever those kwargs kernels pass validation, despite the intended CUDA-only default. Validate kwargs_modules as well (or validate the pre-filtered gated-delta list) so an unset environment variable remains on the padded path outside CUDA.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, fixed in 466b607. The auto-mode device check now runs over every stateful mixer, kwargs-mode ones included, so transformers 5.16+ Qwen mixers on CPU or ROCm stay on the padded path unless UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1. Added test_default_on_is_cuda_only_for_kwargs_mixers, which fails without the change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 466b60795f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from packed-varlen-windows-fa4 to main October 12, 2026 12:33
@danielhanchen
danielhanchen merged commit d5824d0 into main Oct 12, 2026
@danielhanchen
danielhanchen deleted the hybrid-packing-default-on branch October 12, 2026 13:24
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 20, 2026
…-check (unslothai#18611)

Follow-up to unslothai#18313 and unslothai#17738.

## Why ROCm was opt-in

unslothai#13383 made hybrid packing (Qwen3.5, Qwen3.5-MoE, Qwen3-Next, and the
PLE layers from unslothai#14011) default-on for CUDA only. At the time
`UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1` failed closed on gfx1151 because
the boundary-aware causal conv was not allowed on HIP (unsloth-zoo unslothai#2503
fixed that), and once it worked, the full attention layers still ran
SDPA over a dense `(T, T)` mask on ROCm, so packing was a wash (unslothai#17738).
unslothai#18313 moved ROCm packed rows onto torch's flash varlen behind a
one-time self-check, which removes that cost.

## Change

With the variable unset, `_auto_hybrid_device_ok` now also accepts a
ROCm GPU when the unslothai#18313 self-check
(`hf_packed_attention._torch_varlen`) passes on that device. The check
runs once per device (about 0.3 s on gfx1151) and is cached. Everything
else is unchanged:

- The same mixer kinds as CUDA (gated delta and PLE), and the existing
exactness probe still runs before any packing.
- A ROCm build whose flash varlen fails the self-check keeps the padded
path, with the reason logged.
- `=0` still turns packing off and `=1` still opts in Mamba2 / split QKV
mixers and other devices.
- CUDA is unchanged.

The opt-in note from unslothai#17751 now says the path is "not on by default on
this device" instead of naming CUDA only.

## gfx1151, Linux, torch 2.11.0+rocm7.13, transformers 5.5.4

Fake Qwen3.5-4B shaped model (real 4B layer sizes, 4 layers, random
weights), LoRA r=16, `packing = True`, `max_length 2048`, batch 4,
variable unset vs `=0`. Two runs per arm.

| arm | packed | median useful tok/s | median s/step | first losses |
|---|---|---|---|---|
| main, unset | no (padded) | 1691 | 2.96 | 12.9115, 12.9003, 12.9244 |
| main, `=0` | no | 1687 | 2.95 | 12.9115, 12.9003, 12.9244 |
| this PR, unset | yes | 2417 | 3.38 | 12.9344, 12.8879, 12.9011 |
| this PR, `=0` | no | 1699 | 2.97 | 12.9115, 12.9003, 12.9244 |

Default ROCm runs now pack and train at about 1.42x the padded
throughput. The packed losses are the same values unslothai#18313 measured for
the opt-in path, and `=0` is unchanged.

## Tests

`tests/utils/test_hybrid_packing_default.py` adds a case with a ROCm GPU
weight where the self-check passes (default-on) and fails (padded,
reported as an opt-in device). Reverting the change fails the passing
case.
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.

1 participant