Skip to content

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.

Add opt-in BF16 AdamW with stochastic parameter updates (#16662)

Daniel Hanf8269bd685a4
diff --git a/tests/test_bf16_adamw.py b/tests/test_bf16_adamw.py
new file mode 100644
index 00000000000..6f242401919
--- /dev/null
+++ b/tests/test_bf16_adamw.py
@@ -0,0 +1,357 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+import copy
+import importlib.util
+import sys
+import gc
+import weakref
+from pathlib import Path
+
+import pytest
+import torch
+from real_accelerator import has_real_cuda
+
+
[email protected](scope = "module")
+def api():
+ path = Path(__file__).resolve().parents[1] / "unsloth/optimizers/bf16_adamw.py"
+ spec = importlib.util.spec_from_file_location("_test_bf16_adamw", path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_prepare_preserves_identity_ties_and_frozen_parameters(api):
+ model = torch.nn.Module()
+ model.first = torch.nn.Linear(4, 4)
+ model.second = torch.nn.Linear(4, 4, bias = False)
+ model.second.weight = model.first.weight
+ model.frozen = torch.nn.Parameter(torch.arange(4.0), requires_grad = False)
+ model.register_buffer("statistics", torch.ones(4))
+ before = {name: id(p) for name, p in model.named_parameters()}
+ frozen = model.frozen.detach().clone()
+ api.prepare_bf16_training(model)
+ assert {name: id(p) for name, p in model.named_parameters()} == before
+ assert model.first.weight is model.second.weight
+ assert model.first.weight.dtype == model.first.bias.dtype == torch.bfloat16
+ assert model.first.weight.requires_grad and model.first.bias.requires_grad
+ assert model.frozen.dtype == torch.float32 and not model.frozen.requires_grad
+ assert torch.equal(model.frozen, frozen)
+ assert model.statistics.dtype == torch.float32
+ api.prepare_bf16_training(model)
+ assert {name: id(p) for name, p in model.named_parameters()} == before
+
+
[email protected]("invalid", ["dtype", "gradient", "layout"])
+def test_prepare_preflight_does_not_partially_cast(api, invalid):
+ model = torch.nn.Module()
+ model.first = torch.nn.Parameter(torch.ones(4))
+ model.last = torch.nn.Parameter(
+ torch.ones(4, dtype = torch.float64 if invalid == "dtype" else torch.float32)
+ )
+ if invalid == "layout":
+ model.last = torch.nn.Parameter(torch.ones(4, 4).T)
+ if invalid == "gradient":
+ model.last.grad = torch.ones_like(model.last)
+ before = [(id(p), p.dtype, p.detach().clone()) for p in model.parameters()]
+ with pytest.raises((ValueError, RuntimeError, TypeError)):
+ api.prepare_bf16_training(model)
+ for param, (identity, dtype, value) in zip(model.parameters(), before):
+ assert id(param) == identity and param.dtype == dtype
+ assert torch.equal(param, value)
+
+
+def test_moments_match_independent_fp32_adamw(api):
+ p = torch.nn.Parameter(torch.linspace(-2, 2, 65, dtype = torch.bfloat16))
+ reference = torch.nn.Parameter(p.detach().float())
+ kwargs = dict(lr = 0.003, betas = (0.7, 0.95), eps = 1e-6, weight_decay = 0.03)
+ optimizer = api.AdamWBF16([p], seed = 57, **kwargs)
+ control = torch.optim.AdamW([reference], foreach = False, fused = False, **kwargs)
+ for step in range(1, 5):
+ gradient = (torch.arange(65).float().sin() * step / 7).bfloat16()
+ p.grad = gradient.clone()
+ reference.grad = gradient.float()
+ optimizer.step()
+ control.step()
+ for key in ("exp_avg", "exp_avg_sq"):
+ assert optimizer.state[p][key].dtype == torch.float32
+ torch.testing.assert_close(
+ optimizer.state[p][key], control.state[reference][key], atol = 2e-8, rtol = 2e-6
+ )
+ assert int(optimizer.state[p]["step"]) == step
+
+
+def test_sub_ulp_update_moves_correct_fraction_and_preserves_rng(api):
+ p = torch.nn.Parameter(torch.ones(65536, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p], lr = 2**-10, betas = (0.0, 0.0), eps = 0.0, weight_decay = 0.0, seed = 71)
+ p.grad = torch.ones_like(p)
+ global_rng = torch.random.get_rng_state().clone()
+ optimizer.step()
+ assert torch.equal(torch.random.get_rng_state(), global_rng)
+ lower = torch.tensor(1 - 2**-8, dtype = torch.bfloat16)
+ assert torch.all((p == 1) | (p == lower))
+ moved = (p == lower).sum().item()
+ assert abs(moved - p.numel() / 4) < 6 * (p.numel() * 0.25 * 0.75) ** 0.5
+ assert abs(p.float().mean().item() - (1 - 2**-10)) < 3e-5
+ mask = (p != 1).clone()
+ with torch.no_grad():
+ p.fill_(1)
+ optimizer.step()
+ assert 0.3 < float((mask != (p != 1)).float().mean()) < 0.45
+
+
+def test_checkpoint_restores_fp32_moments_and_next_random_update(api):
+ p = torch.nn.Parameter(torch.linspace(0.5, 1.5, 4096, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p], lr = 0.0009, weight_decay = 0.01, seed = 81)
+ for step in range(3):
+ p.grad = (torch.arange(p.numel()).float().cos() + step / 10).bfloat16()
+ optimizer.step()
+ state = copy.deepcopy(optimizer.state_dict())
+ restored_p = torch.nn.Parameter(p.detach().clone())
+ restored = api.AdamWBF16([restored_p], lr = 0.2, seed = 999)
+ restored.load_state_dict(state)
+ for key in ("exp_avg", "exp_avg_sq"):
+ assert restored.state[restored_p][key].dtype == torch.float32
+ assert torch.equal(restored.state[restored_p][key], optimizer.state[p][key])
+ for step in range(3):
+ gradient = (torch.arange(p.numel()).float().sin() + step / 20).bfloat16()
+ p.grad = gradient.clone()
+ restored_p.grad = gradient.clone()
+ optimizer.step()
+ restored.step()
+ assert torch.equal(p, restored_p)
+ for key in ("step", "exp_avg", "exp_avg_sq"):
+ assert torch.equal(
+ torch.as_tensor(optimizer.state[p][key]),
+ torch.as_tensor(restored.state[restored_p][key]),
+ )
+
+
+def test_none_gradient_is_skipped_and_groups_keep_own_steps(api):
+ p = torch.nn.Parameter(torch.ones(64, dtype = torch.bfloat16))
+ q = torch.nn.Parameter(torch.full((64,), 2.0, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p], lr = 0.01, weight_decay = 0.1)
+ optimizer.add_param_group({"params": [q], "lr": 0.0})
+ p.grad = torch.ones_like(p)
+ optimizer.step()
+ if optimizer.state.get(q):
+ assert int(optimizer.state[q]["step"]) == 0
+ assert torch.count_nonzero(optimizer.state[q]["exp_avg"]) == 0
+ assert torch.count_nonzero(optimizer.state[q]["exp_avg_sq"]) == 0
+ assert torch.all(q == 2)
+ p_before = p.detach().clone()
+ p.grad = None
+ q.grad = torch.ones_like(q)
+ optimizer.step()
+ assert torch.equal(p, p_before)
+ assert int(optimizer.state[p]["step"]) == 1
+ assert int(optimizer.state[q]["step"]) == 1
+ assert torch.all(q == 2)
+ optimizer.param_groups[1]["lr"] = 0.03
+ optimizer.step()
+ assert torch.all(q < 2)
+ assert int(optimizer.state[q]["step"]) == 2
+
+
+def _tensor_bytes(value):
+ if isinstance(value, torch.Tensor):
+ return value.numel() * value.element_size()
+ if isinstance(value, dict):
+ return sum(_tensor_bytes(v) for v in value.values())
+ if isinstance(value, (list, tuple)):
+ return sum(_tensor_bytes(v) for v in value)
+ return 0
+
+
+def test_persistent_storage_has_no_master_weight(api):
+ p = torch.nn.Parameter(torch.ones(4096, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p])
+ p.sum().backward()
+ optimizer.step()
+ storage = p.numel() * p.element_size() + p.grad.numel() * p.grad.element_size()
+ storage += _tensor_bytes(optimizer.state_dict())
+ assert p.grad.dtype == torch.bfloat16
+ assert storage <= 12 * p.numel() + 8192
+ for key, value in optimizer.state[p].items():
+ if isinstance(value, torch.Tensor) and value.numel() == p.numel():
+ assert key in ("exp_avg", "exp_avg_sq")
+
+
+def test_optimizer_does_not_retain_gradients(api):
+ p = torch.nn.Parameter(torch.ones(32, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p])
+ p.sum().backward()
+ gradient = weakref.ref(p.grad)
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+ gc.collect()
+ assert gradient() is None
+
+
+def test_frozen_parameters_have_no_moments_and_can_be_unfrozen(api):
+ frozen = torch.nn.Parameter(torch.ones(65536), requires_grad = False)
+ packed = torch.nn.Parameter(torch.ones(65536, dtype = torch.uint8), requires_grad = False)
+ p = torch.nn.Parameter(torch.ones(32, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([frozen, packed, p])
+ assert not optimizer.state
+ assert frozen not in optimizer.state and packed not in optimizer.state
+ p.sum().backward()
+ optimizer.step()
+ assert frozen not in optimizer.state and packed not in optimizer.state
+ frozen.data = frozen.data.bfloat16()
+ frozen.requires_grad_(True)
+ frozen.grad = torch.ones_like(frozen)
+ optimizer.step()
+ assert int(optimizer.state[frozen]["step"]) == 1
+ assert torch.any(frozen != 1)
+ assert packed not in optimizer.state
+
+
[email protected]("dtype", [torch.float16, torch.float64, torch.complex64])
+def test_unsupported_parameter_dtype_is_rejected(api, dtype):
+ p = torch.nn.Parameter(torch.ones(8, dtype = dtype))
+ with pytest.raises((ValueError, RuntimeError, TypeError)):
+ optimizer = api.AdamWBF16([p])
+ p.grad = torch.ones_like(p)
+ optimizer.step()
+
+
+def test_sparse_gradient_is_rejected_without_updating_parameter(api):
+ p = torch.nn.Parameter(torch.ones(8, dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p])
+ p.grad = torch.sparse_coo_tensor(
+ [[1, 3]], torch.ones(2, dtype = p.dtype), (8,), check_invariants = True
+ )
+ before = p.detach().clone()
+ with pytest.raises((ValueError, RuntimeError, TypeError)):
+ optimizer.step()
+ assert torch.equal(p, before)
+
+
+def _cuda_pair(api):
+ initial = torch.linspace(0.5, 1.5, 4096, device = "cuda", dtype = torch.bfloat16)
+ params = [torch.nn.Parameter(initial.clone()) for _ in range(2)]
+ optimizers = [api.AdamWBF16([p], lr = 0.0009, seed = 73) for p in params]
+ for p in params:
+ p.grad = torch.ones_like(p)
+ return params, optimizers
+
+
[email protected](not has_real_cuda(), reason = "requires real CUDA")
+def test_gpu_stochastic_update_has_expected_mean_and_preserves_rng(api):
+ p = torch.nn.Parameter(torch.ones(65536, device = "cuda", dtype = torch.bfloat16))
+ optimizer = api.AdamWBF16([p], lr = 2**-10, betas = (0.0, 0.0), eps = 0.0, weight_decay = 0.0)
+ p.grad = torch.ones_like(p)
+ rng = torch.cuda.get_rng_state().clone()
+ optimizer.step()
+ assert torch.equal(torch.cuda.get_rng_state(), rng)
+ lower = 1 - 2**-8
+ assert torch.all((p == 1) | (p == lower))
+ moved = int((p == lower).sum())
+ assert abs(moved - p.numel() / 4) < 6 * (p.numel() * 0.25 * 0.75) ** 0.5
+ assert abs(float(p.float().mean()) - (1 - 2**-10)) < 3e-5
+ mask = (p != 1).clone()
+ with torch.no_grad():
+ p.fill_(1)
+ optimizer.step()
+ assert 0.3 < float((mask != (p != 1)).float().mean()) < 0.45
+
+
[email protected](not has_real_cuda(), reason = "requires real CUDA")
+def test_gpu_moments_match_independent_fp32_adamw(api):
+ p = torch.nn.Parameter(torch.ones(65, device = "cuda", dtype = torch.bfloat16))
+ reference = torch.nn.Parameter(p.detach().float().cpu())
+ kwargs = dict(lr = 0.003, betas = (0.7, 0.95), eps = 1e-6, weight_decay = 0.03)
+ optimizer = api.AdamWBF16([p], **kwargs)
+ control = torch.optim.AdamW([reference], **kwargs)
+ for step in range(1, 5):
+ gradient = (torch.arange(65).float().sin() * step / 7).bfloat16()
+ p.grad = gradient.to("cuda")
+ reference.grad = gradient.float()
+ optimizer.step()
+ control.step()
+ for key in ("exp_avg", "exp_avg_sq"):
+ torch.testing.assert_close(
+ optimizer.state[p][key].cpu(), control.state[reference][key], atol = 2e-8, rtol = 2e-6
+ )
+
+
+def _assert_optimizer_equal(params, optimizers):
+ assert torch.equal(*params)
+ for key in ("exp_avg", "exp_avg_sq", "step"):
+ assert torch.equal(optimizers[0].state[params[0]][key], optimizers[1].state[params[1]][key])
+
+
[email protected](not has_real_cuda(), reason = "requires real CUDA")
+def test_compiled_optimizer_matches_eager_without_graph_breaks(api):
+ from torch._dynamo.utils import counters
+
+ params, optimizers = _cuda_pair(api)
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(optimizers[1].step, fullgraph = True)
+ try:
+ for index in range(4):
+ gradient = (torch.arange(4096, device = "cuda").float().sin() + index / 10).bfloat16()
+ for p in params:
+ p.grad.copy_(gradient)
+ optimizers[0].step()
+ compiled()
+ _assert_optimizer_equal(params, optimizers)
+ assert int(optimizers[1].state[params[1]]["step"]) == 4
+ assert sum(counters["graph_break"].values()) == 0
+ assert counters["stats"]["unique_graphs"] > 0
+ finally:
+ torch._dynamo.reset()
+
+
[email protected](not has_real_cuda(), reason = "requires real CUDA")
+def test_cuda_graph_replay_advances_stochastic_updates(api):
+ params, optimizers = _cuda_pair(api)
+ stream = torch.cuda.Stream()
+ stream.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(stream):
+ for optimizer in optimizers:
+ optimizer.step()
+ torch.cuda.current_stream().wait_stream(stream)
+ torch.cuda.synchronize()
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph):
+ optimizers[1].step()
+ for _ in range(5):
+ optimizers[0].step()
+ graph.replay()
+ _assert_optimizer_equal(params, optimizers)
+ assert int(optimizers[1].state[params[1]]["step"]) == 6
+
+
[email protected](not has_real_cuda(), reason = "requires real CUDA")
+def test_batched_updates_match_separate_groups_and_new_gradients(api):
+ shapes = [0, 1, 17, 255, 256, 257, 1025, 4096, 8193, 33, 65537] * 7
+ params = [
+ torch.nn.Parameter(torch.ones(n, device = "cuda", dtype = torch.bfloat16)) for n in shapes
+ ]
+ reference = [torch.nn.Parameter(p.detach().clone()) for p in params]
+ optimizer = api.AdamWBF16(params, lr = 0.0001)
+ control = api.AdamWBF16([{"params": [p]} for p in reference], lr = 0.0001)
+ for step in range(4):
+ for i, (p, q) in enumerate(zip(params, reference)):
+ gradient = (torch.arange(p.numel(), device = "cuda").float().sin() + step / 10).bfloat16()
+ p.grad = None if i == step else gradient.clone()
+ q.grad = None if i == step else gradient.clone()
+ optimizer.step()
+ control.step()
+ assert all(torch.equal(p, q) for p, q in zip(params, reference))
+ for p, q in zip(params, reference):
+ assert bool(optimizer.state.get(p)) == bool(control.state.get(q))
+ if not optimizer.state.get(p):
+ continue
+ for key in ("step", "exp_avg", "exp_avg_sq"):
+ assert torch.equal(optimizer.state[p][key], control.state[q][key])
diff --git a/unsloth/optimizers/__init__.py b/unsloth/optimizers/__init__.py
index e860bcac2fd..655f6cc45c9 100644
--- a/unsloth/optimizers/__init__.py
+++ b/unsloth/optimizers/__init__.py
@@ -15,4 +15,13 @@ from .q_galore_adamw import QGaLoreAdamW8bit
__all__ = [
"GaLoreProjector",
"QGaLoreAdamW8bit",
+ "AdamWBF16",
+ "prepare_bf16_training",
]
+
+
+def __getattr__(name):
+ if name in ("AdamWBF16", "prepare_bf16_training"):
+ from . import bf16_adamw
+ return getattr(bf16_adamw, name)
+ raise AttributeError(name)
diff --git a/unsloth/optimizers/bf16_adamw.py b/unsloth/optimizers/bf16_adamw.py
new file mode 100644
index 00000000000..f8b896fdfb2
--- /dev/null
+++ b/unsloth/optimizers/bf16_adamw.py
@@ -0,0 +1,404 @@
+# SPDX-License-Identifier: AGPL-3.0-or-later
+
+import math
+import torch
+from torch import Tensor
+from typing import List
+
+try:
+ import triton
+ import triton.language as tl
+except ImportError:
+ triton = None
+
+if triton is not None:
+ _BATCHED_ARGUMENTS = tuple(int(x) for x in triton.__version__.split(".")[:2]) >= (3, 3)
+
+ @triton.jit(do_not_specialize = ["N"])
+ def _adamw_tile(
+ P,
+ G,
+ M,
+ V,
+ STEP,
+ LR,
+ N,
+ SEED,
+ TILE,
+ B1: tl.constexpr,
+ B2: tl.constexpr,
+ EPS: tl.constexpr,
+ WD: tl.constexpr,
+ BLOCK: tl.constexpr,
+ ):
+ i = TILE.to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
+ valid = i < N
+ p = tl.load(P + i, valid, 0).to(tl.float32)
+ g = tl.load(G + i, valid, 0).to(tl.float32)
+ m = tl.load(M + i, valid, 0)
+ v = tl.load(V + i, valid, 0)
+ step = tl.load(STEP)
+ lr = tl.load(LR)
+ m = m + (g - m) * (1.0 - B1)
+ v = v + (g * g - v) * (1.0 - B2)
+ bc1 = 1.0 - tl.exp(tl.log(B1) * step.to(tl.float32))
+ bc2 = 1.0 - tl.exp(tl.log(B2) * step.to(tl.float32))
+ p = p * (1.0 - lr * WD) - lr * (m / bc1) / (tl.sqrt(v / bc2) + EPS)
+ bits = p.to(tl.uint32, bitcast = True)
+ low = bits & 65535
+ upper = bits & 4294901760
+ random = (
+ tl.randint(tl.load(SEED).to(tl.uint64) + step.to(tl.uint64), i.to(tl.uint32)) & 65535
+ )
+ special = (bits & 2139095040) == 2139095040
+ rounded = tl.where((random < low) & ~special, upper + 65536, upper)
+ # Preserve exceptional values instead of rounding NaN payloads into infinity.
+ result = tl.where(special, bits, rounded).to(tl.float32, bitcast = True)
+ tl.store(P + i, result.to(tl.bfloat16), valid)
+ tl.store(M + i, m, valid)
+ tl.store(V + i, v, valid)
+
+ @triton.jit(do_not_specialize = ["sizes"])
+ def _adamw_batched(
+ P,
+ G,
+ M,
+ V,
+ STEP,
+ SEED,
+ LR,
+ sizes,
+ B1: tl.constexpr,
+ B2: tl.constexpr,
+ EPS: tl.constexpr,
+ WD: tl.constexpr,
+ BLOCK: tl.constexpr,
+ ):
+ pid = tl.program_id(0).to(tl.int64)
+ start = tl.full((), 0, tl.int64)
+ for j in tl.static_range(len(sizes)):
+ n = tl.cast(sizes[j], tl.int64)
+ stop = start + (n + BLOCK - 1) // BLOCK
+ if (pid >= start) & (pid < stop):
+ _adamw_tile(
+ P[j],
+ G[j],
+ M[j],
+ V[j],
+ STEP[j],
+ LR,
+ n,
+ SEED[j],
+ pid - start,
+ B1,
+ B2,
+ EPS,
+ WD,
+ BLOCK,
+ )
+ start = stop
+
+ @triton.jit(do_not_specialize = ["N"])
+ def _adamw_single(
+ P,
+ G,
+ M,
+ V,
+ STEP,
+ LR,
+ N,
+ SEED,
+ B1: tl.constexpr,
+ B2: tl.constexpr,
+ EPS: tl.constexpr,
+ WD: tl.constexpr,
+ BLOCK: tl.constexpr,
+ ):
+ _adamw_tile(P, G, M, V, STEP, LR, N, SEED, tl.program_id(0), B1, B2, EPS, WD, BLOCK)
+
+ def _launch(
+ p: List[Tensor],
+ g: List[Tensor],
+ m: List[Tensor],
+ v: List[Tensor],
+ step: List[Tensor],
+ lr: Tensor,
+ seed: List[Tensor],
+ beta1: float,
+ beta2: float,
+ eps: float,
+ weight_decay: float,
+ ) -> None:
+ sizes = tuple(x.numel() for x in p)
+ tiles = sum((n + 255) // 256 for n in sizes)
+ if not tiles:
+ return
+ with torch.cuda.device(p[0].device):
+ if not _BATCHED_ARGUMENTS:
+ for pi, gi, mi, vi, si, seedi, n in zip(p, g, m, v, step, seed, sizes):
+ if n:
+ _adamw_single[((n + 255) // 256,)](
+ pi,
+ gi,
+ mi,
+ vi,
+ si,
+ lr,
+ n,
+ seedi,
+ beta1,
+ beta2,
+ eps,
+ weight_decay,
+ 256,
+ enable_fp_fusion = False,
+ )
+ return
+ _adamw_batched[(tiles,)](
+ tuple(p),
+ tuple(g),
+ tuple(m),
+ tuple(v),
+ tuple(step),
+ tuple(seed),
+ lr,
+ sizes,
+ beta1,
+ beta2,
+ eps,
+ weight_decay,
+ 256,
+ enable_fp_fusion = False,
+ )
+
+ # Keep this fused update opaque so Inductor cannot change its rounding.
+ _cuda_update = torch.library.custom_op(
+ "unsloth::adamw_bf16_update", mutates_args = {"p", "m", "v"}
+ )(_launch)
+
+ @_cuda_update.register_fake
+ def _fake_update(p, g, m, v, step, lr, seed, beta1, beta2, eps, weight_decay):
+ return None
+
+
+def _plain_parameter(p):
+ return type(p) in (Tensor, torch.nn.Parameter) and p.layout == torch.strided
+
+
+def prepare_bf16_training(model):
+ params = [p for p in model.parameters() if p.requires_grad]
+ for p in params:
+ if (
+ not _plain_parameter(p)
+ or p.dtype not in (torch.float32, torch.bfloat16)
+ or not p.is_contiguous()
+ or p.device.type not in ("cpu", "cuda")
+ ):
+ raise ValueError(
+ "BF16 training requires contiguous plain FP32/BF16 CPU or CUDA parameters"
+ )
+ if p.grad is not None:
+ raise ValueError("Prepare BF16 training before creating gradients")
+ with torch.no_grad():
+ for p in params:
+ p.data = p.data.to(torch.bfloat16)
+ return model
+
+
+def _cpu_update(p, g, m, v, step, lr, seed, beta1, beta2, eps, weight_decay):
+ generator = torch.Generator(device = "cpu")
+ stream = (int(seed) + int(step)) % (2**63 - 1)
+ generator.manual_seed(stream ^ (stream >> 32))
+ gf = g.float()
+ m.lerp_(gf, 1 - beta1)
+ v.lerp_(gf.square(), 1 - beta2)
+ t = int(step)
+ value = p.float() * (1 - lr * weight_decay)
+ value = value - lr * (m / (1 - beta1**t)) / ((v / (1 - beta2**t)).sqrt() + eps)
+ bits = value.contiguous().view(torch.int32)
+ random = torch.randint(65536, bits.shape, generator = generator, dtype = torch.int32)
+ upper = bits & -65536
+ rounded = upper + ((random < (bits & 65535)).to(torch.int32) << 16)
+ special = (bits & 2139095040) == 2139095040
+ p.copy_(torch.where(special, bits, rounded).view(torch.float32))
+
+
+class AdamWBF16(torch.optim.Optimizer):
+ def __init__(
+ self,
+ params,
+ lr = 1e-3,
+ betas = (0.9, 0.999),
+ eps = 1e-8,
+ weight_decay = 0.01,
+ *,
+ seed = 3407,
+ ):
+ if any(not math.isfinite(float(x)) or float(x) < 0 for x in (lr, eps, weight_decay)):
+ raise ValueError("Invalid learning rate, epsilon or weight decay")
+ if not all(0 <= b < 1 for b in betas):
+ raise ValueError("Invalid Adam betas")
+ super().__init__(
+ params, dict(lr = lr, betas = betas, eps = eps, weight_decay = weight_decay, seed = int(seed))
+ )
+ self._initialize()
+ self._ready = True
+
+ def add_param_group(self, param_group):
+ param_group = dict(param_group)
+ values = param_group["params"]
+ values = [values] if isinstance(values, Tensor) else list(values)
+ param_group["params"] = values
+ for p in values:
+ if isinstance(p, Tensor) and not p.requires_grad and p.grad is None:
+ continue
+ if (
+ not isinstance(p, Tensor)
+ or not _plain_parameter(p)
+ or p.dtype != torch.bfloat16
+ or not p.is_contiguous()
+ or p.device.type not in ("cpu", "cuda")
+ or p.numel() > 2**32
+ ):
+ raise ValueError(
+ "AdamWBF16 requires dense contiguous BF16 parameters with <=2**32 elements"
+ )
+ if p.device.type == "cuda" and triton is None:
+ raise RuntimeError("CUDA AdamWBF16 requires Triton")
+ group = {**self.defaults, **param_group}
+ if any(
+ not math.isfinite(float(group[k])) or float(group[k]) < 0
+ for k in ("lr", "eps", "weight_decay")
+ ):
+ raise ValueError("Invalid AdamW hyperparameters")
+ if len(group["betas"]) != 2 or not all(0 <= b < 1 for b in group["betas"]):
+ raise ValueError("Invalid Adam betas")
+ super().add_param_group(param_group)
+ if hasattr(self, "_ready"):
+ self._initialize()
+
+ def _initialize(self):
+ params = [
+ p
+ for group in self.param_groups
+ for p in group["params"]
+ if p.requires_grad or p.grad is not None
+ ]
+ for p in params:
+ if not _plain_parameter(p) or p.dtype != torch.bfloat16 or not p.is_contiguous():
+ raise ValueError("AdamWBF16 requires contiguous plain BF16 parameters")
+ if p.device.type not in ("cpu", "cuda"):
+ raise ValueError("AdamWBF16 supports CPU and CUDA only")
+ if p.device.type == "cuda" and triton is None:
+ raise RuntimeError("CUDA AdamWBF16 requires Triton")
+ index = 0
+ for group in self.param_groups:
+ device = torch.device("cpu")
+ for p in group["params"]:
+ if p.requires_grad or p.grad is not None:
+ device = p.device
+ break
+ group["lr"] = torch.as_tensor(group["lr"], dtype = torch.float32, device = device)
+ for p in group["params"]:
+ if p.grad is None:
+ index += 1
+ continue
+ state = self.state[p]
+ if not state:
+ state.update(
+ step = torch.zeros((), device = p.device, dtype = torch.int64),
+ exp_avg = torch.zeros_like(p, dtype = torch.float32),
+ exp_avg_sq = torch.zeros_like(p, dtype = torch.float32),
+ sr_seed = torch.tensor(
+ (int(group["seed"]) + (index << 32)) % (2**63 - 1),
+ device = p.device,
+ dtype = torch.int64,
+ ),
+ )
+ index += 1
+
+ @torch.no_grad()
+ def step(self, closure = None):
+ loss = None
+ if closure is not None:
+ with torch.enable_grad():
+ loss = closure()
+ for group in self.param_groups:
+ for p in group["params"]:
+ g = p.grad
+ if not p.requires_grad and g is None:
+ continue
+ if not _plain_parameter(p) or p.dtype != torch.bfloat16 or not p.is_contiguous():
+ raise ValueError("AdamWBF16 requires contiguous plain BF16 parameters")
+ if g is not None and (
+ not _plain_parameter(g) or g.dtype != torch.bfloat16 or not g.is_contiguous()
+ ):
+ raise ValueError("AdamWBF16 requires dense contiguous BF16 gradients")
+ if any(
+ p.grad is not None and not self.state.get(p)
+ for group in self.param_groups
+ for p in group["params"]
+ ):
+ self._initialize()
+ for group in self.param_groups:
+ by_device = {}
+ for p in group["params"]:
+ if p.grad is not None:
+ by_device.setdefault(p.device, []).append(p)
+ for device, params in by_device.items():
+ lr = torch.as_tensor(group["lr"], dtype = torch.float32, device = device)
+ torch._foreach_add_([self.state[p]["step"] for p in params], 1)
+ if device.type == "cpu":
+ for p in params:
+ state = self.state[p]
+ _cpu_update(
+ p,
+ p.grad,
+ state["exp_avg"],
+ state["exp_avg_sq"],
+ state["step"],
+ lr,
+ state["sr_seed"],
+ *group["betas"],
+ group["eps"],
+ group["weight_decay"],
+ )
+ continue
+ small, large = [], []
+ for p in params:
+ (small if p.numel() <= 65536 else large).append(p)
+ for width, bucket in ((32, small), (8, large)):
+ for start in range(0, len(bucket), width):
+ batch = bucket[start : start + width]
+ states = [self.state[p] for p in batch]
+ update = _cuda_update if torch.compiler.is_compiling() else _launch
+ update(
+ batch,
+ [p.grad for p in batch],
+ [state["exp_avg"] for state in states],
+ [state["exp_avg_sq"] for state in states],
+ [state["step"] for state in states],
+ lr,
+ [state["sr_seed"] for state in states],
+ *group["betas"],
+ group["eps"],
+ group["weight_decay"],
+ )
+ if not torch.compiler.is_compiling():
+ torch.autograd.graph.increment_version(batch)
+ return loss
+
+ def load_state_dict(self, state_dict):
+ saved = state_dict
+ super().load_state_dict(state_dict)
+ for group, original_group in zip(self.param_groups, saved["param_groups"]):
+ for p, old_id in zip(group["params"], original_group["params"]):
+ original = saved["state"].get(old_id)
+ if original is None:
+ continue
+ state = self.state[p]
+ for name in ("exp_avg", "exp_avg_sq"):
+ state[name] = original[name].to(device = p.device, dtype = torch.float32)
+ state["step"] = original["step"].to(device = p.device, dtype = torch.int64)
+ state["sr_seed"] = original["sr_seed"].to(device = p.device, dtype = torch.int64)
+ self._initialize()
diff --git a/unsloth/optimizers/bf16_training.md b/unsloth/optimizers/bf16_training.md
new file mode 100644
index 00000000000..c593ed6f5ae
--- /dev/null
+++ b/unsloth/optimizers/bf16_training.md
@@ -0,0 +1,68 @@
+# BF16 parameters with stochastic AdamW updates
+
+`AdamWBF16` stores trainable parameters and their gradients in BF16. Adam's
+moment buffers and update arithmetic remain FP32; there is no FP32 master
+weight. The GPU kernel computes the update and stochastically rounds the
+new parameter in one pass, without allocating a full FP32 parameter temporary.
+
+Apply preparation after attaching adapters and before creating the trainer or
+optimizer:
+
+```python
+from unsloth.optimizers import AdamWBF16, prepare_bf16_training
+from trl import SFTConfig, SFTTrainer
+
+# model has already been loaded and its trainable parameters selected.
+prepare_bf16_training(model)
+training_args = SFTConfig(bf16=True, fp16=False, learning_rate=2e-4, seed=3407)
+trainer = SFTTrainer(
+ model=model,
+ processing_class=tokenizer,
+ train_dataset=dataset,
+ args=training_args,
+ optimizer_cls_and_kwargs=(AdamWBF16, {
+ "lr": training_args.learning_rate,
+ "betas": (training_args.adam_beta1, training_args.adam_beta2),
+ "eps": training_args.adam_epsilon,
+ "seed": training_args.seed,
+ }),
+)
+trainer.train()
+```
+
+Preparation operates on trainable parameters, without architecture-specific
+target names. Frozen base weights, including quantized QLoRA weights, and buffers
+are unchanged. It preserves parameter identity and tied weights. Call it after
+any model preparation that upcasts adapters or norms, and before wrapping or
+sharding parameters. Dense, contiguous BF16 parameters are supported; tensor
+subclasses, sparse gradients and sharded parameters are refused.
+
+Weights, gradients and two moments use 12 bytes per trainable scalar, plus scalar
+state, versus 16 bytes for FP32 parameters, gradients and moments. Activations,
+frozen weights and framework buffers are additional. Keeping the moments FP32
+avoids losing small variance updates at common `beta2=0.999`.
+Moment buffers are allocated when a parameter first receives a gradient; frozen
+parameters and unused experts do not receive unnecessary optimizer buffers.
+
+Triton 3.3 and newer batch up to 32 small or eight larger parameter tensors per
+update launch.
+Older Triton versions use the same fused update one tensor at a time. Compiling
+the optimizer step with `torch.compile(..., fullgraph=True)` is supported on GPU;
+CPU provides a reference implementation.
+
+Stochastic rounding preserves the expectation of the FP32 update when both
+neighboring BF16 values are finite. It cannot recover rounding already incurred
+in BF16 matrix operations or gradient accumulation. This changes training
+numerics; validate the loss and evaluation quality for the intended workload.
+Values above the largest finite BF16 value may overflow to infinity.
+
+Each parameter has a checkpointed random seed and device step counter, independent
+of model dropout and the global RNG. Replicated parameters require the same seed,
+parameter ordering and updates on every rank. CPU is a correctness reference and
+uses a different random sequence from the GPU. CUDA graph replay advances the
+device counter. Keep learning rates as device tensors during capture; changing
+Python hyperparameters requires recapturing the graph. Use separate parameter
+groups per device for capture.
+
+The rounding rule follows [Revisiting BFloat16 Training](https://arxiv.org/abs/2010.06192)
+and [TorchAO's stochastic optimizer rounding](https://github.com/pytorch/ao/blob/main/torchao/optim/README.md).