Repository navigation
Add optim = "adamw_flash" (FlashAdamW from flashoptim) for lower optimizer memory - #13881
Conversation
…eader, keep the selection across dataclasses.replace
Codex Review SummaryThis 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. |
…arker, reject FSDP1 and non NVIDIA Linux, refuse mixed dtype uncompressed quantized resume [skip ci]
…s, reject FSDP2 CPU offload, accept --optim adamw_flash in HfArgumentParser [skip ci]
…flashoptim>=0.1.4, reject DeepSpeed optimizer offload and malformed boolean optim_args, document switching back to adamw_torch [skip ci]
|
Codex Review: Didn't find any major issues. Bravo. 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". |
|
pre-commit.ci run |
…t__ (main's eval_steps test execs the class alone)
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
# Conflicts: # unsloth/trainer.py
…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.
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:
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.