Skip to content

SFT: pick padded batches + block compile over padding-free when micro batches are host bound - #15185

Merged
danielhanchen merged 6 commits into
mainfrom
auto-padding-choice
Oct 25, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
auto-padding-choice

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

When padding_free is left unset, Unsloth's SFTTrainer patch always turns padding-free batching on. Padding-free batches bypass the per-decoder-layer block compile, because its forward skips the compiled region whenever packed_seq_lengths is passed. Padded batches run compiled.

On bf16 GPUs with short rows and small micro batches, a step is host bound: the GPU is busy only 10-20% of the step. In that regime, padded batches plus block compile are 11-31% faster, because block compile cuts kernel launch calls by 36-42% for the same GPU work. Everywhere else padding-free wins, often by a lot, because pad tokens cost exactly as much GPU time as real ones. So no fixed default is right for both.

Change

New unsloth/utils/padding_choice.py, called from the SFTTrainer patch only when padding_free is unset.

  1. Estimate GPU time per padded micro batch: LoRA linear FLOPs per token times padded tokens, plus attention FLOPs, divided by 0.5 x the datasheet peak. FLOP counts and peaks come from the existing unsloth/utils/mfu.py. Padded tokens are estimated by simulating batches from 512 sampled row lengths, taken from input_ids, the text field, messages, prompt / completion, or formatting_func.

  2. Pick padded batches + block compile only when both hold:

    • that estimate is under 0.10 s;
    • the run has enough micro batches to repay the extra compile: at least 1250 in 16-bit and 5000 in 4-bit. Padded batches compile about 24 s (16-bit) to 97 s (4-bit) more on A100 / L4.

    So a 60-step notebook run stays padding-free.

  3. Everything else keeps padding-free (today's default): Windows, ROCm / HIP, XPU / MPS / CPU, unknown GPUs, distributed runs, MoE, block compile not installed, unreadable lengths, or any exception.

Overrides: an explicit padding_free= on the config always wins. UNSLOTH_PADDING_CHOICE=padding_free|padded|auto (default auto) forces either path.

What padded means here: when padded is chosen, padding_free is left unset, the same state UNSLOTH_DISABLE_AUTO_PADDING_FREE=1 gives today, and a one-line message says why.

Results

Setup:

  • torch 2.14.1, transformers 4.57.6, TRL 0.24.0, LoRA r 16 with Unsloth gradient checkpointing;
  • 8 sequences per step (bs 2 x ga 4, bs 8 x ga 1, bs 16 x ga 1);
  • datasets: Alpaca, and Alpaca rows concatenated into 1k-4k token documents;
  • each run a fresh process with fresh compile caches, 3 interleaved reps;
  • steady-state real (non-pad) tokens / s.

Each cell is padded + block compile vs padding-free. The long-document rows of the 4B and 4-bit models behave like the 0.6B 16-bit ones (bs 2 from -1.3% to -15.9%, bs 8 from -28.2% to -34.3%, on every GPU), so they are left out. The A/A band is in brackets, and bold where this rule picks padded.

model segment A100 L4 T4 (Kaggle, fp16)
Qwen3-0.6B 16-bit Alpaca bs 2 +15.3% (2.6) +17.0% (3.5) +31.2% (6.6)
Alpaca bs 8 +11.0% (10.0) -1.3% -15.8%
Alpaca bs 16 +9.7% -55.7% -44.3%
long bs 2 -1.3% -15.8% -12.6%
long bs 8 -28.2% -34.2% -31.0%
Qwen3-0.6B 4-bit Alpaca bs 2 / 8 / 16 +15.8% / +11.7% / +10.3% +14.9% / +4.2% / -52.7% +29.3% / -12.1% / -35.3%
Qwen3-4B 16-bit Alpaca bs 2 / 8 / 16 +16.2% / +0.7% / -42.5% +3.0% / -44.4% / -57.3% -20.8% / -38.4% / -53.8%
Qwen3-4B 4-bit Alpaca bs 2 / 8 / 16 +15.0% / +3.0% / -40.8% +0.8% / -43.3% / -56.4% -1.7% / -34.3% / -50.3%

Across all 60 cells:

  • the rule switches 10 cells, all wins of +11% to +31% outside their A/A band;
  • it never picks padded where padded lost;
  • it averages +2.95% over the current default, against +3.53% for a perfect per-cell choice and -16.9% for always padded.

Missed wins: the rule leaves two A100 cells on padding-free, 0.6B 16-bit at bs 16 (+9.7%) and 0.6B 4-bit long at bs 2 (+3.2%).

Other measurements:

  • Loss: padded vs padding-free losses differ by at most 0.015, about the A/A spread.
  • Peak memory: within 7% in the cells the rule switches.
  • End to end (Colab A100, main / always padded / this PR, 3 reps): this PR picked padded exactly in the predicted cells (+14.5% to +17.1%) and matched main within A/A elsewhere.
  • Profiles: see the first paragraph. Where padded wins, it saves host time. Where it loses, the GPU computes pad tokens at 155 us per token in both arms, and padded attention grows with the longest row.

Tests

New tests/test_padding_choice.py (55 CPU tests) covers:

  • the FLOP estimate and length sampling for each dataset format;
  • the micro-batch threshold;
  • every fallback, including ROCm, Windows with CUDA and with ROCm, no-CUDA Linux and macOS;
  • the env override and the explicit config precedence;
  • the measured table, asserting padded is never chosen where padded lost.

On the existing padding-free / packing files, base and head both give 370 passed, 29 skipped.

On the local B200 (correctness only):

  • Alpaca bs 2 for one epoch picks padded, and Alpaca for 60 steps stays padding-free;
  • long bs 8 stays padding-free;
  • messages data for one epoch picks padded;
  • an explicit padding_free=True is respected.

Not covered

  • H100 and B200: no timing (Colab refused H100).
  • RTX PRO 6000: it is not in the mfu.py peak table, so the rule keeps padding-free there, although padded won +15% to +23% on that GPU in an earlier study.
  • Other stacks and settings: transformers 5.x / TRL 1.x, batch size 1, MoE, multi-GPU, ROCm and Windows were not run. The last four keep the current default by construction.
  • Calibration: the 0.5 efficiency factor is calibrated on Colab / Kaggle hosts. A much faster host CPU moves the crossover; the threshold is deliberately conservative.
  • Next lever: block compile for padding-free batches would combine both wins. It needs dynamic handling of cu_seqlens / max_seqlen, and that is a separate change.

…ro batches are host bound

Padding-free batches skip the per-block compile, so host bound micro batches (small batch, short
rows, fast GPU) run 10-17% slower than padded ones; GPU bound ones run up to 57% faster. When
padding_free is unset, estimate the padded micro batch's GPU time from the dataset's length
distribution, the model's LoRA FLOPs and the GPU's datasheet peak, and keep padded batches only
below 0.1 s and when the run is long enough to repay the extra compile. Every unknown keeps
padding-free. UNSLOTH_PADDING_CHOICE=padding_free|padded|auto overrides.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T03:06:59.898479Z e5c66fb 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.

@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: 9b4cd74968

ℹ️ 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/padding_choice.py Outdated
lengths = _sample_lengths(train_dataset, config, processing_class, formatting_func)
if not lengths:
return True, "dataset lengths unknown"
est = estimate_microbatch_tokens(lengths, bs, getattr(config, "max_length", None))

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 Estimate padding costs using the resolved training length

When SFTConfig.max_length retains its default of 1024 but the model was loaded with a larger max_seq_length, this clips sampled lengths to 1024 before the trainer resolves the actual cap. The generated SFT initializer in unsloth/models/rl.py subsequently replaces that default with the model's context length, so training processes longer rows than this estimate assumes. For example, with Qwen3-0.6B FLOPs, A100, batch size 2, and sampled lengths of 2000/4000, this estimates 49 ms and selects padded batches, whereas the actual lengths estimate 223 ms and should retain padding-free. Resolve the effective length using the same precedence as the trainer before estimating costs; otherwise ordinary long-document runs can automatically switch to the slower padded path.

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 e5c66fb. The estimate now clips sampled lengths to the cap training will actually use: the generated SFTTrainer init replaces SFTConfig's default max_length with the model's max_seq_length and keeps a caller-set value only below it, and _effective_max_length mirrors that precedence. Your example (default 1024, model at 4096, rows of 2000 / 4000 on A100) is now a test and keeps padding-free.

@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: e5c66fbd00

ℹ️ 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 6988ffc into main Oct 25, 2026
27 of 37 checks passed
@danielhanchen
danielhanchen deleted the auto-padding-choice branch October 25, 2026 03:40
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…wrap test _decode_graphs (#15209)

## Summary

Two merges left `Repo tests (CPU, rest)` red on main (for example on
#15199, base `0705fa58`):

1. **#15174 (tensor parallelism v2)** reads
`model.safetensors.index.json` with a bare `open()` at
`unsloth/models/tp_native.py:1636` and `:1660`, and its new test does
the same at `tests/test_tp_native_oracle.py:697`. #15185 (padded batches
vs padding-free) added `tests/test_padding_choice.py:267` with a bare
`read_text()`. The two encoding guards flag all four:

```
tests/test_runtime_text_encoding.py::test_shipping_code_names_an_encoding
  ['unsloth/models/tp_native.py:1660: open()', 'unsloth/models/tp_native.py:1636: open()']
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
  ['tests/test_padding_choice.py:267: read_text()', 'tests/test_tp_native_oracle.py:697: open()']
```

The two `tp_native.py` sites are product code, and the guard is right
about them: a checkpoint index read under a non-UTF-8 Windows locale can
fail or mis-decode.

2. **#15188 (decode graphs on by default for RL)** wrapped
`unsloth_unwrap_model_for_generation`'s generate in
`_decode_graphs.rl_generation()` and calls
`_decode_graphs.release_for_training(model)` on the way back to
training. `tests/test_ppo_trainer_patches.py` lifts that function out of
`rl.py` with `ast` and never gave it `_decode_graphs`, so both unwrap
tests stop with `NameError: name '_decode_graphs' is not defined`.

## Change

- `tp_native.py`, `test_tp_native_oracle.py`, `test_padding_choice.py`:
`encoding = "utf-8"` on the four reads.
- `test_ppo_trainer_patches.py`: the lifted function gets a
`_decode_graphs` whose `rl_generation` is the real scope from
`unsloth/models/_decode_graphs.py` (loaded by file path), with entering
it and `release_for_training` recorded in the existing `calls` list. The
PPO-policy test now asserts the full order: `for_inference`,
`rl_generation`, `release_for_training`, `for_training`. The plain-model
test asserts generation happens inside the scope before the release.

## Verification

- On main: the two encoding guards fail and both unwrap tests raise
`NameError`. With this change the encoding guards give `25 passed`, and
`test_ppo_trainer_patches.py`, `test_padding_choice.py` and
`test_tp_native_oracle.py` give `114 passed, 4 skipped`.
- Sabotage, each against `rl.py`:
1. generate outside `_decode_graphs.rl_generation()`: both unwrap tests
fail
  2. no `release_for_training` before training: both unwrap tests fail
-
`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process`
(5 cases) passes on main locally.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
… 5090 peaks (#15216)

Follow-up to #15185. Its padded-vs-padding-free rule was calibrated on
A100, L4 and T4 only, with one threshold of 0.10 s of estimated GPU work
per padded micro batch.

**On faster GPUs that threshold picks losing cells:**
- H100 / B200: their larger datasheet peaks make the estimate smaller,
so the rule switches cells nobody measured. On B200 that includes
Qwen3-4B Alpaca bs 8, which lost 18-44% on every GPU measured.
- RTX PRO 6000: measured on Colab G4. Adding its peak with the same 0.10
s threshold would pick a cell that loses 29%.

### Change
- **`padding_choice.py`, per compute capability thresholds:** used only
where measured.
- sm75 / sm80 / sm89 (T4 / A100 / L4): 0.10 s, decisions unchanged (a
test checks every measured cell).
  - sm120 (RTX PRO 6000 Blackwell): 0.06 s.
- Every other capability returns padding-free with reason `smXY not
measured`, the behaviour before #15185. That includes H100 / H200
(sm90), B200 / B300 (sm100 / sm103) and sm86.
- `choose_padding(..., capability = None)` keeps the old single
threshold for callers that pass no capability; `_decide` passes the
device's.
- **`mfu.py`, new dense 16-bit peaks:** these also give MFU logging a
peak on these GPUs.

  | name key | TFLOPs | source |
  |---|---|---|
| RTX PRO 6000 BLACKWELL MAX-Q | 438.9 | [RTX PRO Blackwell whitepaper
v1.1](https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/quadro-product-literature/pdf/NVIDIA-RTX-Blackwell-PRO-GPU-Architecture-v1_1.pdf),
Table 4 |
| RTX PRO 6000 BLACKWELL SERVER | 500.0 | [Server Edition
page](https://www.nvidia.com/en-us/data-center/rtx-pro-6000-blackwell-server-edition/),
sparse figure halved like the B200 entries |
  | RTX PRO 6000 BLACKWELL | 503.8 | same whitepaper, Table 4 |
| RTX 5090 | 209.5 | [RTX Blackwell whitepaper
v1.1](https://images.nvidia.com/aem-dam/Solutions/geforce/blackwell/nvidia-rtx-blackwell-gpu-architecture.pdf),
Table 3 (FP32 accumulate at half rate on GeForce) |

RTX 5090 D and the laptop part map to unknown. Every new key needs
"PRO", so "RTX 6000 Ada" and "Quadro RTX 6000" cannot match. A test
checks that no key is shadowed by an earlier one.

### Results
**Method:** Colab G4 ("NVIDIA RTX PRO 6000 Blackwell Server Edition"),
using the #15185 method:
- Qwen3 0.6B / 4B, LoRA r16, 16 and 4 bit;
- Alpaca at bs 2 / 8 / 16, and 1-4k token documents at bs 2 / 8;
- 3 rotated reps, every run a fresh process with fresh compile caches;
- steady-state real tokens/s.

**Padded vs padding-free, %** (A/A band in brackets):

| torch | model | alp b2 | alp b8 | alp b16 | long b2 | long b8 |
|---|---|---|---|---|---|---|
| 2.14.1 | 0.6B 16b | +5.4 (3.8) | +5.4 (32.2) | -29.2 (1.1) | -14.5 |
-37.0 |
| 2.14.1 | 0.6B 4b | +6.9 (5.3) | +5.1 (25.4) | -23.7 (2.3) | -14.0 |
-37.1 |
| 2.14.1 | 4B 16b | +5.2 (4.0) | -39.6 | -53.6 | -15.2 | -35.2 |
| 2.14.1 | 4B 4b | +7.2 (3.8) | -38.3 | -53.0 | -15.2 | -35.0 |
| 2.10.0 | 0.6B 16b | +23.6 (5.8) | +64.5 (15.2) | +59.6 (2.8) | -4.9 |
-16.5 |
| 2.10.0 | 0.6B 4b | +21.5 (1.7) | +55.9 (16.6) | +63.2 (1.1) | -4.8 |
-16.6 |
| 2.10.0 | 4B 16b | +24.1 (3.6) | -19.3 | -40.3 | -12.5 | -25.4 |
| 2.10.0 | 4B 4b | +14.8 (4.5) | -18.1 | -39.8 | -12.4 | -25.4 |

**What the rule picks:**
- **This PR:** on G4 it picks only 0.6B Alpaca bs 2 / 8 and 4B Alpaca bs
2 (estimates 6-45 ms). Those win on both torch versions, and none loses
beyond its A/A band.
- **The old 0.10 s threshold:** would also pick 0.6B Alpaca bs 16
(estimate ~92 ms), which loses 29% (16-bit) and 24% (4-bit) on torch
2.14.1.

**Memory and loss:** in the picked cells, padded uses 0.02-0.33 GB more
peak memory, the same order as the cells #15185 already picks. Per-step
loss differences stay at or below 0.01.

### Tests
New CPU tests in `tests/test_padding_choice.py` and
`tests/test_mfu_logging.py`:
- every G4 cell against the Server, Workstation and Max-Q peaks, so no
losing cell is picked;
- a guard that the old threshold would pick the losing cell;
- T4 / A100 / L4 decisions unchanged;
- unmeasured capabilities (sm86, sm90, sm100, sm103, sm121) keep
padding-free;
- name order and shadowing in the peak table.

Both files give 134 passed.

### Not covered
- **H100:** not measured; Colab gave no H100 in more than an hour of
retries. H100 and B200 go back to padding-free until measured.
- **Other sm120 parts:** the RTX 5090, Workstation and Max-Q peaks come
from datasheets, with no timing.
- **Host CPU:** the 0.06 s threshold comes from a 48 vCPU Colab host.
- **Scope:** ROCm, Windows and Mac are unchanged (padding-free before
this logic runs). Qwen3 dense models only, single GPU.
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