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.

float16: agree on GradScaler skips across pipeline stages, scale the CP start, probe the float16 FP8 GEMM (#16070)

Daniel Hanaa3dba5b7cb1
diff --git a/tests/test_context_parallel_fp16_scale.py b/tests/test_context_parallel_fp16_scale.py
new file mode 100644
index 00000000000..e9ff0d90fa7
--- /dev/null
+++ b/tests/test_context_parallel_fp16_scale.py
@@ -0,0 +1,97 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""CP over DDP / accelerate FSDP2 must start the float16 GradScaler at 2**16 / world (rank grads are world x one GPU's)."""
+
+import types
+
+import pytest
+import torch
+
+import unsloth # noqa: F401
+from unsloth import context_parallel as cp
+
+SCALE = 2.0**16
+TOKENS = 8
+FP16_GRAD = (
+ 40000.0 # one GPU's scaled per-token output gradient at 2**16: below the float16 max (65504)
+)
+
+
+class _Handler:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ def to_kwargs(self):
+ return dict(self.kwargs)
+
+
+def _trainer(
+ world,
+ scaler,
+ handler = None,
+):
+ accelerator = types.SimpleNamespace(
+ scaler = scaler,
+ scaler_handler = handler,
+ num_processes = world,
+ state = types.SimpleNamespace(device_mesh = None),
+ )
+ manager = types.SimpleNamespace(device_mesh = None, fsdp2 = False)
+ return types.SimpleNamespace(
+ accelerator = accelerator,
+ model = torch.nn.Linear(2, 2),
+ args = types.SimpleNamespace(ddp_find_unused_parameters = False),
+ _context_parallel_manager = manager,
+ )
+
+
+def _found_inf(scaler, world):
+ """One CP rank's float16 backward at the scaler's start scale: world x one GPU's per-token gradient."""
+ torch.manual_seed(0)
+ x = torch.rand(TOKENS // world, 8) * 1e-3
+ w = torch.nn.Parameter(torch.randn(8, 8) * 0.1)
+ coef = FP16_GRAD * TOKENS / SCALE
+ out = torch.nn.functional.linear(x.half(), w.half())
+ opt = torch.optim.SGD([w], lr = 1e-3)
+ scaler.scale((out.float() * coef).sum() / TOKENS * world).backward()
+ scaler.unscale_(opt)
+ return float(
+ sum(
+ v.item() for v in scaler._per_optimizer_states[id(opt)]["found_inf_per_device"].values()
+ )
+ )
+
+
[email protected]("world", [2, 4])
+def test_cp_trainer_starts_the_scaler_at_two_16_over_world(world):
+ trainer = _trainer(world, torch.amp.GradScaler("cpu"))
+ cp._install_accelerator_state(trainer)
+ scaler = trainer.accelerator.scaler
+ assert scaler._init_scale == SCALE / world
+ # The hook runs again on train / evaluate: divided once.
+ cp._install_accelerator_state(trainer)
+ assert scaler._init_scale == SCALE / world
+ assert _found_inf(scaler, world) == 0.0
+ # The start scale it replaces overflows on the same CP backward (what one GPU at 2**16 does not).
+ assert _found_inf(torch.amp.GradScaler("cpu", init_scale = SCALE), world) == 1.0
+ assert _found_inf(torch.amp.GradScaler("cpu", init_scale = SCALE), 1) == 0.0
+
+
+def test_cp_scaler_start_leaves_user_started_and_native_scalers():
+ user = _trainer(2, torch.amp.GradScaler("cpu", init_scale = SCALE), _Handler(init_scale = SCALE))
+ cp._install_accelerator_state(user)
+ assert user.accelerator.scaler._init_scale == SCALE
+ native = _trainer(2, torch.amp.GradScaler("cpu", init_scale = SCALE / 2)) # FSDP2 / TP set it
+ cp._install_accelerator_state(native)
+ assert native.accelerator.scaler._init_scale == SCALE / 2
+ started = _trainer(2, torch.amp.GradScaler("cpu"))
+ started.accelerator.scaler.scale(torch.ones(()))
+ cp._install_accelerator_state(started)
+ assert started.accelerator.scaler.get_scale() == SCALE
+ off = _trainer(2, None)
+ cp._install_accelerator_state(off)
+ no_cp = _trainer(2, torch.amp.GradScaler("cpu"))
+ no_cp._context_parallel_manager = None
+ cp._install_accelerator_state(no_cp)
+ assert no_cp.accelerator.scaler._init_scale == SCALE
diff --git a/tests/test_float8_training.py b/tests/test_float8_training.py
index afcdc2ff5e7..617617ebec8 100644
--- a/tests/test_float8_training.py
+++ b/tests/test_float8_training.py
@@ -462,3 +462,75 @@ def test_conversion_adds_no_hooks_to_an_undispatched_model():
)
assert converted
assert not any(hasattr(m, "_hf_hook") for m in model.modules())
+
+
+def _probe_out_dtypes(monkeypatch, recipe, *args):
+ seen = []
+
+ def fake_scaled_mm(
+ a,
+ b,
+ scale_a,
+ scale_b,
+ out_dtype = None,
+ **kwargs,
+ ):
+ seen.append((tuple(scale_a.shape) != (), out_dtype))
+
+ monkeypatch.setattr(torch, "_scaled_mm", fake_scaled_mm)
+ f8t._probe_float8_gemm(torch.device("cpu"), recipe, *args)
+ return seen
+
+
+def test_probe_writes_the_output_dtype_torchao_asks_for(monkeypatch):
+ # bfloat16 training: every GEMM writes bfloat16 (unchanged).
+ assert {o for _, o in _probe_out_dtypes(monkeypatch, "tensorwise")} == {torch.bfloat16}
+ # float16 training: tensorwise GEMMs write float16 (a different cuBLAS path); torchao runs rowwise
+ # float16 in bfloat16 and casts, so rowwise still probes bfloat16.
+ tensorwise = _probe_out_dtypes(monkeypatch, "tensorwise", torch.float16)
+ assert tensorwise and all(
+ o == torch.float16 for rowwise, o in tensorwise if not rowwise
+ ), tensorwise
+ rowwise = _probe_out_dtypes(monkeypatch, "rowwise", torch.float16)
+ assert rowwise and {o for _, o in rowwise} == {torch.bfloat16}, rowwise
+
+
+def test_float16_model_probes_float16_output(monkeypatch):
+ """A float16 full finetune runs torchao's tensorwise GEMMs with a float16 output, which the bfloat16-only
+ probe never exercised: the hardware check must probe what training runs, and say so when it fails."""
+ seen = []
+ monkeypatch.setattr(
+ f8t, "_check_hardware", lambda device, recipe, dtype = torch.bfloat16: seen.append(dtype)
+ )
+ config = _emulated_config("tensorwise")
+ object.__setattr__(config, "emulate", False)
+ f8t.convert_model_to_float8_training(_tiny_qwen3(torch.float16), config, size_filter = False)
+ assert seen and set(seen) == {torch.float16}, seen
+ seen.clear()
+ f8t.convert_model_to_float8_training(_tiny_qwen3(torch.bfloat16), config, size_filter = False)
+ assert seen and set(seen) == {torch.bfloat16}, seen
+
+
+def test_float16_probe_failure_names_the_output_dtype(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (12, 0))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda *a: "NVIDIA RTX PRO 6000 Blackwell")
+ monkeypatch.setattr(torch.version, "hip", None)
+ calls = []
+
+ def fp16_unsupported(
+ device,
+ recipe,
+ dtype = torch.bfloat16,
+ ):
+ calls.append(dtype)
+ if dtype == torch.float16:
+ raise RuntimeError("out_dtype float16 not supported")
+
+ monkeypatch.setattr(f8t, "_probe_float8_gemm", fp16_unsupported)
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise")
+ with pytest.raises(
+ RuntimeError, match = "tensorwise scaling, float16 output\\) is not supported"
+ ):
+ f8t._check_hardware(torch.device("cuda", 0), "tensorwise", torch.float16)
+ assert calls == [torch.bfloat16, torch.float16]
diff --git a/tests/test_pp_native_fp16_skip_gloo.py b/tests/test_pp_native_fp16_skip_gloo.py
new file mode 100644
index 00000000000..b90fae1d601
--- /dev/null
+++ b/tests/test_pp_native_fp16_skip_gloo.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""float16 GradScaler skip agreement over pipeline stages when the caller uses the plain torch AMP recipe.
+An inf on one stage must skip the step and back off the scale on every stage."""
+
+import multiprocessing
+import os
+
+if multiprocessing.parent_process() is not None or getattr(
+ multiprocessing.current_process(), "_inheriting", False
+):
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
+
+import pickle # noqa: E402
+import sys # noqa: E402
+import tempfile # noqa: E402
+
+import pytest # noqa: E402
+import torch # noqa: E402
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_pp_native_gloo import LLAMA, _free_port, _torch_pipelining_error, batch, build, ppn # noqa: E402
+
+RECIPES = ("pp_unscale", "scaler_unscale", "scaler_step_only")
+
+
+def _one_step(rank, world, recipe, inf_rank):
+ from torch.distributed.device_mesh import init_device_mesh
+
+ model = build(LLAMA)
+ ids, labels = batch(model)
+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))
+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)
+ scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)
+ opt = torch.optim.SGD(pp.parameters(), lr = 1.0)
+ pp.step(ids, labels, scaler = scaler)
+ if rank == inf_rank:
+ pp.parameters()[0].grad.view(-1)[0] = float("inf")
+ before = [p.detach().clone() for p in pp.parameters()]
+ if recipe == "pp_unscale":
+ pp.unscale_(scaler, opt)
+ pp.clip_grad_norm_(1.0)
+ elif recipe == "scaler_unscale":
+ scaler.unscale_(opt)
+ pp.clip_grad_norm_(1.0)
+ scaler.step(opt)
+ scaler.update()
+ after = [p.detach().clone() for p in pp.parameters()]
+ try:
+ pickle.loads(pickle.dumps(scaler)) # torch.amp allows pickling a GradScaler after update()
+ picklable = "ok"
+ except Exception as exc:
+ picklable = f"{type(exc).__name__}: {exc}"
+ return {
+ "unchanged": all(torch.equal(a, b) for a, b in zip(before, after)),
+ "scale": float(scaler.get_scale()),
+ "picklable": picklable,
+ }
+
+
+def _clip_before_unscale(rank, world):
+ from torch.distributed.device_mesh import init_device_mesh
+
+ model = build(LLAMA)
+ ids, labels = batch(model)
+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))
+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)
+ scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)
+ opt = torch.optim.SGD(pp.parameters(), lr = 1.0)
+ out = {}
+ pp.step(ids, labels, scaler = scaler)
+ try:
+ pp.clip_grad_norm_(1.0)
+ out["scaled_clip"] = None
+ except ValueError as exc:
+ out["scaled_clip"] = str(exc)
+ pp.unscale_(scaler, opt)
+ out["unscaled_clip"] = float(pp.clip_grad_norm_(1.0))
+ scaler.step(opt)
+ scaler.update()
+ opt.zero_grad(set_to_none = True)
+ # A step without a scaler clips as before.
+ pp.step(ids, labels)
+ out["no_scaler_clip"] = float(pp.clip_grad_norm_(1.0))
+ return out
+
+
+def _clip_after_step(rank, world):
+ """Gradients are unscaled once scaler.step ran (it unscales first) and stay so after update():
+ a grad-norm read there (logging) is correct usage and must not be refused."""
+ from torch.distributed.device_mesh import init_device_mesh
+
+ model = build(LLAMA)
+ ids, labels = batch(model)
+ mesh = init_device_mesh("cpu", (world,), mesh_dim_names = ("pp",))
+ pp = ppn.apply_pipeline_parallel(model, mesh["pp"], n_microbatches = 2)
+ scaler = torch.amp.GradScaler("cpu", init_scale = 1024.0)
+ opt = torch.optim.SGD(pp.parameters(), lr = 1.0)
+ out = {}
+ pp.step(ids, labels, scaler = scaler)
+ for where, action in (
+ ("after_step", lambda: scaler.step(opt)),
+ ("after_update", scaler.update),
+ ):
+ action()
+ try:
+ out[where] = float(pp.clip_grad_norm_(1e9))
+ except ValueError as exc:
+ out[where] = str(exc)
+ return out
+
+
+def _worker(rank, world, port, tmp, case, kwargs):
+ os.environ.update(
+ MASTER_ADDR = "127.0.0.1",
+ MASTER_PORT = str(port),
+ RANK = str(rank),
+ WORLD_SIZE = str(world),
+ LOCAL_RANK = str(rank),
+ LOCAL_WORLD_SIZE = str(world),
+ )
+ import datetime
+
+ import torch.distributed as dist
+
+ torch.set_num_threads(2)
+ dist.init_process_group(
+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 180)
+ )
+ try:
+ fn = {"step": _one_step, "clip": _clip_before_unscale, "clip_after": _clip_after_step}[case]
+ res = fn(rank, world, **kwargs)
+ torch.save(res, os.path.join(tmp, f"result_{rank}.pt"))
+ finally:
+ dist.destroy_process_group()
+
+
+def _spawn(
+ case,
+ world = 2,
+ **kwargs,
+):
+ if _torch_pipelining_error():
+ pytest.skip(_torch_pipelining_error())
+ ctx = multiprocessing.get_context("spawn")
+ port = _free_port()
+ with tempfile.TemporaryDirectory() as tmp:
+ procs = [
+ ctx.Process(target = _worker, args = (r, world, port, tmp, case, kwargs))
+ for r in range(world)
+ ]
+ for p in procs:
+ p.start()
+ for p in procs:
+ p.join(600)
+ codes = [p.exitcode for p in procs]
+ assert codes == [0] * world, f"rank exit codes {codes}"
+ return [
+ torch.load(os.path.join(tmp, f"result_{r}.pt"), weights_only = False)
+ for r in range(world)
+ ]
+
+
[email protected]("recipe", RECIPES)
[email protected]("inf_rank", [0, 1])
+def test_pp2_inf_on_one_stage_skips_every_stage(recipe, inf_rank):
+ results = _spawn("step", recipe = recipe, inf_rank = inf_rank)
+ assert [r["unchanged"] for r in results] == [True, True], (recipe, inf_rank, results)
+ assert [r["scale"] for r in results] == [512.0, 512.0], (recipe, inf_rank, results)
+
+
[email protected]("recipe", RECIPES)
+def test_pp2_finite_step_updates_every_stage(recipe):
+ results = _spawn("step", recipe = recipe, inf_rank = -1)
+ assert [r["unchanged"] for r in results] == [False, False], (recipe, results)
+ assert [r["scale"] for r in results] == [1024.0, 1024.0], (recipe, results)
+
+
+def test_pp2_clip_before_unscale_is_refused():
+ for r in _spawn("clip"):
+ assert r["scaled_clip"] is not None and "unscale_" in r["scaled_clip"], r
+ assert r["unscaled_clip"] > 0 and r["no_scaler_clip"] > 0, r
+
+
+def test_pp2_scaler_still_pickles_after_update():
+ """pp.step(scaler = ...) must not leave the scaler unpicklable (torch.save(scaler) after scaler.update())."""
+ results = _spawn("step", recipe = "scaler_step_only", inf_rank = -1)
+ assert [r["picklable"] for r in results] == ["ok", "ok"], results
+
+
+def test_pp2_clip_after_scaler_step_is_allowed():
+ for r in _spawn("clip_after"):
+ assert all(isinstance(v, float) and v > 0 for v in r.values()), r
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index dc4f8226615..6a688124c0c 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -637,6 +637,7 @@ def _install_accelerator_state(self):
_install_fsdp2_parallelism_config(accelerator.state, manager)
else:
_restore_parallelism_config(accelerator.state)
+ _cp_scaler_start(self, accelerator)
# PEFT makes the Trainer ask DDP for find_unused_parameters, which breaks reentrant checkpointing.
if getattr(self.args, "ddp_find_unused_parameters", None) in (None, False):
self.args.ddp_find_unused_parameters = False
@@ -645,6 +646,31 @@ def _install_accelerator_state(self):
handler.find_unused_parameters = False
+def _cp_scaler_start(trainer, accelerator) -> None:
+ """float16: start the GradScaler at 2**16 / world, as native FSDP2 and tensor parallel do.
+ CP rank grads are world x one GPU's (loss is multiplied by world). Only touches a scaler still at the default."""
+ scaler = getattr(accelerator, "scaler", None)
+ if scaler is None or getattr(scaler, "_unsloth_cp_init_scale", False):
+ return
+ try:
+ if not scaler.is_enabled() or getattr(scaler, "_scale", None) is not None:
+ return
+ if float(getattr(scaler, "_init_scale", 0.0)) != 2.0**16:
+ return
+ handler = getattr(accelerator, "scaler_handler", None)
+ user = handler.to_kwargs() if handler is not None and hasattr(handler, "to_kwargs") else {}
+ if "init_scale" in user:
+ return
+ from .models.fsdp2_native import _loss_scale_ranks
+
+ world = _loss_scale_ranks(trainer)
+ except Exception:
+ return
+ if world > 1:
+ scaler._init_scale = 2.0**16 / world
+ scaler._unsloth_cp_init_scale = True
+
+
def _model_parallel_axes(model) -> list:
"""Tensor / pipeline parallel axes in use: UNSLOTH_TP_SIZE or a model split by hand."""
import os
diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py
index bd789c8ec44..fab1bd63f1a 100644
--- a/unsloth/models/float8_training.py
+++ b/unsloth/models/float8_training.py
@@ -147,8 +147,13 @@ def _probe_dtype_pairs(recipe):
return pairs
-def _probe_float8_gemm(device, recipe):
- """Tiny torch._scaled_mm calls with each GEMM's own fp8 dtypes and scaling, so an unsupported GPU / torch refuses here, not mid-training."""
+def _probe_float8_gemm(
+ device,
+ recipe,
+ dtype = torch.bfloat16,
+):
+ """Tiny torch._scaled_mm calls with each GEMM's own fp8 dtypes and scaling, so an unsupported GPU / torch refuses here, not mid-training.
+ Rowwise always writes bfloat16 (torchao computes it in bfloat16 and casts)."""
M, K, N = 16, 32, 16
for (dtype_a, rowwise_a), (dtype_b, rowwise_b) in _probe_gemms(recipe):
a = torch.ones(M, K, device = device).to(dtype_a)
@@ -158,7 +163,22 @@ def _probe_float8_gemm(device, recipe):
rowwise = rowwise_a or rowwise_b
sa = torch.ones(M, 1, device = device) if rowwise else torch.ones((), device = device)
sb = torch.ones(1, N, device = device) if rowwise else torch.ones((), device = device)
- torch._scaled_mm(a, b, scale_a = sa, scale_b = sb, out_dtype = torch.bfloat16)
+ out_dtype = (
+ torch.bfloat16 if rowwise or dtype not in (torch.float16, torch.float32) else dtype
+ )
+ torch._scaled_mm(a, b, scale_a = sa, scale_b = sb, out_dtype = out_dtype)
+
+
+def _float8_compute_dtype(model, module_filter_fn):
+ """float16 when the converted layers will run in float16 (a float16 load, or one Unsloth upcast to float32
+ masters for float16 mixed precision), else bfloat16."""
+ if getattr(model, "_unsloth_original_dtype", None) == torch.float16:
+ return torch.float16
+ for name, module in model.named_modules():
+ if isinstance(module, torch.nn.Linear) and module_filter_fn(module, name):
+ if module.weight.dtype == torch.float16:
+ return torch.float16
+ return torch.bfloat16
def _recipe_scaling(recipe):
@@ -186,7 +206,11 @@ def _selected_devices(model, module_filter_fn):
return devices
-def _check_hardware(device, recipe):
+def _check_hardware(
+ device,
+ recipe,
+ dtype = torch.bfloat16,
+):
if device is None or device.type != "cuda" or not torch.cuda.is_available():
raise RuntimeError(
"Unsloth: float8_training needs the model on an NVIDIA GPU with compute capability 8.9+; "
@@ -221,12 +245,17 @@ def _check_hardware(device, recipe):
"(compute capability 12.x). To try it here, pass "
f"torchao.float8.Float8LinearConfig.from_recipe_name({recipe!r}) as float8_training."
)
- probe_recipe = _recipe_scaling(recipe)
+ probe_recipe = f"{_recipe_scaling(recipe)} scaling"
try:
- _probe_float8_gemm(device, recipe)
+ if dtype == torch.float16:
+ # The float16 output GEMM is a different cuBLAS / CUTLASS path from the bfloat16 one.
+ probe_recipe += ", float16 output"
+ _probe_float8_gemm(device, recipe, torch.float16)
+ else:
+ _probe_float8_gemm(device, recipe)
except Exception as e:
raise RuntimeError(
- f"Unsloth: float8_training ({probe_recipe} scaling) is not supported by torch {torch.__version__} on "
+ f"Unsloth: float8_training ({probe_recipe}) is not supported by torch {torch.__version__} on "
f"{torch.cuda.get_device_name(device)} ({type(e).__name__}: {str(e)[:200]})."
) from e
@@ -285,8 +314,9 @@ def convert_model_to_float8_training(
module_filter_fn = float8_training_filter(model, recipe, size_filter = size_filter)
if check_hardware and not getattr(config, "emulate", False):
devices = _selected_devices(model, module_filter_fn)
+ dtype = _float8_compute_dtype(model, module_filter_fn)
for device in devices or [next((p.device for p in model.parameters()), None)]:
- _check_hardware(device, recipe)
+ _check_hardware(device, recipe, dtype)
# torchao's new Float8Linear drops Accelerate dispatch hooks (device_map / offload); re-attach them.
dispatch_hooks = {
name: m._hf_hook
diff --git a/unsloth/models/pp_native.py b/unsloth/models/pp_native.py
index 85c5cc81a4f..f7a91da3ef6 100644
--- a/unsloth/models/pp_native.py
+++ b/unsloth/models/pp_native.py
@@ -897,6 +897,9 @@ class PipelineParallel:
self._global_ranks = [dist.get_global_rank(self.group, i) for i in range(self.num_stages)]
self._shapes = collections.OrderedDict()
self._scaler = None
+ self._step_scaler = (
+ None # the enabled GradScaler of the last step (clip_grad_norm_ checks it)
+ )
self._mb_losses = []
self._loss_multiplier = 1
self.dp_mesh = None # set by shard_model (FSDP2 over the data parallel dimension)
@@ -1121,6 +1124,8 @@ class PipelineParallel:
torch.zeros((), device = device)
) # every stage's scaler holds the scale (unscale_)
self._scaler = scaler
+ self._bind_scaler(scaler)
+ self._step_scaler = scaler if scaler is not None and scaler.is_enabled() else None
self._mb_losses = []
args = (input_ids.to(device),) if self.is_first else ()
target = step_kwargs["labels"] if self.is_last else None
@@ -1202,6 +1207,7 @@ class PipelineParallel:
divided by the ranks holding a copy of it, summed over every rank)."""
import torch.distributed as dist
+ self._check_unscaled()
params = self.parameters() if parameters is None else list(parameters)
params = [p for p in params if p.grad is not None]
device = self.device
@@ -1227,11 +1233,69 @@ class PipelineParallel:
def unscale_(self, scaler, optimizer):
"""scaler.unscale_(optimizer), then found_inf is the MAX over every stage, so all stages skip the
same steps (scaler.step / scaler.update after this)."""
- import torch.distributed as dist
-
scaler.unscale_(optimizer)
if not scaler.is_enabled():
return
+ self._agree_found_inf(scaler, optimizer)
+
+ def _bind_scaler(self, scaler):
+ """Make scaler.unscale_ / scaler.step agree found_inf over every stage, or one stage steps while another skips.
+ Bound until scaler.update(), so the scaler pickles again where torch.amp allows it and holds no pipeline."""
+ import weakref
+
+ bound = scaler.__dict__.get("_unsloth_pp_agree")
+ if bound is not None and bound() is self:
+ return
+ cls = type(scaler)
+ unscale = cls.unscale_.__get__(scaler)
+ update = cls.update.__get__(scaler)
+ pipeline = weakref.ref(self)
+
+ def unscale_(optimizer):
+ unscale(optimizer)
+ pp = pipeline()
+ if pp is not None and scaler.is_enabled():
+ pp._agree_found_inf(scaler, optimizer)
+
+ def update_(new_scale = None):
+ try:
+ return update(new_scale)
+ finally:
+ for name in ("unscale_", "update", "_unsloth_pp_agree"):
+ scaler.__dict__.pop(name, None)
+ pp = pipeline()
+ if pp is not None and pp._step_scaler is scaler:
+ pp._step_scaler = (
+ None # this step's gradients were unscaled (update follows step)
+ )
+
+ scaler.unscale_ = unscale_
+ scaler.update = update_
+ scaler._unsloth_pp_agree = pipeline
+
+ def _check_unscaled(self):
+ """clip_grad_norm_ on gradients still multiplied by the loss scale clips the wrong norm."""
+ scaler = self._step_scaler
+ if scaler is None or not scaler.is_enabled():
+ return
+ try:
+ from torch.amp.grad_scaler import OptState
+ except ImportError:
+ return
+ states = getattr(scaler, "_per_optimizer_states", {}) or {}
+ if any(
+ state.get("stage") in (OptState.UNSCALED, OptState.STEPPED) for state in states.values()
+ ):
+ return # scaler.step unscales first: STEPPED gradients are unscaled too
+ raise ValueError(
+ "Unsloth: PipelineParallel.clip_grad_norm_ got gradients still multiplied by the float16 "
+ "loss scale. Call scaler.unscale_(optimizer) (or pp.unscale_(scaler, optimizer)) first, as "
+ "torch.amp requires before clipping."
+ )
+
+ def _agree_found_inf(self, scaler, optimizer):
+ import torch.distributed as dist
+
state = scaler._per_optimizer_states[id(optimizer)]
found = state["found_inf_per_device"]
device = self.device