Skip to content

Add optim = "adamw_flash" (FlashAdamW from flashoptim) for lower optimizer memory - #13881

Merged
danielhanchen merged 12 commits into
mainfrom
dh/opt-flash-adamw
Oct 16, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
dh/opt-flash-adamw

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Setting optim = "adamw_flash" in SFTConfig, GRPOConfig, any other Unsloth generated config, or UnslothTrainingArguments now selects FlashAdamW from databricks/flashoptim (Apache-2.0). flashoptim is an optional dependency, and Unsloth prints an install hint if it is missing.

By default, bf16 weights keep a 16 bit error correction term in the optimizer state. The effective master weight is therefore fp32 without a separate fp32 copy, and the Adam moments stay in the parameter dtype. That is about 10 bytes per parameter including bf16 gradients, against 16 or more for bf16 weights with an fp32 master and fp32 moments.

On a Qwen2.5-0.5B full fine-tune (150 steps, lr 2e-5) the default matched fp32 master AdamW: the mean loss over the last 10 steps was identical (1.5146) and the largest per-step difference was 0.005. torch peak memory dropped from 10.2 GB to 5.5 GB.

optim_args = "quantize=True" stores the moments in 8 bits for about 8 bytes per parameter, or about 7 with master_weight_bits=24, which is flashoptim's own default. In the same run that setting ended 0.018 higher in loss, outside the 0.0024 spread between two AdamW seeds, so it is opt-in. LoRA adapters are fp32 and get no correction term; for them only quantize=True saves memory.

transformers does not know this optimizer name. The config therefore stores adamw_torch plus a marker in optim_args that survives dataclasses.replace and that transformers' own parser accepts. Trainer.get_optimizer_cls_and_kwargs is wrapped only once someone selects the optimizer, and every other optim value runs exactly as before.

These all work with it:

  • the weight decay split, LoRA+ groups and embedding learning rate groups
  • betas, eps, schedulers, gradient clipping and gradient accumulation
  • checkpoint resume: resuming from step 100 matched the continuous run to 3e-4 per step on a tiny model

optim_args accepts master_weight_bits, quantize, compress_state_dict, check_numerics and decouple_lr.

Not covered: real-model convergence beyond 150 steps, FSDP2 / DDP, fp16 training, transformers 4.57.6 / TRL 0.22.2, and GRPO / DPO end to end (the generated configs were only checked by their code). Exported weights are bf16: the extra precision lives in the optimizer checkpoint.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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 ⚠️ Failed 2026-10-16T04:55:04.910591Z bfd603b New commits
🔒 Security Review ⚠️ Failed 2026-10-15T16:13:49.279683Z 86c1be3 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…arker, reject FSDP1 and non NVIDIA Linux, refuse mixed dtype uncompressed quantized resume

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…s, reject FSDP2 CPU offload, accept --optim adamw_flash in HfArgumentParser

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…flashoptim>=0.1.4, reject DeepSpeed optimizer offload and malformed boolean optim_args, document switching back to adamw_torch

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 4cfca69755

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

pre-commit.ci run

…t__ (main's eval_steps test execs the class alone)
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: efb0510229

ℹ️ 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 313bfd9 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/opt-flash-adamw branch October 16, 2026 07:30
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 19, 2026
…uantized adamw_flash moments (unslothai#14201)

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