Skip to content

[perf] Qwen3.5-9B LoRA SFT with unsloth-cli.py on a B200: 0.84 s to 0.77 s per step at 1 GPU, the model-independent half of #10744 - #11238

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
TarzanZhao:perf/trainer-bnb-fla-host-overhead
Sep 21, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
TarzanZhao:perf/trainer-bnb-fla-host-overhead

Conversation

@TarzanZhao

@TarzanZhao TarzanZhao commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The model-independent half of #10744, rebuilt on today's main (1d5210d7a): two patches in unsloth/models/_utils.py, +66 lines in one file, nothing from _qwen3_5_layer.py and no new compiled region.

A 120-step LoRA SFT of unsloth/Qwen3.5-9B through unsloth-cli.py keeps the GPU busy for roughly a third of an 841 ms step; the rest is the CPU issuing kernels through Python (profile in #10806). These two patches remove host work that repeats on every micro-step. On the one B200 I measured, the step goes from 840.6 ms to 769.0 ms, 1.09x.

  1. Skip the model.train() walk that training_step repeats on every micro-step. On the PEFT-wrapped 9B model that is a recursive walk over about 2,000 modules with a __setattr__ each, four times per step. Train mode is asserted once and again after any root .eval(), so a submodule flipped to eval on its own now keeps that mode where the stock loop would flip it back.
  2. Launch fla's autotuned Triton kernels with the cached config. unsloth_zoo's compile_fla_no_autotune already pins one config through _ReuseBestCache, yet every launch still built fla's AutotuneKey and then Triton's own key to look up an answer that cannot change. Once the config has settled the kernel is launched with it directly, so this fires only for models that use fla's autotuned kernels (gated-deltanet: Qwen3.5, Qwen3.6, Qwen3-Next).

Not everything model-independent from #10744 is here. The floating_point_ops parameter count cache measured 7.3 ms slower in the chain, so there is nothing to claim for it. The preserve_rng_state=False default never executes under --use_gradient_checkpointing unsloth, and its guard has the problem I described in #10744.

Speedup Result

Measured on one B200, at --lora_dropout 0, on torch 2.11.0, transformers 5.5.0 and triton 3.6.0.

baseline (1d5210d7a) this PR change
training step, median of steps 51 to 120 840.6 ms 769.0 ms 1.09x, −71.6 ms
peak GPU memory, allocated 19.19 GB 19.19 GB

Four runs per arm, interleaved as a balanced Latin square over four rounds so that neither arm sits at a fixed position in the session, every run under the same NUMA pin, with an idle-GPU check and a cool-down before each. Run to run the four baseline medians span 9.7 ms (1.2 %) and the four branch medians 7.7 ms (1.0 %), against a difference of 71.6 ms.

The 769.0 ms arm of that square carried a third host-side patch that is not in this PR. The tree exactly as it stands here was timed in a second block, four more pairs interleaved against that arm: the difference is +6.1 ± 14.9 ms, inside the run-to-run spread, and those four runs read 770.6 ms on their own, which is 1.09x and −70.0 ms against the same baseline. Either reading gives the same ratio.

Reproduced in review on a different stack, torch 2.13+cu130 with transformers 5.17.0 and triton 3.7.1, where the same job's baseline step is 1,640 ms rather than 841 ms: eight interleaved pairs, the head faster in seven of seven kept pairs, −78.1 ms with a 95% CI of [−94.0, −63.2] and a ratio of 1.049x. The milliseconds carry across; the ratio does not, because it is the same saving over twice the denominator. Read −72 to −78 ms on a B200 as the claim and the ratio as whatever that is on the stack in question.

Per change, paired within each round of the square:

commit change measured effect
ee46e130 skip the per-micro-step model.train() walk −27.4 ms (sd 10.3)
7b45cc8f fla kernels launched with the cached config −46.3 ms (sd 8.6)

The fla launch path is most of it. The two paired deltas sum to −73.7 ms against the −71.6 ms measured end to end across the square, a 2 ms disagreement against per-round spreads of 9 to 10 ms.

Correctness Verification

I ran the unmodified 1d5210d7a and this branch over the same 120 steps of the same data in the same environment, and compared 16 recorded quantities: 480 unrounded per-micro-step losses, batch shapes and token ids, the final-norm hidden states at steps 1 and 120, 256 LoRA weight norms plus three layers in full at steps 10, 60 and 120, and peak memory. Tolerances were set before the runs at three times the largest pairwise spread of three runs of the unmodified code, with floors of 0.002 absolute on the loss and 0.5 % on hidden states. The recorder wraps unsloth-cli.py and patches trl.SFTTrainer from outside the repo, so both checkouts ran unchanged; it is not part of this PR.

All 16 checks pass, and the step-1 hidden states are bit-identical between the two trees. #10744 could not claim that, and the difference is not luck: the two checks that failed there came from the fused Qwen3.5 layer and the Gated DeltaNet compiled region, neither of which is in this PR. These two changes add no compiled region and no new kernel, and the fla patch launches the config _ReuseBestCache would have returned anyway, so it runs the same kernel with the same parameters.

recorded baseline vs this PR tolerance
peak GPU memory allocated, end of run 19.19 GB on both +20 %
language_model.norm output, first 32 positions, step 1 / step 120 0 (bit-identical) / 21 % 0.5 % / 110 %
language_model.norm output, mean and std of the whole tensor, step 1 / step 120 0 / 0.13 % 0.5 %
loss per micro-step, unrounded, steps 1 to 20 / 21 to 60 / 61 to 120 0.0011 / 0.0022 / 0.0012 absolute 0.0031 / 0.0113 / 0.0096
LoRA weight norms, 256 tensors, largest relative change, step 10 / 60 / 120 0.41 % / 1.05 % / 1.23 % 1.9 % / 13.4 % / 20.0 %
LoRA A and B of layers 0, 15 and 31 in full, largest relative norm of the difference, step 10 / 60 / 120 5.5 % / 14 % / 15 % 28.9 % / 112.6 % / 111.9 %
number of loss records, steps 1 to 120 480 on both exact
batch shapes, token counts, first 8 ids and ignored-label counts, steps 1 to 8, 60 and 120 identical exact

The final loss is 0.9341 on this branch against 0.9342 on the baseline; the 20 timed runs of the session landed between 0.9324 and 0.9354 on either arm.

Details: hardware, model, full command, measurement setup

Hardware. One B200 (sm_100) of an otherwise empty 8-GPU node, 2 x Xeon Platinum 8562Y+ (128 threads, 2 NUMA nodes; GPUs 0 to 3 on node 0), driver 580.126.20, CUDA runtime 12.8. Python 3.13.15, torch 2.11.0+cu128, triton 3.6.0, transformers 5.5.0, trl 0.24.0, peft 0.20.0, bitsandbytes 0.50.2, unsloth_zoo 2026.9.2 with its vendored fla 0.5.1. No flash-attn, no causal-conv1d, no separate fla-core. Nothing was installed, flagged or tuned on top for these runs; a sweep of install and environment options found none that beat the run-to-run spread.

Job. unsloth-cli.py LoRA SFT of unsloth/Qwen3.5-9B on yahma/alpaca-cleaned, bf16, sequence cap 2048, micro-batch 2 with gradient accumulation 4, LoRA r16 / alpha 16 / dropout 0 on the script's seven projections, --use_gradient_checkpointing unsloth, adamw_8bit, lr 2e-4 linear with 5 warm-up steps, seed 3407, 120 steps, one process on GPU 0.

CUDA_VISIBLE_DEVICES=0 numactl --cpunodebind=0 --membind=0 python unsloth-cli.py \
    --model_name unsloth/Qwen3.5-9B --dataset yahma/alpaca-cleaned \
    --max_seq_length 2048 --r 16 --lora_alpha 16 --lora_dropout 0.0 --bias none \
    --use_gradient_checkpointing unsloth --random_state 3407 \
    --per_device_train_batch_size 2 --gradient_accumulation_steps 4 \
    --warmup_steps 5 --max_steps 120 --learning_rate 2e-4 --optim adamw_8bit \
    --lr_scheduler_type linear --logging_steps 1 --seed 3407 --report_to none

Measurement. Step time is the difference of consecutive stamps from the Trainer's own tqdm bar through TQDM_BAR_FORMAT, so the repo is not modified to measure it; the reported number is the median of steps 51 to 120, by which point the per-step time has settled. Within a run the 25-step block medians drift down 1 to 2 % on every arm, which is why the same window is used everywhere. The arms alternate as:

round 1  base c1 c2 c3      round 3  c2 c3 base c1
round 2  c1 c2 c3 base      round 4  c3 base c1 c2

where c1, c2 and c3 stack three host-side patches in order; this PR is c1 plus the patch c3 adds. Runs: base 842.9 / 845.8 / 836.1 / 837.6, c1 822.1 / 803.1 / 813.0 / 814.6, c2 824.2 / 817.4 / 809.7 / 809.8, c3 766.2 / 772.5 / 772.4 / 764.8. A second block interleaved four more pairs of c3 against the tree of this PR: c3 787.9 / 782.0 / 769.5 / 767.2, this PR 769.0 / 763.1 / 778.5 / 771.8. Pooling all eight c3 runs against the four baseline runs gives 1.088x instead of 1.093x. The second decimal of the ratio is not worth defending, hence 1.09x.

Scope. One GPU, one model, one shape. The fla patch only helps where fla's autotuned kernels run. The model.train() patch is model-independent but scales with the module count, so a small model gets far less than 27 ms from it.

…s set

transformers' training_step re-asserts model.train() on every micro-step; on a
PEFT-wrapped 9B model that is a recursive walk over ~2k modules while the GPU
idles. Assert it once, redo only after a root .eval().

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ATw7g6cxq9N2LtnMratsru
@danielhanchen

Copy link
Copy Markdown
Member

The model.train() skip and the fla cached-config launch are the parts carrying the measured gain, but the bitsandbytes change reassigns bnb_optimizer.sync_gpu globally around each step, which is not safe if another optimizer steps concurrently. Could you drop that commit and keep this to the two patches you measured?

With compile_fla_no_autotune in effect every fla autotuner reuses one config for
every key, yet each launch still built fla's AutotuneKey and Triton's own key.
Once a config is known, call fn.run with it straight away.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ATw7g6cxq9N2LtnMratsru
@TarzanZhao
TarzanZhao force-pushed the perf/trainer-bnb-fla-host-overhead branch from 190fb37 to 7b45cc8 Compare September 18, 2026 17:17
@TarzanZhao

TarzanZhao commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

I just dropped it.

training_step is handed self.model_wrapped. Under DDP, FSDP or DataParallel that is a
wrapper, and Trainer.evaluation_loop calls .eval() on self._wrap_model(self.model,
training=False), which returns the module INSIDE the wrapper. The wrapper's own .training
stays True, so checking the root flag alone let the skip hold forever: after one evaluation
the whole model trained in eval mode for the rest of the run, with every dropout disabled.
Measured on a real DistributedDataParallel object: 50.4 percent of activations dropped
before, 0.0 percent after, and it never recovered.

_unsloth_wrappees_are_in_train_mode walks the wrapper attributes only (module, _orig_mod,
_fsdp_wrapped_module), at most four hops, so an unwrapped model answers on the first miss
and still skips the walk.

Also move patch_fla_autotuner_fast_path to the top of patch_gradient_accumulation_fix. It is
unrelated to gradient accumulation and can only install once fla has been imported; sitting
after the early return meant that loading a non-fla model first and a gated-deltanet model
second left it permanently uninstalled.

Adds tests for both halves of the change: the train mode walk (once per step, re-armed by a
root eval, repaired through a wrapper, unchanged for a submodule-only eval) and the fla fast
path (latched config identical to the original launch bit for bit, fallback without
_ReuseBestCache, fallback on a per-Config pre_hook, standing down under FLA_CACHE_MODE=always,
no-op when fla is absent), plus a version_compat drift guard for the model.train() rewrite
target.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 20, 2026
…ction

The cross-platform runners do not all ship torch, and a module-level import turns that into a
collection error rather than a skip. pytest.importorskip for torch, triton, fla and the unsloth
module under test.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and benchmarked this on one B200. Verdict up front: the speedup is real and I reproduced it, but the PR as submitted had one defect that silently disables dropout for the rest of a DDP run. I fixed it on your branch along with a second, smaller one, and added tests for both halves.

issue: REAL | PR as submitted: DEFECTIVE, 2 fixed by me | merge: YES

The defect

training_step is handed self.model_wrapped. Trainer.evaluation_loop calls .eval() on self._wrap_model(self.model, training=False), which under DDP is the module inside the wrapper. The wrapper's own .training stays True, so _unsloth_train_if_needed kept skipping forever and the model trained in eval mode for the rest of the run. Against a real DistributedDataParallel object over a real process group:

after an evaluation, 50 more micro-steps activations dropped
1d5210d7a dropout back in train mode 50.4%
this PR as submitted still eval, never recovers 0.0%
after the fix dropout back in train mode 50.4%

948e45cf5 adds _unsloth_wrappees_are_in_train_mode, which walks only the wrapper attributes (module, _orig_mod, _fsdp_wrapped_module), at most four hops. Measured cost on a 1,750-module tree: 1.613 us per call, 0.0065 ms per optimizer step at grad-accum 4, against the 2,814.7 us the full walk costs. The counting harness on the fixed tree is unchanged at 1 walk and 11 skips per 12 micro-steps, so nothing of the optimisation is lost.

The second fix, in the same commit: patch_fla_autotuner_fast_path() sat after the early return in patch_gradient_accumulation_fix. Load a non-fla model first and a gated-deltanet model second in one process, and the second call returns before reaching it, so the fla fast path never installs. Moved above the early return.

The speedup, reproduced

Your exact job and flags, 8 interleaved pairs, pair 1 discarded because I was running other work on the box during it:

base 1d5210d7a this PR
step, median of 51-120, 7 pairs 1624.2 to 1709.4 ms 1540.1 to 1608.1 ms head faster in 7/7 pairs
geometric mean ratio 1.0494x, 95% CI [1.0400, 1.0592]
paired delta -78.1 ms, 95% CI [-94.0, -63.2]

Your absolute saving reproduces closely: -78.1 ms here against your -71.6 ms. The ratio does not, and that is not a disagreement. Your step is 841 ms on torch 2.11 / transformers 5.5.0 / triton 3.6.0; here it is 1,640 ms on torch 2.13+cu130 / transformers 5.17.0 / triton 3.7.1. Same patch, same milliseconds saved, twice the denominator. Worth softening "1.09x" in the title to a range, or naming the stack it was measured on.

On a dense model with no fla kernels at all (Llama-3.2-3B), 3 pairs: 690.7 / 674.2 / 684.7 ms to 660.0 / 677.7 / 670.6 ms, mean -13.8 ms. Small, but the train-walk half still pays and never costs.

Correctness, with the control that matters

20 full 120-step runs, 10 per arm, all 120 logged losses compared pairwise:

max abs delta loss
base vs base 0.0070
head vs head 0.0049
base vs head 0.0066

Base against head is smaller than base against itself, so the PR moves nothing beyond the base's own nondeterminism. Step-1 loss is 1.035 in all 20 runs.

Inference, since the fla patch is a global class patch

Qwen3.5-9B, 1024-token prompt, 128 new tokens greedy, 6 processes x 5 repeats per arm:

base this PR
first-token latency, median 69.85 ms 65.48 ms
prefill tok/s, median 14,660 15,638
decode tok/s, median 25.58 25.89
peak memory allocated 19.091 GB 19.091 GB

No regression. Within-arm decode spread on base is 24.37 to 26.26 tok/s, wider than any gap between arms.

The fla patch itself

Checked line by line against triton 3.7.1 Autotuner.run:212-258: everything it bypasses (self.nargs bookkeeping, the autotuner-level pre_hook/post_hook from reset_to_zero/restore_value, do_bench, prune_configs, the disk cache, the TRITON_PRINT_AUTOTUNING line) is reachable only from _bench/benchmark(), never from a cache hit. It preserves best_config and bails correctly on a per-Config.pre_hook. fla has zero reset_to_zero= and zero per-Config(pre_hook=) uses. Enumerated all 32 route cells (n_configs x cache type x cache length x pre_hook x latched): 13 reachable cells take the fast path, 11 fall back to the original, and on the GPU the latched launch is bit-identical to the unpatched one.

Tests added

tests/test_train_mode_asserted_once.py and tests/test_fla_autotuner_fast_path.py, 18 tests. They pin the walk running once per step, a root .eval() re-arming it, the wrapper case being repaired, and, deliberately, the submodule-only eval not being repaired, with the stock behaviour pinned next to it so your documented semantic change is visible rather than assumed. The fla side covers the latched launch matching the original bit for bit, the fallback without _ReuseBestCache, the fallback on a per-Config pre_hook, standing down under FLA_CACHE_MODE=always, and being a no-op when fla is absent.

One more guard, in tests/version_compat/test_transformers_pinned_symbols.py. The whole train-mode change rests on function.replace("model.train()", ..., 1). If a transformers release ever writes self.model.train() earlier in training_step, that replace produces self._unsloth_train_if_needed(model) and every step dies. I scanned 4.47.1, 4.51.3, 4.55.2, 5.5.0, 5.10.0 and 5.17.0: exactly one model.train() in each, never preceded by self.model.. The guard makes a future change fail a test instead of breaking training silently.

Checks

Revert control: with both helpers still defined but both call sites removed, module_train_calls goes back to 33,054, exactly the base number, and fla_run_is_patched to 0. The effect is the hunks, not the symbols.

GPU-free suite on base, head and fixed: 15 failed on all three, the same 15 names. Pre-existing, named, not touched here. Import time is unchanged (medians 11.82 / 11.74 / 12.02 s over 10 runs each, ranges overlapping).

Cross-platform via staging CI: ubuntu-latest, macos-15 and windows-latest all 499 passed, 3 skipped. First attempt was red on all three with No module named 'torch' at collection, because my test files imported torch at module scope; that was my harness, not your PR, and 9f9d92fda fixes it with importorskip. To be exact about what those legs prove: the 3 skips are my two modules, skipped for want of torch on those runners, so the legs show nothing breaks at import and the drift guards hold everywhere, but they do not exercise this PR's behaviour off Linux.

What I could not prove

Real two-rank DDP, since one GPU is assigned here; the defect and its repair are shown against a real DDP object at world_size 1, replaying exactly what evaluation_loop does. Your per-commit -27.4 / -46.3 ms split: my four-arm attribution block was too noisy to resolve it, base medians alone spanned 133 ms across rounds against a 78 ms effect, so it is neither confirmed nor contradicted. lora_dropout > 0 and DoRA are read, not run. Notebooks were not run on a T4; substituted by 30+ end-to-end runs through unsloth-cli.py on two architectures.

Merge order: #10818 edits a different hunk of the same patch_gradient_accumulation_fix. Independent changes, but they will conflict textually. Land one and rebase the other.

@TarzanZhao

Copy link
Copy Markdown
Contributor Author

Thanks for reproducing it! I have updated the PR description to make clear the speedup ratio number is specific to env stack. And I add your number from your review.

unsloth_zoo defines _ReuseBestCache inside compile_fla_no_autotune, so there is no symbol to
import and nothing to isinstance against, and the class-name compare means a rename there
silently turns this fast path off with no test able to notice. dict.keys() membership always
uses dict's own lookup, so a key absent from the raw mapping yet reported present by 'in' is
exactly the reuse behaviour, under whatever name it carries. Falls back on any cache that
raises, and does not mutate the cache.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Follow-up after a pass over the patching conventions and the full declared version matrix. One more commit on your branch, 4d8b47eee, plus re-proofs of everything it could have moved.

The one place the patch probed a name instead of a behaviour

patch_fla_autotuner_fast_path was doing type(cache).__name__ == "_ReuseBestCache". That class is defined inside compile_fla_no_autotune (unsloth_zoo/compiler.py:4808), so there is no symbol to import and nothing to isinstance against, and a rename there would silently switch this fast path off with no test able to notice it. import_fixes.py convention is to probe behaviour, so it now does:

probe = ("__unsloth_probe__",) * 2
return probe not in cache.keys() and probe in cache

dict.keys() membership always uses dict's own lookup, so a key absent from the raw mapping yet reported present by in is the reuse behaviour, under whatever name it carries. Falls back on any cache that raises, and does not mutate the cache. Re-proved on a live Qwen3.5-9B run rather than in a unit test alone:

fla run calls took the fast path model.train calls
1d5210d7a 4,416 n/a, unpatched 20,750
your head 4,416 4,395 6,225
with the behaviour probe 4,416 4,395 6,225

Version matrix, read from released source at each tag

dependency tags result
transformers 34, v4.57.6 to v5.17.0 all identical: one model.train(), never self.model., num_items_in_batch in the signature so the rewrite is never skipped, training_step handed model_wrapped, evaluation_loop evals self.model
TRL 33, v0.22.2 to v1.13.0 every trainer defining training_step is a super() wrapper with zero inline model.train(), so the patch reaches sft, grpo, dpo, reward and gkd
torch v2.6.0 to v2.13.0 module (DDP and DataParallel), _orig_mod, _fsdp_wrapped_module present in every version
peft v0.18.0 to v0.20.0 no self.module = in peft_model.py or tuners_utils.py, so the wrappee walk never descends into PEFT internals and the skip survives

Two things worth pulling out of that. First, evaluation_loop evals self.model in all 34 transformers versions, so the DDP defect was reachable across the entire declared range, not just the one I happened to have installed. Second, one exception on the TRL row: online_dpo, xpo and nash_md at v0.22.2 to v0.25.1 inline their own model.train() and never call super, so they are simply unpatched, no gain and no exposure; from v0.26.0 they stop defining training_step at all.

For GRPO with fast_inference=True, unsloth_unwrap_model_for_generation (rl.py:196, :213) calls for_inference(model) then for_training(model) on the same object TRL passes in, and for_training does a full walk, so the skip is re-armed on every generation cycle.

Compiled cache

unsloth_compiled_cache/UnslothSFTTrainer.py does define training_step, but only as a three-line super().training_step(...) wrapper for the activation-offload context, so the patched Trainer.training_step runs underneath and the generated file needs no edit. Confirmed by instrumentation rather than by reading: 12 helper calls on a run whose trainer class is UnslothSFTTrainer.

While in there: that same generated file's log() does mode = "train" if self.model.training else "eval". Under the DDP defect, training metrics would have been logged under eval_ keys as well. Same root cause, also fixed by 948e45cf5.

Cost of my two additions, settled

The 120-step blocks cannot resolve this and I am not going to pretend otherwise: one block put the fixed tree 13.8 ms slower, a second put it 22.0 ms faster. They disagree in sign, which is what noise looks like. The microbenchmark settles it, on a 1,750-module tree:

per call
full model.train() walk 2,814.694 us
your skip, root flag only 0.051 us
skip with the wrappee check 1.664 us

1.613 us per call, 0.0065 ms per optimizer step at grad-accum 4. One of those three g-pairs had a head arm at 1906.8 ms against 1584 to 1653 ms everywhere else in the block; naming it rather than dropping it quietly.

Re-run after the change

GPU-free suite on the tree carrying all three commits: 15 failed, 11054 passed, 159 skipped. The failure set is identical to base name for name, the same 15 pre-existing; the +3 against the previous run is exactly the three new cache-probe tests.

Cross-platform, counts read from the job logs: ubuntu-latest, macos-15 and windows-latest each 499 passed, 3 skipped. As before, those 3 skips are my two test modules, which need a torch those runners do not ship, so the legs show nothing breaks at import and the drift guards hold everywhere, but they do not exercise this PR's behaviour off Linux.

Not done, deliberately

No Studio screenshots or Playwright recording: the symbol audit returns zero hits across studio/ for every name either of us added, and there is no visible UI effect to capture. A clean-looking before and after pair here would prove nothing.

peft 0.18.0 / 0.19.x / 0.20.0, trl 0.22.2 and transformers 4.57.6 were checked by reading the released source at each tag rather than by installing each and running the suite. The fix references no peft or trl symbol at all, only torch.nn.Module attributes, so an install matrix would have produced passes that test nothing. That is a judgement call and this is the reason for it.

No MLX, AMD or Intel GPU run, and no two-rank DDP run. The diff has no device-specific branch, and the DDP defect and its repair were shown against a real DistributedDataParallel object over a real process group, but only NVIDIA and world_size 1 were actually executed.

@danielhanchen

Copy link
Copy Markdown
Member

Closed the one thing I said I could not prove: the defect is now confirmed on a real two-rank DDP run, not a world_size-1 stand-in. Kaggle 2 x T4, torchrun --nproc_per_node=2, 9m09s.

Genuinely distributed: world_size 2, ParallelMode.DISTRIBUTED, wrapper type DistributedDataParallel, model_wrapped is not model. Also a different stack and a different architecture from my earlier B200 runs, which is the point of running it there: torch 2.10.0+cu128, transformers 5.5.0, trl 0.24.0, peft 0.19.1, sm_75, fp16.

Llama-3.2-1B, LoRA r8 dropout 0.1, 6 steps, eval_strategy="steps", eval_steps=3. Dropout modules with p > 0 in train mode, per step:

arm gs=0 gs=1 gs=2 gs=3* gs=4 gs=5
1d5210d7a 112 112 112 0 112 112
this PR as submitted 112 112 112 0 0 0
with the fix 112 112 112 0 112 112

* on_step_begin fires before training_step runs, so at gs=3 every arm shows the mode the evaluation loop just left. The repair is visible from gs=4.

wrapped.training is True at every step on all three arms, which is exactly the mechanism: the DDP wrapper's own flag never flips, so checking the root flag alone cannot see that the module inside it is in eval.

The notebook's own verdict, unedited:

DEFECT CONFIRMED on a real two-rank DDP run: after the first evaluation the PR as
submitted leaves 0 of 112 dropout modules in train mode, while base leaves all of them
FIX CONFIRMED: the fixed tree matches base exactly
VERDICT_OK

Two things I want to be straight about

The first Kaggle run printed VOID: the BASE arm does not repair train mode. That was my notebook being wrong, not the run: my verdict window included the gs=3 sample, which is taken before the repairing training_step on every arm including base. The per-step data from that first run is identical to the second. I corrected the window and re-ran rather than reinterpreting the first run by hand, so the notebook certifies itself.

And the 6-step losses are the same on all three arms to 3 decimals (base 1.6847 / 1.3987 / 1.5941 / 1.8644 / 1.7471 / 1.6238 against 1.6847 / 1.3987 / 1.5943 / 1.8648 / 1.7472 / 1.6247 on the PR head), with the arm-to-arm spread no larger than base-to-fixed. Six steps of a 1B model at dropout 0.1 is nowhere near enough for silently-disabled dropout to move the loss, and I am not going to present that table as if it were damning. The harm is that a user asks for dropout 0.1 and, from the first evaluation onward, trains without it for the rest of the run. That is a regularisation change, not something a 6-step loss detects.

41 comment lines to 12 on 140 non-blank: section banners, code restatements and the run
instruction deleted outright, the four multi-line docstrings collapsed to the one fact each
carries. Comments only, AST-verified.
Every other file under tests/ carries the SPDX line; these two were added without it.
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #11238, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#49.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror 52f619ec77 (this PR's 4d8b47eee)

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 52f619ec77

View security finding report

Only the user who started this review can view the report in Codex.

No triage reaction was recorded on the mirror

chatgpt-codex-connector[bot] (on the mirror)

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

Reviewed commit: 52f619ec77

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 52f619ec77 (this PR's 4d8b47eee).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review round closed. Since this PR is authored by someone outside the org, Codex does not answer on it directly, so the round ran on a mirror of this exact tree and the transcript is carried back in the comment above.

Converged: CODEX_APPROVED, zero inline items. Code review and security review both clean on the mirror of 4d8b47eee. Nothing to triage, so nothing was reacted to or argued with.

Two commits since, neither of which changes code:

  • 9185caffd cuts the comment volume in tests/test_train_mode_asserted_once.py from 41 comment lines to 12 on 140 non-blank (25.8 percent to 8.6). Section banners, code restatements and the run instruction deleted outright; the four multi-line docstrings collapsed to the one fact each carries. AST-verified comments-only. I limited this to my own test file rather than sweeping your hunks.
  • f04be397e adds the AGPL-3.0 SPDX header to the two new test files. The pre-push gate caught that, not me: every other file under tests/ carries it and these two were added without it.

CI green on the final head. pre-commit.ci passes. Cross-platform on the owned staging repos, counts read from the job logs rather than the tick: ubuntu-latest 499 passed / 3 skipped, macos-15 499 / 3, windows-latest 499 / 3, with gating: scoped so the jobs really run this PR's tests and a break would fail them. Same caveat I gave before: those 3 skips are my two test modules, which need a torch those runners do not ship.

One thing I checked this round rather than carried over as an assumption. My wrappee walk reads module / _orig_mod / _fsdp_wrapped_module, and PEFT forwards unknown attributes to the wrapped model through __getattr__, so it was worth confirming it does not resolve any of the three and quietly descend into model internals on every micro-step. On a real PeftModel all three come back None, the walk stops at the first miss, and a skipped micro-step still makes 0 nn.Module.train calls.

No UI evidence attached, deliberately: the PR touches unsloth/models/_utils.py and three test files, nothing under studio/ or any frontend path, and no Studio file reads any symbol either of us added. There is nothing a before and after screenshot could show.

@danielhanchen
danielhanchen merged commit a801cae into unslothai:main Sep 21, 2026
1 check passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
….77 s per step at 1 GPU, the model-independent half of unslothai#10744 (unslothai#11238)

* Trainer: skip the per-micro-step model.train() walk once train mode is set

transformers' training_step re-asserts model.train() on every micro-step; on a
PEFT-wrapped 9B model that is a recursive walk over ~2k modules while the GPU
idles. Assert it once, redo only after a root .eval().

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ATw7g6cxq9N2LtnMratsru

* fla: launch autotuned Triton kernels with the cached config directly

With compile_fla_no_autotune in effect every fla autotuner reuses one config for
every key, yet each launch still built fla's AutotuneKey and Triton's own key.
Once a config is known, call fn.run with it straight away.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ATw7g6cxq9N2LtnMratsru

* Repair train mode when the model handed to training_step is a wrapper

training_step is handed self.model_wrapped. Under DDP, FSDP or DataParallel that is a
wrapper, and Trainer.evaluation_loop calls .eval() on self._wrap_model(self.model,
training=False), which returns the module INSIDE the wrapper. The wrapper's own .training
stays True, so checking the root flag alone let the skip hold forever: after one evaluation
the whole model trained in eval mode for the rest of the run, with every dropout disabled.
Measured on a real DistributedDataParallel object: 50.4 percent of activations dropped
before, 0.0 percent after, and it never recovered.

_unsloth_wrappees_are_in_train_mode walks the wrapper attributes only (module, _orig_mod,
_fsdp_wrapped_module), at most four hops, so an unwrapped model answers on the first miss
and still skips the walk.

Also move patch_fla_autotuner_fast_path to the top of patch_gradient_accumulation_fix. It is
unrelated to gradient accumulation and can only install once fla has been imported; sitting
after the early return meant that loading a non-fla model first and a gated-deltanet model
second left it permanently uninstalled.

Adds tests for both halves of the change: the train mode walk (once per step, re-armed by a
root eval, repaired through a wrapper, unchanged for a submodule-only eval) and the fla fast
path (latched config identical to the original launch bit for bit, fallback without
_ReuseBestCache, fallback on a per-Config pre_hook, standing down under FLA_CACHE_MODE=always,
no-op when fla is absent), plus a version_compat drift guard for the model.train() rewrite
target.

* Skip the new tests where torch is absent instead of erroring at collection

The cross-platform runners do not all ship torch, and a module-level import turns that into a
collection error rather than a skip. pytest.importorskip for torch, triton, fla and the unsloth
module under test.

* Detect the reuse cache by behaviour instead of its class name

unsloth_zoo defines _ReuseBestCache inside compile_fla_no_autotune, so there is no symbol to
import and nothing to isinstance against, and the class-name compare means a rename there
silently turns this fast path off with no test able to notice. dict.keys() membership always
uses dict's own lookup, so a key absent from the raw mapping yet reported present by 'in' is
exactly the reuse behaviour, under whatever name it carries. Falls back on any cache that
raises, and does not mutate the cache.

* Cut the comment volume in the train-mode test file

41 comment lines to 12 on 140 non-blank: section banners, code restatements and the run
instruction deleted outright, the four multi-line docstrings collapsed to the one fact each
carries. Comments only, AST-verified.

* Add the AGPL-3.0 header to the two new test files

Every other file under tests/ carries the SPDX line; these two were added without it.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit to TarzanZhao/unsloth that referenced this pull request Oct 12, 2026
The model-independent half landed separately in unslothai#11238 (train-mode walk, fla
launch path), so _utils.py takes main's version: the floating_point_ops cache,
the bitsandbytes sync removal and the checkpoint RNG default are left out.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 15, 2026
…l (LoRA and QLoRA) (unslothai#10744)

## Summary

Fine-tuning ran each transformer layer as many small, separately
compiled pieces with eager glue in between, so on small and mid-sized
models the GPU spent much of every step waiting on the CPU. This PR
compiles each decoder layer as one `torch.compile` region, for every
model loaded through `FastModel` / `FastVisionModel`, with LoRA and
4-bit QLoRA inside the region. The model-independent half of the
original change (Trainer, bitsandbytes and fla launch overhead) landed
separately in unslothai#11238; the Qwen3.5-only fused layer this PR started with
is replaced by the generic version and deleted.

New files: `unsloth/models/_block_compile.py` (the per-layer region) and
`unsloth/models/_gdn_op.py` (fla's Gated DeltaNet chunk kernel as an
opaque custom op, so Qwen3.5 / Qwen3.6 layers compile as one graph).
`vision.py` installs it at the end of `post_patch_model`;
`import_fixes.py` gains one torch < 2.8 fix (below).

## What the block does

- Finds every `*DecoderLayer` class and compiles its stock forward once
(`fullgraph=False`, sequence dims marked dynamic up front, no per-length
recompiles).
- Each layer's first call compiles with errors raised; a layer that
cannot compile retries with flex_attention outside the region, then
keeps the stock forward. The mode is pinned per layer so a
gradient-checkpoint recompute never switches graph, and a failure sets
the starting mode for sibling layers of the same kind.
- Training forwards only: eval and generation keep the stock forward, so
their logits match transformers bit for bit.
- Inside a block: Unsloth's decode-aware attention is inlined;
bitsandbytes NF4 uses Unsloth's Triton dequantize; Gemma-4 sliding
layers take is_causal SDPA when the mask is a plain band; Qwen3.5's fla
chunk kernel and causal conv run as traceable ops.
- MoE experts stay inside the block unless tracing would make zoo fold
their LoRA delta into the whole expert stack (Gemma-4); those experts
run outside, one graph break each.
- Stays off on torch < 2.7, under `UNSLOTH_FORCE_FLOAT32` (fp16-only
GPUs for Qwen3.5, Gemma 3 / 3n / 4, Qwen3-MoE, GLM-4 MoE, gpt-oss), and
for gpt-oss. `UNSLOTH_BLOCK_COMPILE=0` turns it off;
`UNSLOTH_COMPILE_DISABLE` also does.
- torch < 2.8: `torch.compiler.disable(fn, recursive = False)` marks
`fn` itself there, so unsloth_zoo's decode-aware disable was disabling
the function it runs.
`import_fixes.fix_torch_compiler_disable_unless_decode` hands it a copy
instead (no-op on 2.8+).

## Speed

Step time, main (merge base) vs this PR, interleaved main, head, head,
main on one rented GPU, fresh process per arm, 20-30 steps, median of
steady steps. Peak memory equal in every pair.

| model | GPU | LoRA (16-bit) | QLoRA (4-bit) |
|---|---|---|---|
| Qwen3-0.6B | A100 | 338 -> 161 ms (2.10x) | 438 -> 190 ms (2.30x) |
| Qwen3.5-0.8B | A100 | 350 -> 213 ms (1.64x) | 458 -> 234 ms (1.96x) |
| gemma-4-E2B-it | A100 / H100 | 606 -> 425 ms (1.43x) | 677 -> 390 ms
(1.74x) |
| gemma-4-12b-it | A100 | 1131 -> 1081 ms (1.05x) | 1022 -> 921 ms
(1.11x) |
| gemma-4-26B-A4B-it | A100-80GB | 803 -> 631 ms (1.27x) | 946 -> 694 ms
(1.36x) |
| Qwen3.6-35B-A3B | RTX PRO 6000 / A100-80GB | 516 -> 465 ms (1.11x) |
1399 -> 827 ms (1.69x, profile) |

The gain is largest where the step is launch-bound (small and MoE
models) and smallest on large dense models. The first step compiles
longer (for example 32 s -> 170 s on gemma-4-E2B, A100), so very short
runs can come out slower overall.

## Correctness

- fp32 one-step parity, block on vs off, LoRA and QLoRA: loss within
1.4e-4 and LoRA grad norms within 1.5e-3 relative on Qwen3, Qwen3.5,
Llama-3.2, gemma-3, gemma-4-E2B and a Gemma-4 MoE, on torch 2.7.1, 2.8,
2.9.1, 2.10, 2.11, 2.12.1, 2.13 and 2.14.1 (T4, L4, A100, B200).
- Graph breaks: 0 for the dense models above on torch 2.8+; Gemma-4 MoE
8 per step (experts outside the block).
- AMD gfx1151 (ROCm torch 2.11): base 38/38, head 49/49 tests pass.
- Regression suite (103 cases, base vs head): 0 regressions, 0 metric
moves. sft, vision_sft (Qwen2.5-VL, Gemma-4), vision_grpo and
inference_smoke base vs head: no regression.

## Not covered

- No speedup where the block stays off: fp16-only GPUs for the
float32-forced families, Gemma-3 on L4 (flex attention exceeds shared
memory), torch 2.7 QLoRA (torch's own duplicate-tensor guard keeps it
eager).
- Models loaded through `FastLanguageModel`'s older Llama path do not
get the block yet.
- MLX does not use this path; Windows with an NVIDIA GPU was not run.

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants