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.

checkpoint_skip_layers="auto": skip the planning collective under DDP.join() (#15779)

Daniel Hana14f61adf374
diff --git a/tests/test_gc_skip_auto_dist_cells.py b/tests/test_gc_skip_auto_dist_cells.py
index 89fbfe50d25..b4bd7941122 100644
--- a/tests/test_gc_skip_auto_dist_cells.py
+++ b/tests/test_gc_skip_auto_dist_cells.py
@@ -172,6 +172,43 @@ def _ddp_scenario(rank, scenario, usable):
}
+def _join_scenario(rank, scenario, usable):
+ """DDP.join(): rank 0 runs out of inputs before rank 1's planning forward."""
+ from torch.nn.parallel import DistributedDataParallel as DDP
+
+ T, ns = _load()
+ memory = {"allocated": 0}
+ model = T._model(layers = 4)
+ if scenario:
+ _spoof_cuda(ns, usable, memory)
+ for layer in model.model.layers:
+ layer.register_forward_hook(
+ lambda m, a, o: memory.__setitem__(
+ "allocated", memory["allocated"] + (GIB // 16 if torch.is_grad_enabled() else 0)
+ )
+ )
+ ns["skip_checkpointing"](model, "auto")
+ planner = getattr(model, "_unsloth_auto_skip", None)
+ ddp = DDP(model)
+ optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
+ generator = torch.Generator().manual_seed(100)
+ batches = [torch.randint(0, 128, (2, 32), generator = generator) for _ in range(3)]
+ losses = []
+ with ddp.join():
+ for ids in batches[: 1 if rank == 0 else 3]:
+ loss = ddp(input_ids = ids, labels = ids).loss
+ loss.backward()
+ optimizer.step()
+ optimizer.zero_grad(set_to_none = True)
+ losses.append(float(loss.detach()))
+ digest = float(sum(p.detach().double().sum() for p in model.parameters()))
+ return {
+ "kept": None if planner is None else list(planner.kept or []),
+ "losses": losses,
+ "digest": digest,
+ }
+
+
class _null:
def __enter__(self):
return self
@@ -193,7 +230,7 @@ def _worker(rank, world, port, kind, scenario, usable, queue):
world_size = world,
timeout = datetime.timedelta(seconds = 30),
)
- run = _fake_scenario if kind == "fake" else _ddp_scenario
+ run = {"fake": _fake_scenario, "join": _join_scenario}.get(kind, _ddp_scenario)
queue.put((rank, run(rank, scenario, usable[rank]), None))
except Exception:
import traceback
@@ -333,3 +370,13 @@ def test_fsdp2_training_unchanged_and_ranks_agree(accumulation):
for rank in (0, 1):
assert reference[rank]["checkpointed"] == [True] * 4
_assert_same_training(auto[rank], reference[rank])
+
+
+def test_ddp_join_with_uneven_inputs_keeps_every_layer_checkpointed():
+ # A joined rank only shadows DDP's collectives, so a planning all_reduce would mispair.
+ usable = [8 * GIB, 8 * GIB]
+ auto = _launch("join", True, usable)
+ reference = _launch("join", False, usable)
+ for rank in (0, 1):
+ assert auto[rank]["kept"] == []
+ _assert_same_training(auto[rank], reference[rank])
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 67ae27ac0c8..82dfedb5db6 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -10549,6 +10549,18 @@ class _AutoCheckpointSkip:
'Unsloth: checkpoint_skip_layers = "auto" under torchrun needs the process group before the second step; every layer stays checkpointed.'
)
return 0
+ try:
+ # Every rank enters DDP.join() (also accelerate join_uneven_inputs), so all take this branch.
+ from torch.nn.parallel import DistributedDataParallel
+ ddp = DistributedDataParallel._get_active_ddp_module()
+ joined = ddp is not None and ddp._join_config.enable
+ except Exception:
+ joined = False
+ if joined:
+ print(
+ 'Unsloth: checkpoint_skip_layers = "auto" does not plan under DDP.join() (uneven inputs); every layer stays checkpointed.'
+ )
+ return 0
backend = str(dist.get_backend())
on = device if "nccl" in backend and device is not None else torch.device("cpu")
agreed = torch.tensor([int(count)], dtype = torch.int64, device = on)