Skip to content

bf16 stochastic rounding: one-pass AdamW kernel for torch AdamW, one-pass round for bitsandbytes - #18282

Merged
danielhanchen merged 6 commits into
mainfrom
bf16-sr-one-pass-adamw
Nov 18, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
bf16-sr-one-pass-adamw

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

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.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.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T13:12:27.226951Z d3a1e99 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: 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 7f2aa27943

ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: d3a1e99208

ℹ️ 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 7a90ea0 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the bf16-sr-one-pass-adamw branch November 18, 2026 13:18
danielhanchen added a commit that referenced this pull request Nov 18, 2026
…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.
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