Skip to content

Studio: batch packed fine-tuning jobs, each job packing only its own documents - #15733

Merged
danielhanchen merged 8 commits into
mainfrom
studio-ft-batch-packing
Oct 28, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-ft-batch-packing

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Since #15478 turned packing on by default, every queued fine-tuning job asks for packing, and #15344 sent packing jobs to train alone. So compatible jobs stopped batching at all, and three batching tests in studio/backend/tests/test_openai_fine_tuning.py fail on main (test_compatible_queued_jobs_start_as_one_batch, test_jobs_differing_only_in_member_fields_batch_in_queue_order, test_only_plain_dense_models_batch[dense]).

This PR lets packing jobs batch, with packing kept per job so a job's documents never meet another job's:

  • Each member packs only its own documents, with TRL's default packing strategy at the run's max length, the same packing its single run would get. Pre-tokenized datasets stay unpacked, as in the single run.
  • Once any member packs, each micro-batch is one padding-free row, as in the single packed run: positions restart at every document, packed_seq_lengths is passed to the model, every token is routed to its own member's adapter, and the label opening each document is masked so nothing is predicted across a boundary. A document never spans two members.
  • Packing is used only where the single job's Unsloth SFTTrainer would pack: not on padding-free blocklisted models, encoder-decoders, forwards that cannot take packed_seq_lengths, or hybrid linear-attention models whose varlen kernels are not available (their recurrent state would carry across documents). Elsewhere packing is ignored, as the single job ignores it.
  • Packing is also used only where a packed forward provably keeps documents apart: before packing, one forward of a short document after another in one packed row is compared with that document alone, and a model whose packed documents see each other trains unpacked with a warning. Qwen3.5 on transformers 5.3 (Studio's tier for it) passes every static check above, yet its full attention layers let packed documents attend across the boundary (logits off by up to 14.7 against 0.36 elsewhere); the root cause is fixed in core by Keep packed documents apart under flash attention when layers get mRoPE position ids #15771, and this check keeps batched jobs isolated on any install that lacks it.
  • Vision-language models (Qwen3.5, Qwen3.6) tokenize their text through the processor's tokenizer, as the single job does; the full processor is still what gets saved.
  • packing is now a per-member field, so packed and unpacked jobs can share a batch; an unpacked member in a packed batch trains exactly as it would alone.

Tests (CPU, tiny Qwen3; studio/backend/tests/test_multi_lora_trainer.py):

  • a packing member's losses and saved adapter are the same with a different neighbour and alone, and every packed document holds one adapter's tokens with positions restarting at each;
  • an unpacked member beside packed ones matches its own run;
  • packing is ignored when the model cannot pack; a hybrid packs only with its varlen kernels;
  • packed rows keep each document's labels with its tokens.

Negative control: with positions not restarting per document, the isolation checks fail. All of test_multi_lora_trainer.py, test_openai_fine_tuning.py and test_training_batch_backend.py pass (113).

GPU, through the OpenAI-compatible API on a fresh install.sh --local Studio (Qwen3-0.6B, 4-bit and 16-bit; a job trained alone, then the same job batched beside another while a third holds the GPU; 16 documents, 20 steps, packing on by default):

GPU mode batched job packed steps alone / batched step 1 loss alone / batched final loss alone / batched learning rate
RTX PRO 6000 (bf16) 4-bit 16 documents into 1 row 20 / 20 2.2689 / 2.2807 0.00017 / 0.00027 identical every step
RTX PRO 6000 (bf16) 16-bit 16 documents into 1 row 20 / 20 2.6012 / 2.5983 0.00016 / 0.00019 identical every step
T4 (fp16) 4-bit 16 documents into 1 row 20 / 20 2.2761 / 2.2772 0.00058 / 0.00020 see below
T4 (fp16) 16-bit 16 documents into 1 row 20 / 20 2.6012 / 2.6012 0.00017 / 0.00015 see below

The single run packed too ("Unsloth: Packing enabled") on every arm. On the T4 the learning-rate schedules drift apart after the single run skips a step on an fp16 overflow while the batched job does not; that comes from the batch sharing one fp16 loss scale, which is on main already and is fixed separately in #15741.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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 ✅ Completed 2026-10-28T13:14:49.223712Z d0ea258 Manual request
ℹ️ 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.

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 240bf52a98

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 8f93372590

ℹ️ 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".

packs = _packs(model) if packs is None else packs
if packs:
documents = len(member.rows)
member.rows, member.seq_lengths = _pack_rows(member.rows, max_length)

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 Preserve overlength documents before legacy wrapped packing

On supported TRL versions below 0.20, packed jobs now enter batching, but _tokenize_member has already truncated every document to max_length via build_tokenizing_transform before this call. Legacy wrapped packing should retain the overflow: the single-job path explicitly disables early truncation in unsloth/models/rl_replacements.py, and test_wrapped_packing_preserves_overlength_tokens verifies that behavior. Consequently, a document longer than the context window silently loses its remaining tokens when queued alongside another job, changing the training data and potentially the number of optimizer steps. Resolve the effective packing strategy before tokenization and bypass early truncation for wrapped packing.

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.

Not reachable in Studio: batched training runs only inside Studio's training worker, which installs trl==0.23.1 (studio/backend/requirements/extras-no-deps.txt), where pack_dataset takes a strategy and BFD packing truncates each document to max_length exactly as the batched path does. The legacy fallback only keeps a pre-0.20 TRL from crashing.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…r; pack with the single job's worker count

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9ccab09e41

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 28, 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

Copy link
Copy Markdown

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

Reviewed commit: d0ea258399

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 75555cc into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the studio-ft-batch-packing branch October 28, 2026 13:46
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 28, 2026
…PE position ids (unslothai#15771)

On transformers 5.3, Qwen3.5 and Qwen3.5-MoE hand their decoder layers
the 3-row mRoPE position ids instead of the text position ids (5.5 and
later pass the text ids). Flash attention finds document boundaries in a
packed row from the position ids, so with mRoPE ids it cannot see them:
since unslothai#12856 stopped those ids from being read as three packed rows (the
out-of-bounds crash in huggingface/transformers#44910), flash attention
runs one causal span over the whole packed row, and every packed
document attends to the documents before it.

This is what Unsloth Studio hits when it trains Qwen3.5 with packing:
Studio runs Qwen3.5 on its transformers 5.3 side environment with flash
attention, so packed documents leak into each other there. The Gated
DeltaNet layers were already kept apart by Unsloth's varlen kernels;
only the full attention layers leaked.

### Fix

When a flash attention call gets an Unsloth packed row
(`packed_seq_lengths`, one row, no attention mask, no `cu_seq_lens_q`
from the caller) and its position ids have more than two dimensions, the
document boundaries are taken from `packed_seq_lengths` and passed as
`cu_seq_lens_q/k` and `max_length_q/k`, which flash attention already
takes ahead of position ids. Every other call is passed through
unchanged:

- no `packed_seq_lengths` (anything that is not Unsloth packing,
inference, generation): untouched, one dict lookup
- 2D position ids (every model on transformers 5.5+, and every non-mRoPE
model): untouched, flash attention finds the boundaries itself as before
- a padding mask, a batch of more than one row, caller supplied
`cu_seq_lens_q`, or lengths that do not cover the row: untouched

### Evidence

Probe on Qwen3.5-0.8B inside a fresh `install.sh --local` Studio, in
each of its transformers environments (L4, flash attention 2): a 61
token document followed by a 41 token document in one packed row, versus
the second document alone. Max logit difference; shifting the document's
positions alone moves the logits by 0.36, so anything near that is
isolated.

| transformers | without the fix | with the fix |
|---|---|---|
| 5.3.0 (Studio's Qwen3.5 tier) | 14.75 | 0.44 |
| 5.5.0 | 0.44 | 0.44 |
| 5.10.2 | 0.44 | 0.44 |

"Without the fix" is the same packed forward without
`packed_seq_lengths`, so the patch cannot engage; on 5.3 that is the
path every Unsloth packed row took before. Per layer on 5.3, the first
full attention layer (layer 3) now differs by 0.012, like the linear
attention layers around it (an earlier probe had it at 0.117, where the
leak starts).

On 5.5 and 5.10 the patch does not engage (2D position ids reach the
layers), and Qwen3-0.6B (no mRoPE) gives 0.79 on all three, against 0.96
for shifted positions.

End to end through Studio's fine-tuning API (Qwen3.5-0.8B on RTX PRO
6000, packing on, 16 documents, 20 steps; a job trained alone, then the
same job batched beside another, on unslothai#15733 with this fix merged in).
Without the fix, Studio's packing check finds the packed documents not
isolated on 5.3 and trains the batch unpacked, and the job trained alone
leaks across its own documents. With it:

| mode | packing check | batched job packed | step 1 loss alone /
batched | step 20 loss alone / batched | learning rate |
|---|---|---|---|---|---|
| 4-bit | isolated | 16 documents into 8 rows | 0.8034 / 0.8004 | 0.0000
/ 0.0001 | identical every step |
| 16-bit | isolated | 16 documents into 8 rows | 0.7438 / 0.7444 |
0.0000 / 0.0000 | identical every step |

Tests in `tests/test_flash_attention_mrope_packed.py` cover the boundary
kwargs, every pass-through case, idempotency, and (on CUDA with
flash-attn) that a packed row's output matches each document's attention
computed alone. All 10 pass with flash-attn 2.8.4 in each of Studio's
environments (transformers 5.3.0, 5.5.0, 5.10.2). Negative control: the
same packed-row call with the patch removed differs from per-document
attention by 2.91 (bf16) on all three versions, against 0.0 with it, so
the CUDA test fails without the fix.
debojyoti-dev pushed a commit to debojyoti-dev/unsloth that referenced this pull request Oct 29, 2026
…s kernels (unslothai#16012)

Batched multi-LoRA training on fused MoE experts (Studio training
several queued jobs together on Qwen3 MoE, Qwen3.5 / Qwen3.6 MoE such as
Qwen3.6-35B-A3B, unslothai#15742 and unslothai#15733) now runs every adapter's expert LoRA
in one grouped pass, on the same Unsloth Zoo grouped GEMM kernels a
single job uses, instead of running the experts once per adapter. 1.3x
to 2.1x faster per MoE layer with 2 to 8 jobs, bit-identical results.

Until now `MultiLoraExperts.forward` looped over the adapters in the
batch and ran the experts module on each adapter's tokens: per MoE layer
and step, one routing sort, gather, unpermute and set of grouped GEMM
launches per adapter, and one read (with QLoRA, one dequantize) of the
frozen expert stacks per adapter.

### How it works

* Routes are sorted once by `expert * (U + 1) + adapter`, with
fixed-size counts (no `bincount`, so no host sync and a static shape
under compile). Each expert's rows stay contiguous, so the same permuted
rows serve two group layouts: E groups for the frozen base and E x (U +
1) groups for LoRA. Rows of no adapter go to slot U, whose LoRA factors
are zero; dropped routes (expert id outside the table) read a zero row
with weight 0, so they add exactly nothing and cannot overflow into a
gradient.
* Base: Unsloth Zoo's own base GEMM, with the weight provider, recompute
in backward and selective 4-bit dequant its single-job MoE forward uses,
called once per projection for every adapter together.
* LoRA: two of Zoo's grouped GEMMs per projection (its Triton kernels
where they apply) over the E x (U + 1) pair groups, on every adapter's
factors stacked, zero-padded to the largest rank rounded up to 8, with
each adapter's scale (alpha / r or rsLoRA alpha / sqrt(r)) folded in.
The factor orientation is the per-adapter stash path's, so every PEFT
version and input-major stacks work unchanged.
* Routes are combined as Zoo's forward does: its gate-gradient identity
and fused weighted unpermute (deterministic fallback without Triton).
Gradients reach hidden states, routing weights and every adapter's A and
B; adapters absent from a batch get exact zero gradients and stay in the
graph for DDP.

So a call is 2 base + 4 LoRA grouped GEMMs whatever the number of jobs,
and the expert stacks are read and dequantized once. An earlier version
of this PR called `torch._grouped_mm` directly; on A100 / L4 that op
runs one matmul per group (21,504 launches in three steps at Qwen3.6
shapes), which was 7x to 15x slower than the per-adapter path. Building
on Zoo's kernels fixed that and keeps the numerics identical to a single
job.

### When it runs

Decided per layer on the first call, after the existing stash / fold
check: fused 3D `gate_up_proj` / `down_proj` with an `act_fn`, no
biases, not interleaved (GPT-OSS), no custom gate, not MXFP4, LoRA only
on those two stacks, 16-byte aligned rows, a Zoo with its grouped MoE
GEMMs and a grouped GEMM kernel for the device and dtype (Zoo's Triton
kernels, else torch's grouped GEMM), then a no-grad parity check on a
few rows per adapter against the per-adapter path. After that, a batch
where only one adapter has tokens runs that adapter's own pass (nothing
to fuse; it is faster there), and inside a compiled graph non-bf16 calls
run per adapter (torch's grouped GEMM only traces in bf16).

Anything else keeps the per-adapter path exactly as before and logs why
once; `UNSLOTH_MULTI_LORA_MOE_GROUPED=0` forces it. A single job never
reaches this module (it only exists in batched multi-LoRA training) and
Zoo's MoE forward is unchanged, so single-GPU single-job training is not
touched. The saved adapter's layout follows how a lone PEFT load applies
LoRA, not the training mode, so adapters trained grouped reload exactly
as before. `UNSLOTH_ENABLE_LOGGING=1` prints one line per experts class
when the grouped pass engages.

### Speed and memory

One Qwen3.6-35B-A3B MoE layer (hidden 2048, expert intermediate 512, 256
experts, top 8), forward + backward, 2048 tokens per job, rank 16, bf16,
A100 80GB, a fresh process per measurement, ABBA order, 3 repeats (A/A
noise under 0.2%); per-adapter path vs this PR:

| jobs | 16-bit ms | speedup | 4-bit ms | speedup | peak memory 16-bit /
4-bit |
|---|---|---|---|---|---|
| 1 | 5.59 vs 6.52 | 0.86x | 7.90 vs 8.43 | 0.94x | 0.96x / 1.00x |
| 2 | 11.87 vs 9.03 | 1.31x | 16.18 vs 11.70 | 1.38x | 1.03x / 1.03x |
| 4 | 23.01 vs 14.73 | 1.56x | 32.84 vs 17.37 | 1.89x | 1.16x / 1.07x |
| 8 | 45.92 vs 29.11 | 1.58x | 67.00 vs 31.70 | 2.11x | 1.30x / 1.12x |

Skewed (Zipf) routing gives the same speedups. Mixed ranks 8 / 16 / 32 /
64 (padded to 64): 1.19x with 4 jobs, 1.25x with 8. In every cell the
two paths give bit-identical outputs, input gradients and LoRA
gradients. The one-job row is why a batch with a single adapter's tokens
now runs that adapter's own pass. Peak memory per layer grows with the
number of jobs (up to 1.3x at 8 jobs in 16-bit), since every job's
stacked factors and intermediates live for the one fused pass.

### Tests

`tests/test_multi_lora_experts.py` (36, CPU; also run on GPUs below):

* Existing tests run in grouped, stash and fold modes: parity with a
lone PEFT run, gradients, isolation (other adapters' rows bit-identical
when one adapter changes), absent adapter with NaN weights, input-major
layout, autocast, gradient checkpointing against eager.
* float64 oracle for grouped: non-square dims, ranks 2 / 4 / 3 with
unequal alpha, rsLoRA, rows of no adapter, an expert never routed,
skewed routing, a dropped route, an absent adapter; output and gradients
for hidden states, routing weights and every A and B.
* One pass: 2 base + 4 LoRA GEMMs per call for 2 and 3 jobs; one present
adapter runs its own pass with the same result; real bitsandbytes NF4
stacks through Zoo's provider; a dropped route with a NaN weight changes
nothing forward or backward; empty top-k;
`torch.compile(fullgraph=True)` in bf16 and fp32 on the test device.
* Engagement counters (`MULTI_LORA_MOE_STATS`) and fallback for expert
biases or a wrong grouped result.
* Negative controls: swapping adapter slots, not folding the scale,
sending rows of no adapter to adapter 0, removing the dropped-route
zeroing, removing the compile dtype gate, or removing the empty top-k
guard each turns a test red.

`tests/test_multi_lora.py`, `tests/test_multi_lora_absent_nan_a_dx.py`:
unchanged, pass. torch 2.6, 2.8, 2.10 (CPU): 35 passed each.

GPU, an independent float64 oracle per mode, dtype and scenario, each
with a negative control that must disagree: grouped matches the oracle
with the same error as the existing stash path on T4 (fp32, fp16), L4,
A100 and G4 (fp32, bf16). Under bf16 autocast, grouped logits are as
close to an fp32 run as the per-adapter path's (max 0.0045, mean 0.0005
on A100 and G4). Unaligned dims decline grouped; the fp16 fold path on
unaligned dims errors on main too (Zoo's grouped GEMM stride rule),
unchanged here.

Studio end to end through the fine-tuning API (tiny Qwen3.6 MoE, a job
trained alone, then batched beside another, 20 steps, LoRA and QLoRA),
with the grouped pass engaged in every batched run (its log line in both
batched runs on each GPU) and both packed and batched as before:

| GPU | mode | step 1 loss alone / batched | step 20 | learning rate |
|---|---|---|---|---|
| L4 (bf16) | 16-bit | 12.3844 / 12.3843 | 12.1696 / 12.1679 | identical
every step |
| L4 (bf16) | 4-bit | 12.3861 / 12.3862 | 12.1698 / 12.1669 | identical
every step |
| T4 (fp16) | 16-bit | 12.3844 / 12.3844 | 12.1696 / 12.1679 | identical
every step |
| T4 (fp16) | 4-bit | 12.3861 / 12.3861 | 12.1697 / 12.1669 | identical
every step |
danielhanchen added a commit that referenced this pull request Nov 18, 2026
#18324)

## Multi-LoRA packing: load the num_proc policy without importing
unsloth


`studio/backend/tests/test_dataset_map_num_proc.py::test_the_batched_packing_pool_asks_the_same_veto`
fails in `(Python 3.13, a-f)` on every PR since #17701, for example
#18015, #18108, #18142 and #18303:

```
core/training/multi_lora_trainer.py:686: in _pack_num_proc
    from unsloth_zoo.dataset_num_proc import get_dataset_num_proc
E   ModuleNotFoundError: No module named 'unsloth_zoo'
core/training/multi_lora_trainer.py:688: in _pack_num_proc
    from unsloth.dataset_num_proc import get_dataset_num_proc
unsloth/_gpu_init.py:241: in <module>
E   ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo` then retry!
```

### Cause

`_pack_num_proc`, the multi-LoRA packing pool's worker count from
#15733, looks up the shared `dataset_num_proc` policy in two steps:

1. it imports `unsloth_zoo`;
2. if that fails, it falls back to `from unsloth.dataset_num_proc import
...`.

That fallback runs the whole `unsloth` package `__init__`, which needs
`unsloth_zoo` anyway and patches torch on the way.

The rest of the backend already avoids this.
`utils.hardware.hardware._shared_policy()` tries `unsloth_zoo` first and
otherwise loads the stdlib-only `dataset_num_proc.py` straight off disk,
precisely so that no caller runs `import unsloth`.

#17701 added the first test that reaches `_pack_num_proc`, and the
backend shard runs without `unsloth_zoo`, so the fallback fails there.

### Fix

`_pack_num_proc` now gets the policy from `_shared_policy()`, the same
loader the single-job tokenize pool uses.

- **With a policy**, which is every real install: the call is unchanged,
`get_dataset_num_proc(count)` on the same module.
- **With no policy at all:** it keeps that function's contract, so a
serial count of 1 still means `None`.

### Verification

- Faithful repro of the CI state: `core.training.trainer` already
imported, then `unsloth_zoo` made unimportable, then `_pack_num_proc`
called with a tight host-memory snapshot.
  - `main`: `ModuleNotFoundError: No module named 'unsloth_zoo'`.
  - This PR: returns `None`, as the test expects.
- With `unsloth_zoo` installed: `tests/test_dataset_map_num_proc.py` and
the multi-LoRA tests pass (88 passed).
- ruff is clean.
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