Repository navigation
SFT: pick padded batches + block compile over padding-free when micro batches are host bound - #15185
Conversation
…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.
… devices (not measured there)
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…onfig's default max_length [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
… 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.
When
padding_freeis 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 wheneverpacked_seq_lengthsis 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 whenpadding_freeis unset.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 frominput_ids, the text field,messages, prompt / completion, orformatting_func.Pick padded batches + block compile only when both hold:
So a 60-step notebook run stays padding-free.
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(defaultauto) forces either path.What padded means here: when padded is chosen,
padding_freeis left unset, the same stateUNSLOTH_DISABLE_AUTO_PADDING_FREE=1gives today, and a one-line message says why.Results
Setup:
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.
Across all 60 cells:
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:
Tests
New
tests/test_padding_choice.py(55 CPU tests) covers:On the existing padding-free / packing files, base and head both give 370 passed, 29 skipped.
On the local B200 (correctness only):
messagesdata for one epoch picks padded;padding_free=Trueis respected.Not covered
mfu.pypeak table, so the rule keeps padding-free there, although padded won +15% to +23% on that GPU in an earlier study.cu_seqlens/max_seqlen, and that is a separate change.