Repository navigation
bf16 stochastic rounding: one-pass AdamW kernel for torch AdamW, one-pass round for bitsandbytes - #18282
Conversation
…pass round for bitsandbytes torch AdamW / Adam weights now step in one Triton kernel per weight: bf16 weight, gradient and moments are read once, AdamW's float32 arithmetic runs in registers, and the weight and both bf16 moments are written back with stochastic rounding (Philox lanes 0/1/2 seeded by the same (param index, step) value as before), so resumes and DDP replicas still draw alike. bitsandbytes keeps its own 8-bit state, so its weights still step a float32 copy, now rounded back in one kernel. UNSLOTH_BF16_SR_FUSED=0 keeps the float32-copy route with torch.randint draws; amsgrad, maximize, capturable, Adam with L2 decay, float32 moments and non-CUDA weights keep it too.
|
@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: 6c910e753b
ℹ️ 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".
… device probe, exact test reference A one-pass launch that fails after the per-device probe passed (a specialisation the probe never compiled) used to end training with the step counters already advanced. The weights it did not reach now take the float32 route with their step undone, and so does every later step on that device; a failed one-pass round for bitsandbytes falls back to the torch.randint round of the same float32 step. The rare ulp in the op-by-op test came from the reference, not the kernel: CUDA computes tensor / python_float as tensor * (1 / float). With a tensor divisor the kernel is bitwise equal to the reference (0 differences over 120M outputs on B200, Triton 3.3 to 3.9 except 3.6). Triton 3.6 still emits FFMAs on sm_100 despite enable_fp_fusion=False, so there the test bounds the count and the distance instead.
…radScaler, matches torch.lerp - Step hooks: the one-pass update now runs inside torch's step hook dispatch, per weight when the optimizer has its own hooks (state offload, idle-expert gradients, DP sync) as the float32 route does, else once per group. Before, a step where every weight took the one-pass route ran no hooks, so offloaded state stayed on the GPU and dropped gradients were still applied. - GradScaler: a fused optimizer stepped by GradScaler carries grad_scale / found_inf, which only torch's kernel applies, so such steps keep the float32 route. - exp_avg: torch.lerp computes weights >= 0.5 from the far end; the kernel now does too, so beta1 <= 0.5 matches torch and beta1 = 0 keeps a tiny gradient whole.
…eeps syncing gradients The float32 route stepped each bfloat16 weight by swapping p.data to a float32 copy and back. A dtype change through .data resets the weight's AccumulateGrad node, and DDP's allreduce hooks live on that node: from the second backward on, DDP stopped syncing those gradients and the replicas trained on their own gradients and drifted apart (2-rank gloo: gradients differ at step 1 on main). The optimizer now steps a separate float32 copy under the weight's own state (moved to the copy for the call), and the result is rounded back into the weight in place. bitsandbytes gets the copy too. The one-pass kernel never swapped .data. Torch step hooks run once around the update with the real weights, the class step underneath runs unhooked.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1bc9d1edda
ℹ️ 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".
…fter the one-pass kernel
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…18343) ## Comment the BLOCK constexpr on the bf16 stochastic rounding kernels `tests/test_triton_constexpr_comments.py` fails on `main` since #18282. It shows up in `Repo tests (CPU, rest)` on unrelated PRs, for example #18312 and #18313: ``` E AssertionError: tl.constexpr parameters without a comment: E unsloth/optimizers/bf16_stochastic_rounding.py:60 _round_kernel.BLOCK E unsloth/optimizers/bf16_stochastic_rounding.py:83 _adamw_kernel.BLOCK ``` ### Cause That lint requires every `tl.constexpr` parameter of an Unsloth Triton kernel to sit on its own line with a comment saying what it is. It does this because each distinct constexpr value compiles a new kernel. #18282 added `_round_kernel` and `_adamw_kernel`, whose `BLOCK` constexpr has no comment. `_round_kernel` also takes it inline on the `def` line. ### Fix Both kernels now take `BLOCK` on its own line with a comment: `# elements per program, fixed at _BLOCK`. `_round_kernel`'s signature is split one parameter per line to match. No behaviour changes. The parameters and their order are unchanged, and every launch still passes `BLOCK = _BLOCK` (1024). ### Verification - `tests/test_triton_constexpr_comments.py`: fails on `main` on these two lines and passes with this change. - `tests/test_bf16_stochastic_rounding.py`: 13 passed, 2 skipped on CPU across the two files. - ruff is clean.
Summary
#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.randinttensor per chunk. With the Trainer defaultadamw_torch_fusedit 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 withadamw_torch, and +24% withadamw_8bit.This PR makes the default path cheaper. Numerics stay the same in distribution:
pandgin the same dtype, so weights still step a float32 copy. The six-pass round is replaced by one Triton kernel.Contract kept
low16 / 2**16. This is the same law as(bits + U[0, 2**16)) & -65536today. Inf and NaN are kept.(seed, param index, step)value_reseeduses today. Lane 0 rounds the weight, lanes 1 and 2 roundexp_avgandexp_avg_sq. A resumed run draws what an uninterrupted one would. DDP replicas use the same seed, index and step, so they round identically.step(CPU, or device forfused=True), plus bf16exp_avgandexp_avg_sq. Checkpoints move freely between main and this PR.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=0still turns SR off.UNSLOTH_BF16_SR_FUSED=0keeps the previous float32-copy route withtorch.randintdraws.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.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_allocatedper phase, GiB, batch 4: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):
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):tensor / python_floatas 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 despiteenable_fp_fusion=False, so there, and on ROCm, the test bounds the count and the distance (one bfloat16 step) instead. This covers foreach andfused=True, with and without weight decay. The step counter keeps torch's placement.UNSLOTH_BF16_SR_FUSED=0andUNSLOTH_BF16_STOCHASTIC_ROUNDING=0switches are covered..datato 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.Also checked:
tests/test_bf16_stochastic_rounding.py) andtests/test_bf16_adamw.pypass unchanged.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.fused=True.Not covered
adamw_torch,adamw_torch_fusedandadamw_8bit, with the same loss drop as main (0.00806 vs 0.00805; SR off 0.00588).pandgin one dtype, so it needs the float32 copy.