Repository navigation
bfloat16 full fine-tuning: stochastic rounding of the optimizer's weight writes by default - #18192
Conversation
…tes by default A bfloat16 full finetune keeps bfloat16 weights, and the optimizer writes them back with round-to-nearest. bfloat16 spacing near 0.02 is ~1e-4, so AdamW updates at lr 1e-5 mostly vanish: on Qwen3-0.6B over 150 steps the weights kept 7-8% of the update float32 masters made (adamw_torch and adamw_8bit), so training ran at a fraction of the requested learning rate. For models loaded with full_finetuning = True, the Trainer's AdamW / Adam (torch) and bitsandbytes optimizers (adamw_8bit, paged_adamw_8bit, ...) now step each bfloat16 weight in float32, one weight at a time, and write it back with stochastic rounding (unbiased). Persistent memory is unchanged: bitsandbytes state does not depend on the weight dtype, and torch AdamW's moments stay stored in bfloat16, also stochastically rounded. float32 weights, LoRA, DTensor (FSDP2) parameters and other optimizers are untouched. It is enabled in Trainer.create_scheduler, idempotently, and UNSLOTH_BF16_STOCHASTIC_ROUNDING=0 restores round-to-nearest.
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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: 07b12c6ef8
ℹ️ 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".
| flat_src = src.reshape(-1) | ||
| flat_dst = dst.view(-1) |
There was a problem hiding this comment.
Handle noncontiguous weights before flattening the destination
For a valid noncontiguous BF16 parameter, such as torch.nn.Parameter(torch.randn(4, 4, dtype=torch.bfloat16).T), _tracked accepts the parameter, but the first optimizer step fails here because view(-1) cannot flatten its strides. Plain torch AdamW supports this layout, so enabling the new wrapper turns a working custom training loop into a runtime error. Handle the writeback through a contiguous buffer and copy it back, or exclude unsupported layouts before installing the wrapper.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Non-contiguous bf16 weights are no longer tracked: they step through the unwrapped optimizer exactly as before, so a layout like a transposed parameter keeps working. Covered by test_noncontiguous_weights_are_left_to_the_optimizer.
| def _moments(state, p, dtype): | ||
| return [ | ||
| key | ||
| for key, value in state.items() | ||
| if torch.is_tensor(value) and value.dtype == dtype and value.shape == p.shape | ||
| ] |
There was a problem hiding this comment.
Exclude Adam's step counter from moment conversion
For a scalar BF16 parameter, Adam's scalar FP32 state['step'] has the same shape as the parameter and therefore matches this predicate. _store_state consequently converts the step counter to BF16 with stochastic rounding, rather than preserving its original FP32 representation. Once the counter exceeds 256, it can skip or repeat step values, changing subsequent bias correction and checkpoint contents. Restrict conversion to the actual moment keys (exp_avg, exp_avg_sq, and max_exp_avg_sq) instead of identifying moments by shape and dtype alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Only exp_avg, exp_avg_sq and max_exp_avg_sq are converted now, by name, so a scalar parameter keeps its fp32 step. test_scalar_weight_keeps_a_float32_step_counter runs 300 steps on a scalar weight and checks the counter stays an exact fp32 300.
| def _generator(optimizer, device, seed): | ||
| generators = optimizer.__dict__.setdefault("_unsloth_sr_generators", {}) | ||
| key = str(device) | ||
| if key not in generators: | ||
| g = torch.Generator(device = device) |
There was a problem hiding this comment.
Persist the stochastic-rounding RNG state in checkpoints
When training resumes in a fresh process, the rounding generators are recreated from the initial seed because they live only in the optimizer's private attributes, outside its state_dict. Restoring the Trainer's global RNG state does not restore these explicit generators either. Consequently, resuming an otherwise identical checkpoint replays the initial rounding sequence instead of continuing it, producing different weights and moments from an uninterrupted run. Save and restore these generator states, or derive rounding randomness from checkpointed optimizer state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Each weight write now reseeds the rounding generator from the parameter index and that parameter's optimizer step, which is part of the checkpointed optimizer state, so a resumed run draws exactly what an uninterrupted run would. test_resume_draws_what_an_uninterrupted_run_draws checks 4 straight steps against 2 + save + reload + 2 bitwise.
… only the Adam moments, seed each draw from the checkpointed step [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…_cuda (skip-guard lint red since #18192) (#18204) `tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe` fails on main since #18192 (CPU `studio` shard, seen on the staging run of #18188): ``` E AssertionError: these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide, ... E assert not ['test_bf16_stochastic_rounding.py:150: torch.cuda.is_available()'] ``` ## Cause #18192 added `tests/test_bf16_stochastic_rounding.py`, whose bitsandbytes case is gated on `@pytest.mark.skipif(not torch.cuda.is_available(), ...)`. The CUDA spoof the version-compat suites install patches `torch.cuda.is_available` to True for the whole process, so on a CPU runner that shares a session with them the case would un-skip and fail. The lint is right; the new guard used the spoofable probe. ## Fix Gate on `has_real_cuda()` from `tests/_shared/real_accelerator.py`, which reads the device before any spoof, as the other GPU-only tests do. The test itself is unchanged. ## Verification - main: the lint fails with the line above. - this branch: `tests/python/test_accelerator_skip_guards.py` and `tests/test_bf16_stochastic_rounding.py`: 33 passed, 2 skipped (the CUDA case on this CPU host).
…pass round for bitsandbytes (unslothai#18282) ## Summary unslothai#18192 made stochastic rounding (SR) the default for bf16 full fine-tuning. The current path upcasts each weight, gradient and (for torch AdamW) both moments to float32, steps the optimizer once per weight, then rounds back with about six elementwise passes and a `torch.randint` tensor per chunk. With the Trainer default `adamw_torch_fused` it also reads the device step counter with `.item()` once per weight. On a Colab L4 (Qwen3-0.6B full fine-tune, batch 4 x GA 2, seq 512) that costs +62% step time and +1.2 GiB with `adamw_torch`, and +24% with `adamw_8bit`. This PR makes the default path cheaper. Numerics stay the same in distribution: - **torch AdamW / Adam (foreach, fused, or plain):** one Triton kernel per weight. It reads the bf16 weight, gradient and moments once and does AdamW's float32 arithmetic in registers, op for op as torch's foreach path does it. It then writes the weight and both bf16 moments back with stochastic rounding. No float32 copies, and one host read per device for the step counters instead of one per weight. - **bitsandbytes 8-bit:** bitsandbytes keeps its own 8-bit state, and its kernel needs `p` and `g` in the same dtype, so weights still step a float32 copy. The six-pass round is replaced by one Triton kernel. ## Contract kept - Unbiased: a value is rounded up with probability `low16 / 2**16`. This is the same law as `(bits + U[0, 2**16)) & -65536` today. Inf and NaN are kept. - Seeding: the Philox seed is the same `(seed, param index, step)` value `_reseed` uses today. Lane 0 rounds the weight, lanes 1 and 2 round `exp_avg` and `exp_avg_sq`. A resumed run draws what an uninterrupted one would. DDP replicas use the same seed, index and step, so they round identically. - Optimizer state format is unchanged: `step` (CPU, or device for `fused=True`), plus bf16 `exp_avg` and `exp_avg_sq`. Checkpoints move freely between main and this PR. - The bits are not identical to main, because the random source is Philox instead of `torch.randint`. With the same draws the result is bitwise identical to torch AdamW's float32 arithmetic followed by rounding (see tests). - `UNSLOTH_BF16_STOCHASTIC_ROUNDING=0` still turns SR off. `UNSLOTH_BF16_SR_FUSED=0` keeps the previous float32-copy route with `torch.randint` draws. - The previous route is also kept for amsgrad, maximize, capturable, Adam with L2 decay, float32 moments loaded from a checkpoint (converted once, then fused), CPU / XPU weights, and when Triton is missing or its one-time per-device probe fails. ## Colab L4 A/B Setup: Qwen3-0.6B full fine-tune, alpaca, seq 512, lr 1e-5, 40 steps (30 at batch 16). Median step time over steps 4 onward. Arms were interleaved off, main, head, main, head, off on one VM. "main" is `dc95f368ca`; "head" is main plus this PR. Versions: torch 2.14.1, transformers 5.17.0, TRL 1.15.0, bitsandbytes 0.50.2, Triton 3.8.0. | optim, batch | SR off | main SR | this PR | PR vs main | PR vs off | |---|---|---|---|---|---| | adamw_torch, 4 x GA 2 | 0.347 / 0.353 s | 0.563 / 0.570 s | 0.292 / 0.294 s | -48% | -16% | | adamw_torch_fused, 4 x GA 2 | 0.298 s | 0.574 / 0.572 s | 0.292 / 0.292 s | -49% | -2% | | adamw_8bit, 4 x GA 2 | 0.308 / 0.306 s | 0.384 / 0.377 s | 0.343 / 0.343 s | -10% | +12% | | adamw_torch, 16 x GA 1 | 0.464 s | 0.687 s | 0.419 s | -39% | -10% | | adamw_8bit, 16 x GA 1 | 0.443 s | 0.514 s | 0.477 s | -7% | +8% | The A/A spread (two runs of the same arm) is at most 1.7%. Batch 16 ran each arm once. Optimizer step alone (median): adamw_torch 0.306 s on main vs 0.037 s with this PR (SR off: 0.091 s). adamw_8bit: 0.122 s vs 0.084 s (SR off: 0.051 s). Memory, `max_memory_allocated` per phase, GiB, batch 4: | optim | phase | SR off | main SR | this PR | |---|---|---|---|---| | adamw_torch | forward + backward | 5.11 | 5.11 | 5.11 | | adamw_torch | optimizer step | 5.57 | 6.78 | 4.46 | | adamw_torch_fused | optimizer step | 4.46 | 6.20 | 4.46 | | adamw_8bit | optimizer step | 4.23 | 5.39 | 5.39 | With torch AdamW the step peak drops from 6.78 to 5.11 GiB, so forward + backward is now the peak. bitsandbytes still needs the float32 copy of one weight at a time, so its memory is unchanged. Update kept versus a float32-master run (same data, layers 0 / 14 / 27): | optim | SR off | main SR | this PR | |---|---|---|---| | adamw_torch | 0.093 | 0.930 / 0.931 | 0.930 / 0.932 | | adamw_torch_fused | 0.094 | 0.930 / 0.931 | 0.932 / 0.928 | | adamw_8bit | 0.098 | 0.954 / 0.954 | 0.954 / 0.955 | Mean loss over the last 10 steps for adamw_torch: main 1.4747 / 1.4740, this PR 1.4753 / 1.4752, SR off 1.5493. ## Tests `tests/test_bf16_stochastic_rounding_fused_gpu.py` (CUDA): - The round kernel: exact values pass through, specials are kept, and the mean is unbiased for both signs. - The one-pass step is checked against AdamW's float32 arithmetic op by op with the same Philox draws. It is bitwise on CUDA (0 differences over 120M outputs on B200 with Triton 3.3 to 3.9). The reference divides by a tensor: CUDA computes `tensor / python_float` as a multiply by the reciprocal, which was the rare ulp seen earlier. Triton 3.6 (torch 2.10 / 2.11) still emits FMAs on sm_100 despite `enable_fp_fusion=False`, so there, and on ROCm, the test bounds the count and the distance (one bfloat16 step) instead. This covers foreach and `fused=True`, with and without weight decay. The step counter keeps torch's placement. - Kept update matches main's route; the `UNSLOTH_BF16_SR_FUSED=0` and `UNSLOTH_BF16_STOCHASTIC_ROUNDING=0` switches are covered. - The one-pass update runs inside torch's step hook dispatch, so optimizer state offload, idle-expert gradient dropping and other step hooks still run (per weight when the optimizer has its own hooks, as the float32 route does). A GradScaler step on a fused optimizer (grad_scale / found_inf set) keeps the float32 route, and exp_avg follows torch.lerp's far-end form for beta1 <= 0.5. - Under DDP the float32 route no longer swaps a weight's `.data` to float32 and back. That swap reset the weight's AccumulateGrad node, which carries DDP's allreduce hook, so on main the ranks stopped syncing gradients from the second step and drifted apart. The optimizer now steps a separate float32 copy, rounded back into the weight in place. `tests/test_bf16_stochastic_rounding_ddp_gloo.py` (2 gloo ranks, 4 steps; CPU, one-pass, float32 route, bitsandbytes) fails on main and keeps the replicas bitwise identical here. - A launch that fails after the per-device probe passed hands the weights it did not reach to the previous route, with their step undone, and so does every later step on that device. The same holds for the bitsandbytes one-pass round. - Resume from a state dict is bitwise identical to an uninterrupted run. Two replicas with the same seed are bitwise identical, and a different seed differs. - Float32 moments take the old route once, then the fused one. - amsgrad, maximize and Adam with L2 decay stay on the old route. - bitsandbytes uses the one-pass round, is deterministic, and its kill switch works. Also checked: - The existing CPU tests (`tests/test_bf16_stochastic_rounding.py`) and `tests/test_bf16_adamw.py` pass unchanged. - Through the real SFTTrainer path (tiny Qwen3, `adamw_torch`, `adamw_torch_fused`, `adamw_8bit`), the one-pass route engages on every weight and step. With either kill switch it engages 0 times. - A 2-rank DDP run (gloo) keeps the bf16 weights bitwise identical across ranks, both for foreach and for `fused=True`. ## Not covered - Real 2-GPU NCCL DDP was not run; DDP was checked with 2 ranks on one GPU over gloo. - AMD gfx1151 ran, Linux (ROCm 7.13, Triton 3.6) and Windows 11 (ROCm 7.14, triton-windows 3.9), base vs head on one host. The PR's tests passed (53 vs 39 at the base, none newly failing). A tiny Qwen3 bf16 full fine-tune engaged the one-pass path on every weight and step with `adamw_torch`, `adamw_torch_fused` and `adamw_8bit`, with the same loss drop as main (0.00806 vs 0.00805; SR off 0.00588). - Batch 16 ran each arm once (no A/A). - bitsandbytes still pays about +12% over SR off at batch 4. Its kernel requires `p` and `g` in one dtype, so it needs the float32 copy.
bfloat16 full fine-tuning: stochastic rounding of the optimizer's weight writes by default
With
full_finetuning = Trueon a bf16 GPU, Unsloth trains bf16 weights directly. bf16 keeps 8 mantissa bits, so a weight of magnitude ~0.02 moves in steps of ~1e-4, while an AdamW update at lr 1e-5 is ~1e-5 per element. Round to nearest writes most of those updates back unchanged: after one step at lr 1e-5 withadamw_8bit, 98.2% of a Qwen3-0.6B's weights had not moved (B200).For the Trainer's torch AdamW / Adam and the bitsandbytes optimizers (
adamw_8bit,paged_adamw_8bit, ...), each bf16 weight is now upcast to fp32 for its own update and written back with stochastic rounding, which is unbiased (E[round(x)] = x), so small updates survive in expectation. Persistent memory is unchanged: bitsandbytes state does not depend on the weight dtype, and torch AdamW's moments stay stored in bf16, also written back stochastically. The fp32 copy is one weight at a time.full_finetuning = Truewhose trainable weights are bf16. fp32 weights, LoRA / QLoRA, FSDP2 DTensor parameters (they useAdamWBF16) and other optimizers are untouched.Trainer.create_schedulernext to the gradient-accumulation patch (covers UnslothTrainer's embedding-lr path), one log line, idempotent.UNSLOTH_BF16_STOCHASTIC_ROUNDING=0restores round to nearest.enable_bf16_stochastic_rounding(optimizer)is exported for custom loops.Results
Colab L4, Qwen3-0.6B full fine-tune, alpaca-cleaned, 150 steps, batch 4 x GA 2, seq 512. "Kept" is the fraction of the fp32-master weight change the run actually made; loss is the mean of the last 30 steps.
adamw_8bit: +0.5 GiB peak (one fp32 weight plus its gradient at a time) and +23% step time at this small batch (about 4k tokens per step). Withadamw_torch: +1.2 GiB and +64% step time. A fused kernel would remove most of the step cost.Tests
tests/test_bf16_stochastic_rounding.py(CPU): unbiasedness, Inf / NaN kept, chunking, idempotence, the kill switch, DTensor and LoRA left alone, resume from a state saved without it. Main: 6 errors (module missing); here: all pass.tests/test_bf16_stochastic_rounding_default_gpu.py(B200): both default-path optimizers engage on a full fine-tune, LoRA is untouched, the kill switch restores round to nearest, bnb AdamW8bit / PagedAdamW8bit fidelity. Main: 10 of 11 fail (the LoRA no-change check passes); here: 11 pass.optimizer.stepto stay a bound method; a test covers it.Not covered