Skip to content

Studio: give each batched fine-tuning job its own fp16 loss scale - #15741

Merged
danielhanchen merged 14 commits into
mainfrom
studio-ft-batch-fp16-scale
Oct 28, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
studio-ft-batch-fp16-scale

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

On fp16 GPUs (T4, V100, any card without bf16), batched fine-tuning shares one loss scale (accelerate's GradScaler) between every job in the batch. So one job's overflow skips the optimizer step of every job in the batch, halves the scale the others train with, and holds their learning-rate schedules, and the step a job skips depends on which jobs it was batched with. On a T4 (Qwen3-0.6B, 16-bit) the same job trained alone skipped its step 6 on an fp16 overflow and kept its learning rate, while inside a batch it did not skip, so its schedule ran one step ahead from there (max relative learning-rate difference 0.5 to 0.75, against 0.0 on a bf16 GPU).

This PR gives each job its own loss scale, with torch.amp.GradScaler's defaults and rules (2^16 to start, halved on overflow, doubled after 2000 finite steps):

  • Each job's gradient is scaled by its own scale, in fp32 at its logits before the fp16 backward, exactly where GradScaler scales the loss. Jobs share no trainable weight and a logit's gradient comes only from its own job's loss, so each adapter's gradient carries only its own scale.
  • Each job's gradients are unscaled and checked on their own, with one host read per job per step. A job with an overflow has its gradients dropped for that step (the optimizer leaves its parameters and state alone), its scale halved and its learning-rate schedule held, and it reports no gradient norm for that step, as the single job does. Every other job steps normally.
  • bf16 and fp32 runs are unchanged.

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

  • with the per-job scale forced on, every job trains as without it;
  • an overflow injected into one job's first step skips only that job's step: the other jobs' losses and saved adapters are bit-identical to the run without the overflow, and the job that overflowed reports no gradient norm and keeps its learning rate for the next step;
  • the scale follows GradScaler's growth and backoff rules.

Negative control: dropping every job's step when one job overflows (what the shared scaler did) fails the isolation test.

GPU, T4 (fp16), Qwen3-0.6B 16-bit, through the OpenAI-compatible API on a fresh install.sh --local Studio. Job B trained in a batch beside a normal job C, then again beside a job C whose learning rate (0.9) makes its fp16 gradients overflow from step 4 on (C skipped steps 4 to 20):

B, beside the overflowing C step 4 step 5 step 10 step 20
before (one shared scale): loss / learning rate 0.0480 / 0.0006 0.0480 / 0.0006 0.0480 / 0.0006 0.0480 / 0.0006
after (one scale per job): loss / learning rate 0.0480 / 0.0006 0.0113 / 0.0008 0.00101 / 0.00073 0.00015 / 0.000067
B beside the normal C (both): loss / learning rate 0.0480 / 0.0006 0.0113 / 0.0008 0.00101 / 0.00073 0.00015 / 0.000067

Before this PR, B stopped training at step 4 for the rest of the run because its neighbour overflowed. With it, every one of B's 20 steps (loss, learning rate, gradient norm) matches its run beside the normal job.

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@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-28T15:01:05.108897Z 07a7940 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 04b139b0f7

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

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: e8567ec359

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

grads = [p.grad for p in params if p.grad is not None]
for g in grads:
g.div_(self.scale[slot])
finite = all(bool(torch.isfinite(g).all()) for g in grads)

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 Aggregate gradient finiteness checks before synchronizing

On fp16 CUDA runs, converting each gradient's finiteness result to a Python bool synchronizes the CPU with the GPU separately for every parameter tensor. Each member has two tensors per targeted layer, so targeting all linear layers causes hundreds or thousands of serialized device synchronizations per optimizer step, multiplied by the number of batched jobs. This replaces GradScaler's batched device-side checking and can substantially reduce training throughput. Accumulate the non-finite flag on-device, preferably using a fused unscale/check operation, and read it back only once per member.

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.

Fixed in dd323f2: gradients are unscaled with one foreach multiply and the finiteness flags are stacked on device, so each member needs a single host read per step.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

Base automatically changed from studio-ft-batch-packing to main October 28, 2026 13:46
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
…documents (unslothai#15733)

Since unslothai#15478 turned packing on by default, every queued fine-tuning job
asks for packing, and unslothai#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 unslothai#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 unslothai#15741.
…scale

# Conflicts:
#	studio/backend/core/training/multi_lora_trainer.py
#	studio/backend/tests/test_multi_lora_trainer.py

[skip ci]
@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. Keep them coming!

Reviewed commit: 07a7940fd5

ℹ️ 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 795da3b into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the studio-ft-batch-fp16-scale branch October 28, 2026 15:10
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