Skip to content

adamw_flash: keep the unquantized bf16 Adam variance in fp32 so it can decay - #14749

Merged
danielhanchen merged 6 commits into
mainfrom
flash-adamw-bf16-variance
Oct 25, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
flash-adamw-bf16-variance

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

optim = "adamw_flash" defaults to quantize = False, so flashoptim stores both Adam moments in the parameter dtype. Its fused kernel updates the variance in fp32 and writes it back with round-to-nearest (tl.store(var_ptr, var_f32.to(PARAM_DTYPE)), flashoptim 0.1.4 optimizers.py:2529).

At beta2 = 0.999 one step moves the variance by 0.1% of the gap to g**2. That is under half a bf16 ulp (0.2% to 0.4%) unless g**2 is several times the stored value, so the rounding throws the step away. Two things follow:

  • After large gradients: the variance can never decrease, so the effective step size lr / sqrt(v) keeps shrinking. Under noisy gradients it ratchets up on every large sample and never comes back.
  • Under a steady gradient: it stops rising at about a third of g**2, so steps are about 1.8x too large.

Through the real fused flashoptim step (4096 elements, stored variance over an fp32 EMA of the same gradients):

gradient pattern step 1000 step 3000 step 6000
one large gradient, then small ones 2.32 6.90 9.76
noise, scale drops 10x at step 1000 1.06 7.10 47.1
steady constant gradient 0.48 0.32 0.31
steady noise 1.06 1.34 1.64

With this PR every cell is 1.00.

This affects bf16 full finetuning with the default optim_args. LoRA adapters (fp32 params), quantize=True and the other optimizers are not affected.

Evidence (Qwen2.5-0.5B, bf16 full finetune, wikitext-103, batch 8 x 512, lr 2e-5 cosine with 50 warmup steps, grad clip 1.0, B200)

The stored variance was read from the optimizer state every 100 steps and compared with an fp32 EMA of the same clipped gradients, for 5 tensors.

With the current default:

  • The stored variance did not go down for a single element at any checkpoint.
  • The fp32 EMA of the same gradients went down for 0.1% to 73% of elements per 100 steps.
  • The stored to true variance ratio grew steadily:
step 1000 2000 3000 4000 5000 6000
q_proj.12 1.07 1.19 1.32 1.46 1.59 1.70
q_proj.0 1.07 1.23 1.43 1.62 1.90 2.12

With this PR: the ratio is 1.0 throughout, and the share of elements that decrease matches the fp32 EMA.

Eval loss, 6000 steps:

step fp32 master AdamW adamw_flash (this PR) same, repeat adamw_flash (main)
2000 2.64133 2.64215 2.64125 2.63303
4000 2.53689 2.53662 2.53697 2.53566
6000 2.51328 2.51352 2.51333 2.51709
  • Main: it drifts away from AdamW beyond run-to-run noise. Mid-run its eval loss is lower, because the inflated variance acts like a smaller learning rate. By the end of the schedule it is 0.0038 worse.
  • This PR: it stays within run-to-run noise of the reference. Two runs of this PR differ by up to 0.0013 at a checkpoint and 0.0002 at the end, and this PR is at most 0.0017 from the reference. Main is up to 0.0083 from it.

2000-step runs (mean train loss over the last 500 steps, relative to fp32 AdamW):

run delta
A/A repeat of fp32 AdamW -0.00006
this PR +0.00013
main +0.00088
quantize=True +0.0217 (eval 2.5772 vs 2.5496, so switching the default to it is not a fix)

Fix

For bf16 params with unquantized moments, UnslothFlashAdamW widens exp_avg_sq to fp32 when the state is created or loaded.

  • Fused step: the flashoptim kernel still reads that fp32 variance exactly and updates the param and momentum as before. A one-pass Triton kernel computes the same fp32 v * beta2 + g**2 * (1 - beta2) beside it, and that result replaces the variance after the step.
  • Unfused step: flashoptim's own set_data keeps the fp32 storage.
  • load_state_dict: torch casts floating state to the param dtype on load, so the saved fp32 variance is copied back after loading instead of being rounded to bf16. Checkpoints written before this PR (bf16 variance) still load.
  • Fallback: if a future flashoptim does not have the private storage fields this relies on, the variance is left as flashoptim stores it, which is today's behaviour.
  • fp16 refusal message (Optimizer parking outside inference mode; refuse fp16 params with unquantized adamw_flash moments #14201): it now says bf16 is the safe cast because its variance is kept in fp32. Before, it suggested bf16 even though bf16 unquantized moments had the stall above. fp16 with quantize=False is still refused: the variance would underflow.

Cost

optimizer state peak memory, Qwen2.5-0.5B run optimizer step, interleaved on one B200
main 6 bytes/param (2.76 GiB) 16.0 GiB 13.1 ms median
this PR 8 bytes/param (3.68 GiB) 16.9 GiB 21.2 ms median
fp32 master AdamW 8 bytes/param (3.68 GiB) 19.6 GiB
  • Per-param memory: about 12 bytes per parameter with bf16 grads instead of 10. That is still under the 16 for bf16 weights plus fp32 master plus fp32 moments.
  • Step time: about +8 ms per step for the 290 tensors of this model. Most of that is per-tensor launch overhead, so it does not grow with model size. The bandwidth part is one extra pass of 10 bytes per element.

Tests

tests/utils/test_flash_adamw_optim.py:

  • test_adamw_flash_bf16_variance_follows_fp32[_scaled_noise|_steady] (CPU, unfused): the variance must match an fp32 EMA after a 10x gradient drop and under a steady gradient. On main it stays frozen at its peak in the first and stalls at 0.31x in the second.
  • test_adamw_flash_bf16_variance_survives_a_state_dict_round_trip (CPU): the fp32 variance is unchanged after state_dict / load_state_dict.
  • test_adamw_flash_fused_bf16_variance_follows_fp32[_scaled_noise|_steady] (gpu): the same checks through flashoptim's fused kernel.
  • test_adamw_flash_rejects_fp16_params_with_unquantized_moments now checks the new message.

All of these fail on main and pass here. The rest of the file passes unchanged.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T05:42:14.904001Z 1e0e938 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

Copy link
Copy Markdown

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

Reviewed commit: 3b0fa386dd

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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 1e0e938056

ℹ️ 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 04f21d3 into main Oct 25, 2026
3 of 30 checks passed
@danielhanchen
danielhanchen deleted the flash-adamw-bf16-variance branch October 25, 2026 07:08
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.

1 participant