Skip to content

Optimizer parking outside inference mode; refuse fp16 params with unquantized adamw_flash moments - #14201

Merged
danielhanchen merged 8 commits into
mainfrom
dh/fu-optim
Oct 19, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/fu-optim

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two follow-ups on opt-in optimizer features. Both default paths are unchanged.

  1. Optimizer parking under an outer torch.inference_mode() (UNSLOTH_PARK_OPTIMIZER_DURING_ROLLOUT=1, GRPO: opt-in parking of optimizer state and gradients on host during rollout #13866). When generate_and_score ran inside inference_mode, for example during an eval between train calls, the pinned host buffers and the restored moments and grads became inference tensors. The next optimizer.step() then raised Inplace update to inference tensor outside InferenceMode is not allowed. Parking and restoring now run under torch.inference_mode(False), torch.no_grad(). After restore the values are byte-equal, nothing is an inference tensor, and two park / step cycles in a row pass.
  2. adamw_flash with trainable fp16 parameters (Add optim = "adamw_flash" (FlashAdamW from flashoptim) for lower optimizer memory #13881). With quantize=False, flashoptim stores the Adam moments in the parameter dtype (flashoptim/optimizers.py, 0.1.4). An fp16 variance (grad**2 * (1 - beta2)) underflows to 0 for small gradients, so the update becomes momentum / eps. In a repro, one fp16 weight went to -46.375 where an fp64 AdamW reference gives 0.99833. Upstream avoids this only through its quantize=True default, which stores the variance as a square root with per-group scales. Keeping the variance in fp32 would need a change to flashoptim's kernel, so UnslothFlashAdamW now raises a clear error for trainable fp16 parameters in a group with quantize off. The message says to cast to float32 / bfloat16 or set optim_args = 'quantize=True'. With quantize=True the results match main (max error 2.05e-4 against the reference), and bf16 / fp32 parameters are unaffected.

Tests

  • tests/test_grpo_park_optimizer_during_rollout.py::test_park_under_outer_inference_mode_restores_ordinary_tensors (CPU): fails on main, passes here.
  • tests/utils/test_flash_adamw_optim.py::test_adamw_flash_rejects_fp16_params_with_unquantized_moments (CPU, stubbed flashoptim): fails on main, passes here.
  • Both files on GPU with the real flashoptim 0.1.4: 49 passed.

Not covered here

  • No end-to-end GRPO run with parking, and no Trainer run through an fp16 trainable parameter path; the helpers and the optimizer were tested directly.
  • torch 2.13 only.

…unquantized adamw_flash moments

- UNSLOTH_PARK_OPTIMIZER_DURING_ROLLOUT: park and restore under torch.inference_mode(False) + no_grad,
  so an outer torch.inference_mode() rollout no longer turns optimizer moments / grads into inference
  tensors that break the next optimizer.step().
- adamw_flash: flashoptim stores unquantized moments in the param dtype, so fp16 variance underflows
  and updates become momentum / eps. Raise a clear ValueError for trainable fp16 params unless
  quantize=True.
@danielhanchen danielhanchen self-assigned this Oct 19, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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-19T08:20:20.994151Z 6fe3b35 Manual request
🔒 Security Review ⚠️ Failed 2026-10-19T05:45:29.506841Z 930b911 PR opened
ℹ️ 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.

@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: 930b9117d0

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

Comment thread unsloth/optimizers/flash_adamw.py Outdated
# flashoptim stores unquantized moments in the param dtype, so an fp16 variance
# (grad**2 * (1 - beta2)) underflows to 0 for small grads and the update becomes
# momentum / eps. quantize=True keeps the variance as sqrt with per-group scales.
default_quantize = kwargs.get("quantize", True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Account for positional quantize arguments

When callers use FlashAdamW's supported positional API, quantize is carried in args, so this defaults to True even if the positional value is False. For example, passing positional values through decouple_lr and then False for quantize allows an fp16 group through this guard, after which the unquantized moments can produce the corrupt updates this change is intended to prevent; bind the forwarded arguments to the upstream signature or make this wrapper reject positional optimizer options.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3c6ea83: the check now runs per param group after flashoptim fills its defaults, so a positional quantize (or a per-group one) is what gets checked. Covered by test_adamw_flash_fp16_check_covers_positional_late_and_unfrozen_groups.

Comment thread unsloth/optimizers/flash_adamw.py Outdated
Comment on lines +140 to +144
if any(
p.dtype == torch.float16
and not (
group.get("quantize", default_quantize)
if isinstance(group, dict)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate parameter groups added after construction

This safety check only scans the groups present in __init__. FlashOptim exposes add_param_group, so progressive unfreezing can add an fp16 group whose effective quantize value is false after construction; that group bypasses this guard and receives the same unsafe unquantized fp16 moments. Apply the validation when groups are added or before they are first stepped as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3c6ea83: the check lives in add_param_group, which torch's Optimizer.init also calls, so groups added later (progressive unfreezing) are refused the same way. Covered by the same test.

Comment thread unsloth/optimizers/flash_adamw.py Outdated
# momentum / eps. quantize=True keeps the variance as sqrt with per-group scales.
default_quantize = kwargs.get("quantize", True)
if any(
p.dtype == torch.float16

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude permanently frozen fp16 parameters from the rejection

When an optimizer is built from model.parameters() rather than a prefiltered trainable list, this scan also rejects fp16 parameters with requires_grad=False. Such parameters never acquire gradients or optimizer moments, so they cannot trigger the underflow being guarded against; this unnecessarily blocks otherwise safe setups such as fp32 LoRA adapters over a frozen fp16 base model. Limit the construction-time rejection to parameters that are currently trainable, with step-time validation covering parameters that are later unfrozen.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3c6ea83: only params that are trainable when the group is added are refused. Frozen fp16 params in an unquantized group (an fp16 base under fp32 LoRA) are accepted and checked at step, so one that is unfrozen later and gets a gradient is refused before it gets moments. Covered by the same test; 50 tests pass on GPU.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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 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: 3c6ea83e10

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

Comment thread unsloth/optimizers/flash_adamw.py Outdated
Comment on lines +169 to +173
def step(self, *args, **kwargs):
watched = self.__dict__.get("_unsloth_frozen_fp16")
if watched and any(p.grad is not None for p in watched):
_refuse_unquantized_fp16()
return super().step(*args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Revalidate fp16 groups after loading optimizer state

When resuming an older checkpoint whose saved parameter group has quantize=False, load_state_dict() restores that group metadata even if the optimizer was constructed with quantize=True (PyTorch documents parameter-group metadata as part of optimizer state). This guard only examines _unsloth_frozen_fp16, which is populated during add_param_group, so an fp16 group accepted during construction is not watched after loading changes its effective setting to unquantized; subsequent steps can therefore silently perform the unsafe updates this change is intended to prevent. Revalidate or rebuild the watched groups after load_state_dict(), or inspect each group's effective setting in step().

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eb9f5c5: the update-time check now reads each group's current quantize in step_param, so a group whose quantize=False came back through load_state_dict is refused on its first fp16 update. Added to test_adamw_flash_fp16_check_covers_positional_late_and_unfrozen_groups.

Comment thread unsloth/optimizers/flash_adamw.py Outdated
Comment on lines +169 to +173
def step(self, *args, **kwargs):
watched = self.__dict__.get("_unsloth_frozen_fp16")
if watched and any(p.grad is not None for p in watched):
_refuse_unquantized_fp16()
return super().step(*args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate fp16 parameters in the per-parameter update path

When FlashOptim gradient release is enabled, backward hooks update parameters through step_param() and the later step() is a no-op, as described by FlashOptim's gradient-release API. An fp16 parameter that was frozen when this unquantized group was added can therefore be unfrozen and updated during backward before this wrapper's check ever runs, allowing exactly the unsafe unquantized update being guarded against. Override and validate in step_param() (the common update entry point), or explicitly reject gradient release for watched groups.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eb9f5c5: the check moved into step_param, which both step() and the gradient-release hooks go through, so an fp16 param unfrozen later is refused before its first update either way. Only fp16 params with a gradient pay for the group lookup. Covered by the same test (direct step_param call); 50 tests pass on GPU.

@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: eb9f5c5dc0

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

Comment thread unsloth/optimizers/flash_adamw.py Outdated
Comment on lines +177 to +178
if group is not None and not group.get("quantize", True):
_refuse_unquantized_fp16()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor the optimizer-wide quantization fallback

When an fp16 optimizer constructed with quantize=False loads a vanilla AdamW or older compatible state dict whose parameter groups omit quantize, this .get(..., True) treats the group as quantized and permits the update. FlashOptim explicitly supports vanilla optimizer states and resolves a missing group value as hparams.get("quantize", self._quantize) in _ensure_state_initialized, so the moments remain unquantized fp16 and can produce the corrupt updates this guard is intended to prevent. This missing-key fallback is fresh evidence beyond the previously fixed checkpoint case where quantize=False was explicitly present; use the optimizer-wide setting when the group key is absent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d7cee3e: a group without the quantize key now resolves to the optimizer-wide setting (flashoptim's self._quantize), the same fallback flashoptim uses in step and load_state_dict. A vanilla state dict under quantize=False is now refused at step; there is a test for it.

Comment thread unsloth/optimizers/flash_adamw.py Outdated
Comment on lines +156 to +158
super().add_param_group(param_group)
group = self.param_groups[-1]
if not group.get("quantize", True) and any(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate a new group before appending it

When a progressive-unfreezing caller catches this ValueError and tries to recover, super().add_param_group() has already appended the rejected fp16 group before validation runs. The optimizer therefore still owns the parameter: retrying with corrected settings fails as a duplicate, while continuing causes each step to raise again. Validate without committing the group, or remove the newly appended group before raising.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d7cee3e: a refused group is popped from param_groups (and the cached quantized_state_spec dropped) before raising, so a caller that catches the error can add the params again with quantize=True. The test checks that the group count stays at 1 and that re-adding with quantize=True then steps.

@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: d7cee3e169

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

Comment thread unsloth/optimizers/flash_adamw.py Outdated
p,
group = None,
):
if p.dtype == torch.float16 and p.grad is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the no-op behavior for still-frozen parameters

If a caller freezes an fp16 parameter after backward, requires_grad_(False) leaves its existing .grad attached, so this condition raises for an unquantized group even though FlashOptim's base step_param explicitly returns without updating parameters whose requires_grad is false (upstream implementation). This can unexpectedly abort progressive-freezing workflows; include p.requires_grad in the validation condition so only parameters that could actually be updated are rejected.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6fe3b35: the check now also requires p.requires_grad, matching flashoptim's own skip in step_param, so a param frozen after backward with its .grad still attached is a no-op again. Added to the test.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6fe3b35cf9

ℹ️ 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 commented Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

The Core zoo (HF=4.57.6 + TRL<1) red here is not from this PR. It runs unsloth-zoo's own tests at zoo main f9c2fb21. There, tests/test_mlx_speculative.py::test_only_the_verify_forward_is_built_as_a_verify_block fails with 'SpeculativeEngine' object has no attribute '_invariant', because zoo #1871 added that flag to __init__ and the test builds the engine with object.__new__.

It reproduces on zoo main with mlx[cpu] (1 failed, 26 passed). The test-side fix is unslothai/unsloth-zoo#1877, now merged. The zoo commit is resolved once per run by the resolve-zoo-ref job, so "re-run failed jobs" reuses f9c2fb21 and fails again. A full re-run of the workflow (all jobs) or a new push picks up the fix.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 19, 2026
… sets (#1877)

## Summary


`tests/test_mlx_speculative.py::test_only_the_verify_forward_is_built_as_a_verify_block`
fails on zoo main since #1871:

```
unsloth_zoo/mlx/speculative.py:1012: in _verify
    if self._invariant:
E   AttributeError: 'SpeculativeEngine' object has no attribute '_invariant'
```

This turns `Core zoo (HF=4.57.6 + TRL<1)` red on unsloth PRs (for
example unslothai/unsloth#14201, which tests zoo `f9c2fb21`) and
anywhere else this file runs with `mlx` installed.

## Cause

#1871 added the `_invariant` flag to `SpeculativeEngine.__init__` and
branches on it in `_verify`. The product is fine: every real engine goes
through `__init__`.

The test does not. `__init__` imports `mlx_vlm`, which the CPU job does
not install, so the test builds the engine with `object.__new__` and
sets `_exact`, `lm`, `cache`, `_kwargs` and `_hidden` by hand. Any flag
`__init__` gains later is simply missing, and `_verify` dies on it.

## Change

Test-only, `tests/test_mlx_speculative.py`:

- **`_init_attributes(cls)`:** reads every `self.<name> = ...` target in
`cls.__init__` with `ast`.
- **`_bare_engine(cls, **attrs)`:** `object.__new__`, every one of those
attributes set to `None`, then the overrides. A flag added to `__init__`
later defaults to off, so the hand-built engine stays on the plain
verify path the test is about.
- **`test_the_bare_engine_has_every_attribute_init_sets`:** pins that
the reader still finds the flags `_verify` branches on (`_exact`,
`_invariant`, `lm`, `cache`, `_verify_forward`). That way a reader that
silently finds nothing cannot make the helper vacuous.

## Testing

Linux, `mlx[cpu]` 0.32.4 (no `mlx_vlm`, as in the CPU job):

- **Before, zoo main `e782f78c`:** `1 failed, 26 passed`.
- **After:** `28 passed`.
- **Sabotage:** I added a hypothetical `self._future_flag = False` to
`__init__`, with an `if self._future_flag: raise` branch in `_verify`.
The new test still passes (2 passed), and the old hand-built form fails
on it (1 failed). This is the failure class it guards against.
@danielhanchen
danielhanchen merged commit 143e41f into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the dh/fu-optim branch October 19, 2026 18:51
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Oct 25, 2026
…n decay (unslothai#14749)

## 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 (unslothai#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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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