Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
adamw_flash: keep the unquantized bf16 Adam variance in fp32 so it can decay (#14749)
Daniel Han04f21d39a96d
diff --git a/tests/utils/test_flash_adamw_optim.py b/tests/utils/test_flash_adamw_optim.pyindex 14040f03e9b..54159aa6e9c 100644--- a/tests/utils/test_flash_adamw_optim.py+++ b/tests/utils/test_flash_adamw_optim.py@@ -7,6 +7,7 @@ import typesimport pytest+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.pyimport unsloth # noqa: F401 (must precede transformers/trl)import torch@@ -445,7 +446,8 @@ def test_adamw_flash_rejects_fp16_params_with_unquantized_moments(stub_flashoptioptimizer_cls, optimizer_kwargs = flash_adamw.get_flash_adamw_cls_and_kwargs(_flash_kwargs_args(optim_args = optim_args))- with pytest.raises(ValueError, match = "float16"):+ # bf16 is the suggested dtype because its variance is widened to fp32.+ with pytest.raises(ValueError, match = r"bfloat16 \(its variance is kept in float32\)"):optimizer_cls([{"params": [fp32, fp16]}], **optimizer_kwargs)# bf16 / fp32 keep working with unquantized moments.optimizer_cls([{"params": [fp32, bf16]}], **optimizer_kwargs)@@ -517,3 +519,81 @@ def test_adamw_flash_fp16_check_covers_positional_late_and_unfrozen_groups(assert len(optimizer.param_groups) == 2fp16.grad = torch.ones(4, dtype = torch.float16)optimizer.step()+++def _real_flash_adamw(monkeypatch):+ pytest.importorskip("flashoptim")+ import unsloth.optimizers.flash_adamw as flash_adamw++ monkeypatch.setattr(flash_adamw, "_FLASH_ADAMW_CLASS", None)+ return flash_adamw._get_flash_adamw_class()+++def _scaled_noise(step, drop_at):+ # The gradient scale falls 10x at drop_at, as when a finetune moves past its early large+ # gradients. An fp32 EMA follows it down; a variance that cannot decay stays at its peak.+ return torch.randn(1024) * (1.0 if step < drop_at else 0.1)+++def _steady(step, drop_at):+ # A steady gradient: the fp32 EMA rises to grad**2, a bf16 one stalls near a third of it.+ return torch.full((1024,), 0.01)+++def _train(+ cls,+ device,+ gradient = _scaled_noise,+ steps = 2000,+ drop_at = 500,+ **kwargs,+):+ torch.manual_seed(0)+ p = torch.nn.Parameter(torch.zeros(1024, dtype = torch.bfloat16, device = device))+ opt = cls([p], lr = 1e-4, weight_decay = 0.0, quantize = False, **kwargs)+ ema = torch.zeros(1024, device = device)+ for step in range(steps):+ grad = gradient(step, drop_at).to(device = device, dtype = torch.bfloat16)+ ema.mul_(0.999).addcmul_(grad.float(), grad.float(), value = 0.001)+ p.grad = grad+ opt.step()+ return opt, p, ema++[email protected]("gradient", [_scaled_noise, _steady])+def test_adamw_flash_bf16_variance_follows_fp32(monkeypatch, gradient):+ # With bf16 storage and round-to-nearest the variance froze near 0.39 after the drop+ # (fp32: 0.096) and stalled at 0.31x of grad**2 under the steady gradient: at beta2 =+ # 0.999 a step moves it by at most 0.1% of the gap, under half a bf16 ulp.+ cls = _real_flash_adamw(monkeypatch)+ opt, p, ema = _train(cls, "cpu", gradient, master_weight_bits = None, fused = False)+ var = opt.state[p]["exp_avg_sq"].materialize()+ assert var.dtype == torch.float32+ torch.testing.assert_close(var, ema, rtol = 1e-5, atol = 1e-12)+++def test_adamw_flash_bf16_variance_survives_a_state_dict_round_trip(monkeypatch):+ cls = _real_flash_adamw(monkeypatch)+ opt, p, _ = _train(cls, "cpu", steps = 50, drop_at = 25, master_weight_bits = None, fused = False)+ saved = opt.state[p]["exp_avg_sq"].materialize().clone()+ fresh = cls(+ [p], lr = 1e-4, weight_decay = 0.0, quantize = False, master_weight_bits = None, fused = False+ )+ fresh.load_state_dict(opt.state_dict())+ loaded = fresh.state[p]["exp_avg_sq"].materialize()+ assert loaded.dtype == torch.float32+ torch.testing.assert_close(loaded, saved, rtol = 0, atol = 0)++[email protected](not has_real_cuda(), reason = "flashoptim's fused Triton step needs CUDA")[email protected]("gradient", [_scaled_noise, _steady])+def test_adamw_flash_fused_bf16_variance_follows_fp32(monkeypatch, gradient):+ # The fused kernel stores its variance update rounded to the param dtype; the fp32 copy+ # computed beside it is what is kept.+ cls = _real_flash_adamw(monkeypatch)+ opt, p, ema = _train(cls, "cuda", gradient, master_weight_bits = 32)+ var = opt.state[p]["exp_avg_sq"].materialize()+ assert var.dtype == torch.float32+ # fp32 rounding differs between the kernel and the torch EMA (about 2e-5 after 2000 steps).+ torch.testing.assert_close(var, ema, rtol = 1e-4, atol = 1e-12)diff --git a/unsloth/optimizers/flash_adamw.py b/unsloth/optimizers/flash_adamw.pyindex 9d4fc876803..6770a63495f 100644--- a/unsloth/optimizers/flash_adamw.py+++ b/unsloth/optimizers/flash_adamw.py@@ -4,12 +4,13 @@"""`optim = "adamw_flash"`: FlashAdamW from databricks/flashoptim (arXiv 2602.23349).bf16 / fp16 parameters keep a 16 bit error correction term in the optimizer state, so-the effective master weight is fp32, and the Adam moments are stored in the parameter-dtype: about 10 bytes per parameter (with bf16 grads) instead of 16 for bf16 weights-plus fp32 master plus fp32 moments. This default tracked fp32 master AdamW on a real-Qwen2.5-0.5B full finetune. optim_args = "quantize=True" stores the moments in 8 bits-(about 8 bytes per parameter; with "master_weight_bits=24", flashoptim's own default,-about 7), but its loss curve moved measurably away from AdamW there.+the effective master weight is fp32. The momentum is stored in the parameter dtype and the+bf16 variance in fp32 (a bf16 variance cannot decay at beta2 = 0.999): about 12 bytes per+parameter (with bf16 grads) instead of 16 for bf16 weights plus fp32 master plus fp32+moments. This default tracked fp32 master AdamW on a real Qwen2.5-0.5B full finetune.+optim_args = "quantize=True" stores the moments in 8 bits (about 8 bytes per parameter;+with "master_weight_bits=24", flashoptim's own default, about 7), but its loss curve moved+measurably away from AdamW there.fp32 parameters (LoRA adapters) have no correction term; for them only quantize=Truesaves memory. Trainable fp16 parameters need quantize=True: unquantized fp16 momentsunderflow, so the optimizer refuses them.@@ -39,6 +40,7 @@ FLASH_ADAMW_NAME = "adamw_flash"_FLASH_ADAMW_PLACEHOLDER = "adamw_torch"_FLASH_ADAMW_MARKER = "unsloth_adamw_flash"_FLASH_ADAMW_CLASS = None+_VARIANCE_UPDATE_KERNEL = None_FLASH_ADAMW_MIN_VERSION = "0.1.4"_TRUE_VALUES = ("1", "true", "yes")_FALSE_VALUES = ("0", "false", "no")@@ -168,6 +170,50 @@ def _get_flash_adamw_class():self.__dict__.pop("quantized_state_spec", None)_refuse_unquantized_fp16()+ # A bf16 variance cannot move at beta2 = 0.999 (a step is under half an ulp), so it never+ # decays and stalls near grad**2 / 3: the unquantized bf16 variance is kept in fp32.+ def _ensure_state_initialized(self, p, hparams):+ super()._ensure_state_initialized(p, hparams)+ _widen_variance(self.state[p].get("exp_avg_sq"))++ def _load_state_for_param(self, param, opt_state, hparams):+ state = super()._load_state_for_param(param, opt_state, hparams)+ _widen_variance(state.get("exp_avg_sq"))+ return state++ def load_state_dict(self, state_dict):+ # torch.optim casts floating state to the param dtype: restore the fp32 variance.+ saved_ids = [i for g in state_dict.get("param_groups", []) for i in g["params"]]+ params = dict(zip(saved_ids, (p for g in self.param_groups for p in g["params"])))+ fp32_vars = {+ params[i]: v+ for i, st in state_dict.get("state", {}).items()+ if i in params+ and torch.is_tensor(v := st.get("exp_avg_sq"))+ and v.dtype == torch.float32+ }+ super().load_state_dict(state_dict)+ for p, v in fp32_vars.items():+ var = getattr(self.state.get(p, {}).get("exp_avg_sq"), "_data", None)+ v = self._get_local_tensor(v)+ if var is not None and var.dtype == torch.float32 and var.shape == v.shape:+ var.copy_(v)++ def _do_step(self, param, grad, errors, param_state, hparams):+ var = getattr(param_state.get("exp_avg_sq"), "_data", None)+ if (+ not self._fused+ or var is None+ or var.dtype != torch.float32+ or param.dtype == torch.float32+ ):+ return super()._do_step(param, grad, errors, param_state, hparams)+ # The fused kernel stores the variance rounded to the param dtype: keep an fp32 copy.+ new_var = _variance_update(var, grad, hparams["betas"][1])+ out = super()._do_step(param, grad, errors, param_state, hparams)+ param_state["exp_avg_sq"]._data = new_var+ return out+# Every update goes through step_param: step() loops over it and gradient release calls# it per parameter. Checked there against the group's current quantize (load_state_dict# can restore an older group's quantize=False), so a frozen fp16 param unfrozen later is@@ -192,12 +238,43 @@ def _get_flash_adamw_class():return _FLASH_ADAMW_CLASS+def _variance_update(var, grad, beta2):+ """fp32 `var * beta2 + grad**2 * (1 - beta2)`, as flashoptim's fused kernel computes it."""+ global _VARIANCE_UPDATE_KERNEL+ import triton++ if _VARIANCE_UPDATE_KERNEL is None:+ import triton.language as tl++ @triton.jit+ def kernel(var_ptr, grad_ptr, out_ptr, n, beta2, BLOCK: tl.constexpr):+ offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)+ mask = offsets < n+ v = tl.load(var_ptr + offsets, mask = mask)+ g = tl.load(grad_ptr + offsets, mask = mask).to(tl.float32)+ tl.store(out_ptr + offsets, v * beta2 + g * g * (1.0 - beta2), mask = mask)++ _VARIANCE_UPDATE_KERNEL = kernel+ out = torch.empty_like(var)+ n = var.numel()+ _VARIANCE_UPDATE_KERNEL[(triton.cdiv(n, 1024),)](var, grad, out, n, beta2, BLOCK = 1024)+ return out+++def _widen_variance(state):+ # flashoptim's private _MaybeQuantizedTensor fields; absent ones leave its storage as is.+ data = getattr(state, "_data", None)+ if data is not None and data.dtype == torch.bfloat16 and hasattr(state, "_storage_dtype"):+ state._storage_dtype = torch.float32+ state._data = data.float()++def _refuse_unquantized_fp16():raise ValueError(- "Unsloth: optim = 'adamw_flash' with quantize=False stores the Adam moments in "- "the parameter dtype, and float16 moments underflow (wrong updates). Found "- "trainable float16 parameters: cast them to float32 or bfloat16, or set "- "optim_args = 'quantize=True'."+ "Unsloth: optim = 'adamw_flash' with quantize=False stores float16 Adam moments in "+ "float16, where the variance underflows (wrong updates). Found trainable float16 "+ "parameters: cast them to bfloat16 (its variance is kept in float32) or float32, or "+ "set optim_args = 'quantize=True'.")