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.

Context parallel: Ulysses for Kimi-Linear (KDA + MLA), and fix Kimi-Linear MoE gate backward (#15880)

Immanuel Sunb61e6ee37a18
diff --git a/tests/test_context_parallel.py b/tests/test_context_parallel.py
index 191cc5ee461..3e2d7968619 100644
--- a/tests/test_context_parallel.py
+++ b/tests/test_context_parallel.py
@@ -159,6 +159,69 @@ def test_training_step_divides_the_pre_shard_token_count_by_cp_size(monkeypatch)
assert seen[-1][1].dtype == torch.int64
+def test_training_step_installs_the_idle_expert_hook_once(monkeypatch):
+ # Under CP every-expert MoE blocks get the optimizer pre-hook that drops globally idle experts'
+ # zero gradients; through accelerate's wrapper, once, and not for a model without such blocks.
+ monkeypatch.setattr(cp, "context_parallel", _fake_context_parallel([]))
+
+ class Experts(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.experts = torch.nn.ModuleList(torch.nn.Linear(2, 2) for _ in range(3))
+
+ def forward(self, x):
+ return x
+
+ Experts.forward._unsloth_remote_moe_shim = True
+
+ class Wrapped: # accelerate's AcceleratedOptimizer steps the optimizer it wraps
+ def __init__(self, optimizer):
+ self.optimizer = optimizer
+
+ class Trainer:
+ def __init__(self):
+ pass
+
+ def training_step(
+ self,
+ model,
+ inputs,
+ num_items_in_batch = None,
+ ):
+ pass
+
+ def prediction_step(self, model, inputs, prediction_loss_only):
+ return (None, None, None)
+
+ def train(self):
+ pass
+
+ def evaluate(self):
+ pass
+
+ def evaluation_loop(self, *a, **k):
+ pass
+
+ import trl
+
+ monkeypatch.setattr(trl, "SFTTrainer", Trainer)
+ cp.patch_sft_trainer(install_cp_methods = True)
+ trainer = Trainer()
+ trainer.model = torch.nn.Sequential(Experts())
+ inner = torch.optim.AdamW(trainer.model.parameters())
+ trainer.optimizer = Wrapped(inner)
+ manager = _manager(size = 2)
+ manager.mesh = None
+ trainer._context_parallel_manager = manager
+ for _ in range(2):
+ trainer.training_step(None, {"input_ids": torch.ones(1, 4, dtype = torch.long)}, 4)
+ assert len(inner._optimizer_step_pre_hooks) == 1
+ plain = torch.optim.AdamW(torch.nn.Linear(2, 2).parameters())
+ trainer.model, trainer.optimizer = torch.nn.Linear(2, 2), plain
+ trainer.training_step(None, {"input_ids": torch.ones(1, 4, dtype = torch.long)}, 4)
+ assert not plain._optimizer_step_pre_hooks
+
+
def test_shift_labels_is_not_an_eval_label_name():
# A named shift_labels made find_labels treat it as a required eval label.
from transformers.utils import find_labels
diff --git a/tests/test_context_parallel_rl.py b/tests/test_context_parallel_rl.py
index 063e0d56b7f..4b688fe6cca 100644
--- a/tests/test_context_parallel_rl.py
+++ b/tests/test_context_parallel_rl.py
@@ -253,7 +253,7 @@ def _fake_trainer_class(log):
@pytest.mark.parametrize("kind", ["dpo_trainer", "grpo_trainer"])
def test_rl_scopes_keep_generation_unsharded(monkeypatch, kind):
log = []
- manager = types.SimpleNamespace(size = 2, backend = "ulysses")
+ manager = types.SimpleNamespace(size = 2, backend = "ulysses", _clear_real_tokens = lambda: None)
monkeypatch.setattr(cp, "_check_cp_runtime", lambda *a: None)
monkeypatch.setattr(cp, "_check_cp_trainer", lambda *a: None)
monkeypatch.setattr(cp, "_install_accelerator_state", lambda *a: None)
@@ -586,7 +586,7 @@ def _cp_fake_trainer(
log,
installs = None,
):
- manager = types.SimpleNamespace(size = 2, backend = "ulysses")
+ manager = types.SimpleNamespace(size = 2, backend = "ulysses", _clear_real_tokens = lambda: None)
monkeypatch.setattr(cp, "_check_cp_runtime", lambda *a: None)
monkeypatch.setattr(cp, "_check_cp_trainer", lambda *a: None)
monkeypatch.setattr(
diff --git a/tests/test_parallel_capabilities_evidence.py b/tests/test_parallel_capabilities_evidence.py
index d81d0cfcb0a..a4da1ca491e 100644
--- a/tests/test_parallel_capabilities_evidence.py
+++ b/tests/test_parallel_capabilities_evidence.py
@@ -222,6 +222,39 @@ def test_unsloth_checkpoint_is_seen_and_covered_by_the_cells_that_measured_it(mo
caps.check(query)
+ "mode, expert_lora",
+ [("full", False), ("lora", False), ("lora", True)],
+ ids = ["full", "lora", "lora+experts"],
+)
+def test_kimi_linear_moe_under_cp_follows_its_gloo_evidence(mode, expert_lora):
+ # tests/test_ulysses_kimi.py::test_kimi_moe_under_ulysses_matches_one_process: sdpa / eager, none / HF
+ # checkpointing, cp 2 and dp 2 x cp 2. Unsloth's checkpoint, FSDP2 x cp and the router loss stay refused.
+ kw = dict(
+ trainer = "sft",
+ family = "kimi_linear",
+ moe = True,
+ mode = mode,
+ expert_lora = expert_lora,
+ cp = 2,
+ cp_backend = "ulysses",
+ torch = (2, 13),
+ )
+ for extra in ({}, {"memory": "gc"}, {"attention": "eager"}, {"dp": 2}):
+ query = caps.Query(**kw, **extra)
+ status, cell = caps.cell_status(query)
+ assert status == "supported" and "test_kimi_moe_under_ulysses" in cell.parity, (extra, cell)
+ caps.check(query)
+ for extra, match in (
+ ({"memory": "unsloth_offload"}, "Unsloth checkpoint"),
+ ({"fsdp2": True}, "fsdp2_cp"),
+ ({"router_aux_loss": True}, "router auxiliary loss"),
+ ({"compile": "block"}, "no numeric parity"),
+ ):
+ with pytest.raises(NotImplementedError, match = match):
+ caps.check(caps.Query(**kw, **extra))
+
+
def test_unsloth_checkpoint_keeps_an_unverified_moe_row_refused_under_strict(
clean_env, monkeypatch
):
diff --git a/tests/test_parallel_env.py b/tests/test_parallel_env.py
index 5a04d9b2b11..83b5f156394 100644
--- a/tests/test_parallel_env.py
+++ b/tests/test_parallel_env.py
@@ -873,7 +873,8 @@ def test_moe_rows_cover_family_precision_aux_and_mode():
moe = [
c
for c in caps.CELLS
- if c.name.startswith("MoE ") and not c.name.endswith(", block compile")
+ if c.name.startswith("MoE ")
+ and not c.name.endswith((", block compile", ", Unsloth checkpoint"))
]
assert len(moe) == len(caps.MOE_FAMILIES) * 4 * 2 * 6
proven = sorted(c.name for c in moe if not c.missing())
diff --git a/tests/test_remote_moe_shims.py b/tests/test_remote_moe_shims.py
index 1c3b6d824a8..82447c2d2d3 100644
--- a/tests/test_remote_moe_shims.py
+++ b/tests/test_remote_moe_shims.py
@@ -47,6 +47,10 @@ import torch.nn.functional as F
from torch import nn
class Cfg:
+ # A PretrainedConfig in the hub code: PEFT 0.18 reads model.config.to_dict().
+ def to_dict(self):
+ return dict(vars(self))
+
def __init__(self):
self.hidden_size = 16; self.n_routed_experts = 8; self.num_experts_per_tok = 2
self.moe_intermediate_size = 8; self.n_shared_experts = 1; self.routed_scaling_factor = 2.5
@@ -132,7 +136,8 @@ class DeepseekV3MoE(nn.Module):
linecache.cache[filename] = (len(src), None, src.splitlines(True), filename)
exec(compile(src, filename, "exec"), mod.__dict__)
sys.modules[name] = mod
- for cls in (mod.MoEGate, getattr(mod, "DeepseekV3MoE", None) or mod.SarvamMLAMoE, mod.MLP):
+ gate_cls = getattr(mod, "MoEGate", None) or mod.KimiMoEGate
+ for cls in (gate_cls, getattr(mod, "DeepseekV3MoE", None) or mod.SarvamMLAMoE, mod.MLP):
cls.__module__ = name
return mod
@@ -192,6 +197,34 @@ def test_training_forward_matches_eval_and_backpropagates():
assert block.gate.training and block.training
+def test_a_gate_adding_its_bias_in_place_still_backpropagates():
+ """Kimi-Linear's gate (renamed KimiMoEGate) adds e_score_correction_bias in place to the sigmoid
+ output that the sigmoid's backward saved; training through the shim must not trip autograd's
+ version check."""
+ inplace = (
+ ("class MoEGate(nn.Module):", "class KimiMoEGate(nn.Module):"),
+ ("self.gate = MoEGate(config)", "self.gate = KimiMoEGate(config)"),
+ (
+ "scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)",
+ "scores_for_choice = scores.view(bsz * seq_len, -1)\n"
+ " scores_for_choice += self.e_score_correction_bias.unsqueeze(0)",
+ ),
+ )
+ grads = []
+ for name, edits in (("tiny_kimi_c", ()), ("tiny_kimi_inplace", inplace)):
+ mod = _remote_module(f"transformers_modules.{name}.modeling_deepseek", edits)
+ torch.manual_seed(0)
+ block = mod.DeepseekV3MoE(mod.Cfg())
+ assert len(prepare_remote_moe_for_training(block, verbose = False)) == 2
+ block.train()
+ x = torch.randn(2, 5, 16, requires_grad = True)
+ block(x).float().pow(2).sum().backward()
+ grads.append((x.grad, block.gate.weight.grad))
+ # The bias is zero, so the in-place port routes and weighs exactly like the reference one.
+ for got, expected in zip(grads[1], grads[0]):
+ torch.testing.assert_close(got, expected)
+
+
def test_shims_reach_a_module_behind_an_accelerate_hook():
"""A device_map load wraps forward with an accelerate hook that keeps the original as
`_old_forward`; the class-level shim alone is never called from `module(...)`. Kimi-K2.7-Code
@@ -597,7 +630,11 @@ def test_a_latent_moe_trains_through_its_own_projections():
block.train()
with pytest.raises((AssertionError, NotImplementedError)):
block(x)
- assert prepare_remote_moe_for_training(block, verbose = False) == ["KimiSparseMoeBlock"]
+ # The renamed gate is shimmed through its inference-only block (in-place-safe backward).
+ assert sorted(prepare_remote_moe_for_training(block, verbose = False)) == [
+ "KimiMoEGate",
+ "KimiSparseMoeBlock",
+ ]
block.eval()
with torch.no_grad():
reference = block(x)
@@ -621,3 +658,671 @@ def test_a_latent_moe_trains_through_its_own_projections():
block.eval()
with torch.no_grad():
assert torch.allclose(block(x), reference)
+
+
+_KIMI_INPLACE = (
+ ("class MoEGate(nn.Module):", "class KimiMoEGate(nn.Module):"),
+ ("self.gate = MoEGate(config)", "self.gate = KimiMoEGate(config)"),
+ (
+ "scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)",
+ "scores_for_choice = scores.view(bsz * seq_len, -1)\n"
+ " scores_for_choice += self.e_score_correction_bias.unsqueeze(0)",
+ ),
+)
+# The same gate written out of place. The in-place add goes through a view, so Kimi's `scores`
+# (later gathered into the routing weights) carries the bias too: keep that.
+_KIMI_OUT_OF_PLACE = _KIMI_INPLACE[:2] + (
+ (
+ "scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)",
+ "scores = scores + self.e_score_correction_bias.unsqueeze(0)\n"
+ " scores_for_choice = scores.view(bsz * seq_len, -1)",
+ ),
+ ("torch.float32", "torch.float64"),
+)
+
+
+def _kimi_gate_block(name, edits, scoring, dtype):
+ if scoring == "softmax":
+ edits = edits + (("scores = logits.sigmoid()", "scores = logits.softmax(dim=-1)"),)
+ mod = _remote_module(f"transformers_modules.{name}.modeling_deepseek", edits)
+ torch.manual_seed(0)
+ block = mod.DeepseekV3MoE(mod.Cfg())
+ with torch.no_grad():
+ block.gate.e_score_correction_bias.normal_(0, 0.3) # nonzero: Kimi's real bias
+ assert sorted(prepare_remote_moe_for_training(block, verbose = False)) == [
+ "DeepseekV3MoE",
+ "KimiMoEGate",
+ ]
+ return block.to(dtype).train()
+
+
+def _checkpointed(block, x, mode):
+ from torch.utils.checkpoint import checkpoint
+
+ if mode == "none":
+ return block(x)
+ if mode == "reentrant":
+ return checkpoint(block, x, use_reentrant = True)
+ if mode == "non_reentrant":
+ return checkpoint(block, x, use_reentrant = False)
+ # How vision.py runs non-reentrant checkpointing under DDP: inside the zoo offload hooks.
+ from unsloth_zoo.gradient_checkpointing import non_reentrant_offload_hooks
+
+ with non_reentrant_offload_hooks():
+ return checkpoint(block, x, use_reentrant = False)
+
+
[email protected]("scoring", ["sigmoid", "softmax"])
[email protected]("mode", ["none", "reentrant", "non_reentrant", "non_reentrant_offload"])
+def test_an_in_place_kimi_gate_matches_an_out_of_place_oracle(mode, scoring):
+ """Kimi-Linear adds its (nonzero) score bias in place to the sigmoid / softmax output that op's
+ backward saved. Without a copy, plain and reentrant backward raise autograd's version error and
+ non-reentrant checkpointing silently differentiates the biased scores."""
+ if mode == "non_reentrant_offload":
+ pytest.importorskip("unsloth_zoo.gradient_checkpointing").non_reentrant_offload_hooks
+ x = torch.randn(3, 7, 16, dtype = torch.float64, generator = torch.Generator().manual_seed(1))
+ oracle = _kimi_gate_block(f"kimi_oop_{scoring}", _KIMI_OUT_OF_PLACE, scoring, torch.float64)
+ x_oracle = x.clone().requires_grad_()
+ expected = oracle(x_oracle)
+ expected.pow(2).sum().backward()
+
+ block = _kimi_gate_block(
+ f"kimi_inplace_{mode}_{scoring}", _KIMI_INPLACE, scoring, torch.float32
+ )
+ x_block = x.float().requires_grad_()
+ out = _checkpointed(block, x_block, mode)
+ out.pow(2).sum().backward()
+ torch.testing.assert_close(out.double(), expected, rtol = 1e-5, atol = 1e-6)
+ torch.testing.assert_close(x_block.grad.double(), x_oracle.grad, rtol = 1e-4, atol = 1e-6)
+ for (name, got), want in zip(block.named_parameters(), oracle.parameters()):
+ assert (got.grad is None) == (want.grad is None), name
+ if got.grad is not None:
+ torch.testing.assert_close(
+ got.grad.double(), want.grad, rtol = 1e-4, atol = 1e-6, msg = lambda m: f"{name}: {m}"
+ )
+
+
+def test_the_gate_leaves_its_saved_tensors_to_checkpointing():
+ """Inside non-reentrant checkpointing (Unsloth's DDP / context parallel default) every saved
+ tensor belongs to the checkpoint, which drops it until backward. saved_tensors_hooks pushed
+ inside the gate would win over the checkpoint's and keep the gate's saved tensors (its fp32
+ input copy, scores, weights) alive through the whole forward."""
+ import gc
+ import weakref
+
+ from torch.utils._python_dispatch import TorchDispatchMode
+ from torch.utils.checkpoint import checkpoint
+
+ class Created(TorchDispatchMode):
+ def __init__(self):
+ super().__init__()
+ self.refs = []
+
+ def __torch_dispatch__(
+ self,
+ func,
+ types,
+ args = (),
+ kwargs = None,
+ ):
+ out = func(*args, **(kwargs or {}))
+ for t in out if isinstance(out, (tuple, list)) else (out,):
+ if isinstance(t, torch.Tensor):
+ self.refs.append(weakref.ref(t))
+ return out
+
+ block = _kimi_gate_block("kimi_resident", _KIMI_INPLACE, "sigmoid", torch.float32)
+ x = torch.randn(2, 64, 16, requires_grad = True)
+ with Created() as created:
+ out = checkpoint(block, x, use_reentrant = False)
+ gc.collect()
+ keep = {t.untyped_storage().data_ptr() for t in (out, x, *block.parameters())}
+ resident = {
+ t.untyped_storage().data_ptr(): t.untyped_storage().nbytes()
+ for t in (r() for r in created.refs)
+ if t is not None and t.untyped_storage().data_ptr() not in keep
+ }
+ assert sum(resident.values()) == 0, resident
+ out.pow(2).sum().backward()
+ assert x.grad is not None and block.gate.weight.grad is not None
+
+
+def test_a_non_remote_gate_is_not_patched():
+ mod = _remote_module("transformers_modules.kimi_local_gate.modeling_deepseek", _KIMI_INPLACE)
+ mod.KimiMoEGate.__module__ = "my_project.modeling" # a local class an inference-only port uses
+ original = mod.KimiMoEGate.forward
+ block = mod.DeepseekV3MoE(mod.Cfg())
+ assert prepare_remote_moe_for_training(block, verbose = False) == ["DeepseekV3MoE"]
+ assert mod.KimiMoEGate.forward is original
+ assert prepare_remote_moe_for_training(block, verbose = False) == []
+
+
+def _moe_ddp_entry(rank, world, init_file, fn, args):
+ import datetime
+
+ import torch.distributed as dist
+
+ torch.set_num_threads(1)
+ dist.init_process_group(
+ "gloo",
+ init_method = f"file://{init_file}",
+ rank = rank,
+ world_size = world,
+ timeout = datetime.timedelta(seconds = 60),
+ )
+ try:
+ fn(rank, world, *args)
+ finally:
+ dist.destroy_process_group()
+
+
+def _moe_spawn(fn, world, *args):
+ import torch.multiprocessing as mp
+ if "fork" not in mp.get_all_start_methods():
+ pytest.skip("needs the fork start method")
+ with tempfile.TemporaryDirectory() as d:
+ mp.start_processes(
+ _moe_ddp_entry,
+ args = (world, os.path.join(d, "init"), fn, args),
+ nprocs = world,
+ join = True,
+ start_method = "fork",
+ )
+
+
+def _routed_tokens(experts, seed):
+ # The gate below scores expert e by feature e, so these tokens pick exactly `experts`.
+ x = 0.1 * torch.randn(1, 6, 16, generator = torch.Generator().manual_seed(seed))
+ for boost, expert in zip((5.0, 4.0), experts):
+ x[..., expert] += boost
+ return x
+
+
+def _complementary_block(lora):
+ mod = _remote_module("transformers_modules.kimi_ddp.modeling_deepseek", _KIMI_INPLACE)
+ torch.manual_seed(0)
+ block = mod.DeepseekV3MoE(mod.Cfg())
+ with torch.no_grad():
+ block.gate.weight.copy_(torch.eye(8, 16))
+ prepare_remote_moe_for_training(block, verbose = False)
+ if lora:
+ from peft import LoraConfig, inject_adapter_in_model
+
+ config = LoraConfig(r = 2, target_modules = r".*experts\.\d+\.(gate_proj|up_proj|down_proj)")
+ block = inject_adapter_in_model(config, block)
+ for name, param in block.named_parameters():
+ param.requires_grad_("lora_" in name)
+ if "lora_B" in name:
+ with torch.no_grad():
+ param.normal_(0, 0.1)
+ return block.train()
+
+
+# Per step, the experts each rank routes to: disjoint across ranks and changing every step, so
+# with the shard-local routing of context parallelism each rank leaves experts its peer trains.
+_ROUTES = (((0, 1), (2, 3)), ((2, 3), (4, 5)), ((6, 7), (0, 1)))
+
+
+def _moe_ddp_worker(rank, world, cp_active, lora):
+ import copy
+
+ import torch.distributed as dist
+ from torch.nn.parallel import DistributedDataParallel
+
+ from unsloth import context_parallel as cp
+
+ block = _complementary_block(lora)
+ reference = copy.deepcopy(block)
+ model = DistributedDataParallel(block, find_unused_parameters = False)
+ params = [p for p in block.parameters() if p.requires_grad]
+ optimizer = torch.optim.SGD(params, lr = 0.1)
+ ref_optimizer = torch.optim.SGD([p for p in reference.parameters() if p.requires_grad], lr = 0.1)
+ cp._ACTIVE_MANAGER = object() if cp_active else None
+ try:
+ for step, routes in enumerate(_ROUTES):
+ optimizer.zero_grad(set_to_none = True)
+ model(_routed_tokens(routes[rank], step * 10 + rank)).pow(2).sum().backward()
+ # DDP averages over ranks: the reference sees both ranks' tokens at half weight.
+ ref_optimizer.zero_grad(set_to_none = True)
+ for peer in range(world):
+ loss = reference(_routed_tokens(routes[peer], step * 10 + peer)).pow(2).sum()
+ (loss / world).backward()
+ used = {e for pair in routes for e in pair}
+ for (name, got), want in zip(block.named_parameters(), reference.parameters()):
+ if not got.requires_grad:
+ continue
+ expert = int(name.split(".")[1]) if name.startswith("experts.") else None
+ assert got.grad is not None, name # a zero gradient, never None, for DDP
+ if want.grad is None:
+ assert expert is not None and expert not in used, name
+ assert not got.grad.any(), name
+ else:
+ torch.testing.assert_close(got.grad, want.grad, msg = lambda m: f"{name}: {m}")
+ optimizer.step()
+ ref_optimizer.step()
+ for (name, got), want in zip(block.named_parameters(), reference.parameters()):
+ torch.testing.assert_close(got, want, msg = lambda m: f"{name} after 3 steps: {m}")
+ finally:
+ cp._ACTIVE_MANAGER = None
+
+
[email protected]("lora", [False, True], ids = ["full", "lora_experts"])
+def test_context_parallel_ranks_routing_disjoint_experts_train_under_ddp(lora):
+ """Under context parallelism each rank routes its own sequence shard, so an expert idle on one
+ rank trains on its peer. DDP with find_unused_parameters = False needs a gradient from every
+ rank: idle experts run on no tokens for a zero gradient, over several steps of shifting routes."""
+ _moe_spawn(_moe_ddp_worker, 2, True, lora)
+
+
+def test_without_context_parallelism_idle_experts_stall_ddp():
+ # Negative control: the CP-off dispatch leaves idle experts' gradients None, so DDP without
+ # find_unused_parameters never reduces that bucket (local gradients) and refuses the next step.
+ with pytest.raises(Exception, match = "not close|finished reduction|did not receive grad"):
+ _moe_spawn(_moe_ddp_worker, 2, False, False)
+
+
+# Per optimizer step, two gradient accumulation micro-batches, the experts each rank routes to.
+# Step 0: 6 and 7 idle everywhere; 4 and 5 used in the second micro-batch only. Step 1: 2 to 5
+# idle everywhere after training at step 0 (AdamW momentum and weight decay would move them).
+# Step 2: 4 to 7 idle everywhere.
+_GA_ROUTES = (
+ (((0, 1), (2, 3)), ((0, 1), (4, 5))),
+ (((6, 7), (0, 1)), ((0, 1), (6, 7))),
+ (((2, 3), (2, 3)), ((0, 1), (2, 3))),
+)
+
+
+def _moe_adamw_worker(rank, world, lora, hook):
+ import copy
+
+ from torch.nn.parallel import DistributedDataParallel
+
+ from unsloth import context_parallel as cp
+
+ block = _complementary_block(lora)
+ reference = copy.deepcopy(block)
+ model = DistributedDataParallel(block, find_unused_parameters = False)
+ adamw = dict(lr = 1e-2, weight_decay = 0.1)
+ optimizer = torch.optim.AdamW([p for p in block.parameters() if p.requires_grad], **adamw)
+ ref_optimizer = torch.optim.AdamW(
+ [p for p in reference.parameters() if p.requires_grad], **adamw
+ )
+ if hook:
+ assert cp.install_idle_expert_grad_hook(optimizer, model)
+ assert cp.install_idle_expert_grad_hook(optimizer, model) # once per optimizer
+ assert len(optimizer._optimizer_step_pre_hooks) == 1
+ cp._ACTIVE_MANAGER = object()
+ try:
+ for step, micro_routes in enumerate(_GA_ROUTES):
+ optimizer.zero_grad(set_to_none = True)
+ ref_optimizer.zero_grad(set_to_none = True)
+ for micro, routes in enumerate(micro_routes):
+ seed = step * 100 + micro * 10
+ loss = model(_routed_tokens(routes[rank], seed + rank)).pow(2).sum()
+ (loss / len(micro_routes)).backward()
+ cp._ACTIVE_MANAGER = None # the single-process reference
+ for peer in range(world):
+ loss = reference(_routed_tokens(routes[peer], seed + peer)).pow(2).sum()
+ (loss / (world * len(micro_routes))).backward()
+ cp._ACTIVE_MANAGER = object()
+ used = {e for routes in micro_routes for pair in routes for e in pair}
+ before = {n: p.detach().clone() for n, p in block.named_parameters()}
+ optimizer.step()
+ ref_optimizer.step()
+ for (name, got), want in zip(block.named_parameters(), reference.parameters()):
+ if not got.requires_grad:
+ continue
+ expert = int(name.split(".")[1]) if name.startswith("experts.") else None
+ if hook and expert is not None:
+ assert (got.grad is None) == (expert not in used), (step, name)
+ if expert is not None and expert not in used:
+ assert torch.equal(got, before[name]), f"idle {name} moved at step {step}"
+ torch.testing.assert_close(got, want, msg = lambda m: f"{name} step {step}: {m}")
+ finally:
+ cp._ACTIVE_MANAGER = None
+
+
[email protected]("lora", [False, True], ids = ["full", "lora_experts"])
+def test_context_parallel_idle_experts_follow_single_process_adamw(lora):
+ """An expert no rank routes to runs on no tokens under CP, so DDP hands it a zero gradient.
+ The optimizer step pre-hook must turn that back into None so AdamW (weight decay, moments,
+ step count) treats it like the single-process run, over gradient accumulation micro-batches
+ where an expert used in only one micro-batch keeps its gradient."""
+ _moe_spawn(_moe_adamw_worker, 2, lora, True)
+
+
+def test_without_the_hook_idle_experts_move_under_adamw():
+ # Negative control: the zero gradients alone decay idle experts and advance their moments.
+ with pytest.raises(Exception, match = "moved at step|not close"):
+ _moe_spawn(_moe_adamw_worker, 2, False, False)
+
+
+def test_idle_expert_hook_is_inert_without_every_expert_blocks_and_when_all_are_routed():
+ from unsloth import context_parallel as cp
+
+ optimizer = torch.optim.AdamW(nn.Linear(2, 2).parameters())
+ assert not cp.install_idle_expert_grad_hook(optimizer, nn.Linear(2, 2))
+ assert not optimizer._optimizer_step_pre_hooks
+ block = _complementary_block(False)
+ cp._ACTIVE_MANAGER = object()
+ try:
+ x = torch.cat([_routed_tokens((e, (e + 1) % 8), e) for e in range(0, 8, 2)], dim = 1)
+ block(x).pow(2).sum().backward()
+ with torch.no_grad(): # a graph-free forward does not count
+ block(_routed_tokens((0, 1), 0))
+ finally:
+ cp._ACTIVE_MANAGER = None
+ assert block._unsloth_cp_expert_tokens.gt(0).all()
+ grads = {n: p.grad.clone() for n, p in block.named_parameters() if p.grad is not None}
+ assert cp.drop_idle_expert_grads([block]) == 0
+ for n, p in block.named_parameters():
+ if n in grads:
+ assert torch.equal(p.grad, grads[n]), n
+ # The next window forgets only experts whose gradients were cleared since (zero_grad).
+ for expert in block.experts[:4]:
+ expert.zero_grad(set_to_none = True)
+ cp.start_expert_window([block])
+ assert block._unsloth_cp_expert_tokens.gt(0).tolist() == [False] * 4 + [True] * 4
+ block.zero_grad(set_to_none = True)
+ cp.start_expert_window([block])
+ assert "_unsloth_cp_expert_tokens" not in block.__dict__
+ # No counts recorded (CP off): the step keeps every gradient, also if a CP hook is installed.
+ block(_routed_tokens((0, 1), 0)).pow(2).sum().backward()
+ assert "_unsloth_cp_expert_tokens" not in block.__dict__
+ assert cp.drop_idle_expert_grads([block]) == 0
+ assert all(p.grad is not None for p in block.experts[0].parameters())
+
+
[email protected]("skipped", [False, True], ids = ["stepped", "amp_skipped"])
+def test_an_optimizer_reused_without_context_parallelism_keeps_every_gradient(skipped):
+ """The idle-expert step pre-hook stays on the optimizer. A later trainer without CP reusing it
+ must keep the gradients of experts the CP window never routed to (one process has them), also
+ when the last CP step was skipped (GradScaler overflow: the pre-hook never ran)."""
+ from unsloth import context_parallel as cp
+
+ block = _complementary_block(False)
+ optimizer = torch.optim.AdamW(block.parameters(), lr = 1e-2, weight_decay = 0.1)
+ assert cp.install_idle_expert_grad_hook(optimizer, block, window = 0)
+ cp._ACTIVE_MANAGER = object()
+ try:
+ block(_routed_tokens((0, 2), 0)).pow(2).sum().backward() # CP step: experts 0 and 2
+ finally:
+ cp._ACTIVE_MANAGER = None
+ if not skipped:
+ optimizer.step() # the hook drops the other experts' zero gradients
+ assert block.experts[1].down_proj.weight.grad is None
+ optimizer.zero_grad(set_to_none = True)
+ # The same optimizer, CP off: experts 1 and 3 only.
+ block(_routed_tokens((1, 3), 1)).pow(2).sum().backward()
+ grads = {n: p.grad.clone() for n, p in block.named_parameters() if p.grad is not None}
+ assert any(n.startswith("experts.1.") for n in grads)
+ before = {n: p.detach().clone() for n, p in block.named_parameters()}
+ optimizer.step()
+ for name, param in block.named_parameters():
+ assert (param.grad is None) == (name not in grads), name
+ if name.startswith(("experts.1.", "experts.3.")):
+ assert torch.equal(param.grad, grads[name]), name
+ assert not torch.equal(param, before[name]), f"{name} did not train"
+
+
+def test_an_expert_parallel_block_is_not_counted_as_running_every_expert():
+ """ep_size > 1 keeps the remote forward (its own expert all-to-all), not the zero-token
+ dispatch, so the context parallel MoE refusal must still apply to it."""
+ from unsloth import context_parallel as cp
+
+ mod = _remote_module("transformers_modules.kimi_ep.modeling_deepseek", _KIMI_INPLACE)
+ block = mod.DeepseekV3MoE(mod.Cfg())
+ prepare_remote_moe_for_training(block, verbose = False)
+ assert cp._runs_every_expert(block)
+ block.ep_size = 2
+ assert not cp._runs_every_expert(block)
+ block.train()
+ with pytest.raises(Exception): # the port has no training path of its own
+ block(torch.randn(1, 3, 16))
+
+
+def _ulysses_manager(
+ size,
+ rank,
+ backend = "ulysses",
+):
+ from unsloth import context_parallel as cp
+
+ manager = object.__new__(cp.ContextParallelManager)
+ manager.size = size
+ manager.backend = backend
+ if backend == "ring":
+ from torch.distributed.device_mesh import init_device_mesh
+ manager.mesh = init_device_mesh("cpu", (size,))
+ else:
+ manager.mesh = types.SimpleNamespace(get_group = lambda: None, get_local_rank = lambda: rank)
+ return manager
+
+
+def _pad_routed_embedding():
+ # Token t routes to experts _PAD_ROUTES[t]; token 0 is the id context parallelism pads with.
+ weight = torch.cat([_routed_tokens(experts, t)[0, :1] for t, experts in enumerate(_PAD_ROUTES)])
+ return nn.Embedding.from_pretrained(weight, freeze = True)
+
+
+_PAD_ROUTES = ((6, 7), (0, 1), (2, 3), (4, 5))
+
+
+def _moe_cp_padding_worker(rank, world, lora, backend):
+ """Five real tokens over 2 ranks: the manager pads with id 0 (Ulysses: one token, on rank 1's
+ shard; ring: three, load balanced over both), the only token routed to experts 6 and 7. One
+ process never routes to them."""
+ import copy
+
+ import torch.distributed as dist
+
+ from unsloth import context_parallel as cp
+
+ block = _complementary_block(lora)
+ reference = copy.deepcopy(block)
+ embed = _pad_routed_embedding()
+ ids = torch.tensor([[1, 2, 3, 1, 2]])
+ shift = F.pad(ids, (0, 1), value = -100)[:, 1:]
+ count = shift.ne(-100).sum()
+
+ def loss_of(module, input_ids, shift_labels):
+ out = module(embed(input_ids)).pow(2).sum(-1)
+ return (out * shift_labels.ne(-100)).sum() / count
+
+ adamw = dict(lr = 1e-2, weight_decay = 0.1)
+ optimizer = torch.optim.AdamW([p for p in block.parameters() if p.requires_grad], **adamw)
+ ref_optimizer = torch.optim.AdamW(
+ [p for p in reference.parameters() if p.requires_grad], **adamw
+ )
+ assert cp.install_idle_expert_grad_hook(optimizer, block)
+ for step in range(2):
+ optimizer.zero_grad(set_to_none = True)
+ ref_optimizer.zero_grad(set_to_none = True)
+ loss_of(reference, ids, shift).backward()
+ manager = _ulysses_manager(world, rank, backend)
+ inputs = {"input_ids": ids.clone(), "labels": ids.clone()}
+ with manager.apply(inputs):
+ local = inputs["input_ids"]
+ assert local.shape == ((1, 3) if backend == "ulysses" else (1, 4))
+ # Synthetic pad tokens are on this shard, and they really run through the MoE.
+ assert bool(local.eq(0).any()) == (backend == "ring" or rank == world - 1)
+ loss_of(block, local, inputs["shift_labels"]).backward()
+ for param in block.parameters():
+ if param.requires_grad:
+ assert param.grad is not None # every expert ran, as DDP needs
+ dist.all_reduce(param.grad)
+ before = {n: p.detach().clone() for n, p in block.named_parameters()}
+ optimizer.step()
+ ref_optimizer.step()
+ for (name, got), want in zip(block.named_parameters(), reference.parameters()):
+ if not got.requires_grad:
+ continue
+ expert = int(name.split(".")[1]) if name.startswith("experts.") else None
+ if expert in (6, 7):
+ assert want.grad is None, name
+ assert got.grad is None, f"{name}: a pad-only expert kept its zero gradient"
+ assert torch.equal(got, before[name]), f"pad-only {name} moved at step {step}"
+ assert (got.grad is None) == (want.grad is None), name
+ torch.testing.assert_close(got, want, msg = lambda m: f"{name} step {step}: {m}")
+ for p, q in zip(
+ optimizer.param_groups[0]["params"], ref_optimizer.param_groups[0]["params"]
+ ):
+ assert (p in optimizer.state) == (q in ref_optimizer.state)
+
+
+ "lora, backend",
+ [(False, "ulysses"), (True, "ulysses"), (False, "ring")],
+ ids = ["full-ulysses", "lora_experts-ulysses", "full-ring"],
+)
+def test_context_parallel_padding_does_not_count_as_expert_usage(lora, backend):
+ """When the sequence length does not divide the CP size, the manager appends synthetic pad
+ tokens. Their routes must not mark an expert as used: one process never sees them, so an
+ expert only they pick has a None gradient there and AdamW must leave it alone under CP too."""
+ _moe_spawn(_moe_cp_padding_worker, 2, lora, backend)
+
+
+# Per optimizer step, two gradient accumulation micro-batches, the experts each rank routes to.
+# Step 0 overflows under fp16 loss scaling, so GradScaler skips optimizer.step() (and its pre-hook).
+# Step 1: 0 to 3 idle everywhere; they were used only in the discarded window. Step 2: 4 to 7 idle.
+_AMP_ROUTES = (
+ (((0, 1), (2, 3)), ((0, 1), (2, 3))),
+ (((4, 5), (6, 7)), ((4, 5), (6, 7))),
+ (((0, 1), (0, 1)), ((2, 3), (0, 1))),
+)
+
+
+class _CheckpointedLayer(nn.Module):
+ def __init__(self, block, gc):
+ super().__init__()
+ self.block = block
+ self.gc = gc
+
+ def forward(self, x):
+ if self.gc:
+ from torch.utils.checkpoint import checkpoint
+ return checkpoint(self.block, x, use_reentrant = False)
+ return self.block(x)
+
+
+def _moe_amp_skip_worker(rank, world, set_to_none, gc):
+ """Trainer.training_step (Unsloth's CP wrapper) over DDP, GradScaler skipping the first step,
+ against one process seeing every rank's tokens with the same scaler."""
+ import copy
+
+ import trl
+ from torch.nn.parallel import DistributedDataParallel
+
+ from unsloth import context_parallel as cp
+
+ block = _complementary_block(False)
+ reference = _CheckpointedLayer(copy.deepcopy(block), gc)
+ model = DistributedDataParallel(_CheckpointedLayer(block, gc), find_unused_parameters = False)
+ adamw = dict(lr = 1e-2, weight_decay = 0.1)
+ optimizer = torch.optim.AdamW([p for p in block.parameters() if p.requires_grad], **adamw)
+ ref_optimizer = torch.optim.AdamW(
+ [p for p in reference.parameters() if p.requires_grad], **adamw
+ )
+ scaler = torch.amp.GradScaler("cpu", init_scale = 1.0)
+ ref_scaler = torch.amp.GradScaler("cpu", init_scale = 1.0)
+ micros = len(_AMP_ROUTES[0])
+
+ class Trainer:
+ def __init__(self):
+ pass
+
+ def training_step(
+ self,
+ model,
+ inputs,
+ num_items_in_batch = None,
+ ):
+ loss = model(_routed_tokens(self.route, self.seed)).pow(2).sum() / micros
+ scaler.scale(loss).backward()
+
+ def prediction_step(self, model, inputs, prediction_loss_only):
+ return (None, None, None)
+
+ def train(self):
+ pass
+
+ def evaluate(self):
+ pass
+
+ def evaluation_loop(self, *a, **k):
+ pass
+
+ trl.SFTTrainer = Trainer
+ cp.patch_sft_trainer(install_cp_methods = True)
+ trainer = Trainer()
+ trainer.model, trainer.optimizer = model, optimizer
+ trainer.state = types.SimpleNamespace(global_step = 0)
+ trainer._context_parallel_manager = _ulysses_manager(world, rank)
+ probe = next(n for n, p in block.named_parameters() if p.requires_grad)
+ for step, micro_routes in enumerate(_AMP_ROUTES):
+ for micro, routes in enumerate(micro_routes):
+ seed = step * 100 + micro * 10
+ trainer.route, trainer.seed = routes[rank], seed + rank
+ trainer.training_step(model, {"input_ids": torch.ones(1, 4, dtype = torch.long)}, 4)
+ for peer in range(world):
+ loss = reference(_routed_tokens(routes[peer], seed + peer)).pow(2).sum()
+ ref_scaler.scale(loss / (world * micros)).backward()
+ if step == 0: # an fp16 overflow on every rank
+ for module in (block, reference.block):
+ module.get_parameter(probe).grad.view(-1)[0] = float("inf")
+ before = {n: p.detach().clone() for n, p in block.named_parameters()}
+ scaler.step(optimizer)
+ ref_scaler.step(ref_optimizer)
+ scaler.update()
+ ref_scaler.update()
+ if step == 0:
+ assert not optimizer.state and not ref_optimizer.state # really skipped
+ assert scaler.get_scale() < 1.0
+ else:
+ for (name, got), want in zip(block.named_parameters(), reference.block.parameters()):
+ if got.requires_grad:
+ assert (got.grad is None) == (want.grad is None), (step, name)
+ for (name, got), want in zip(block.named_parameters(), reference.block.parameters()):
+ if not got.requires_grad:
+ continue
+ expert = int(name.split(".")[1]) if name.startswith("experts.") else None
+ if step == 2 and set_to_none and expert is not None and expert >= 4:
+ assert torch.equal(got, before[name]), f"idle {name} moved at step {step}"
+ torch.testing.assert_close(got, want, msg = lambda m: f"{name} step {step}: {m}")
+ # Trainer's model.zero_grad() (set_to_none = True); set_to_none = False keeps zero tensors.
+ model.zero_grad(set_to_none = set_to_none)
+ reference.zero_grad(set_to_none = set_to_none)
+ trainer.state.global_step += 1
+
+
[email protected]("gc", [False, True], ids = ["plain", "checkpointed"])
[email protected]("set_to_none", [True, False], ids = ["set_to_none", "zeroed"])
+def test_a_skipped_amp_step_does_not_leak_expert_usage(set_to_none, gc):
+ """fp16 GradScaler skips optimizer.step() on overflow, so the step pre-hook never runs for that
+ window. Its expert usage must not carry into the next window (an expert used only there would
+ keep a zero gradient and AdamW would decay it), with gradient accumulation and checkpoint
+ recompute; with zero_grad(set_to_none = False) one process keeps zero gradients, which CP
+ must mirror instead of dropping them."""
+ _moe_spawn(_moe_amp_skip_worker, 2, set_to_none, gc)
+
+
+def test_real_token_masks_never_mark_a_real_token_as_padding():
+ """The MoE sees only a shard's token count: masks of graph-building forwards of one size are
+ OR-ed, and one with nothing appended makes every token of that size real."""
+ manager = _ulysses_manager(2, 1)
+ odd = {"input_ids": torch.ones(1, 5, dtype = torch.long)}
+ manager._prepare_inputs(odd)
+ manager._prepare_inputs(odd) # prediction_step, then apply: still knows the real length
+ manager._ulysses_shard(odd)
+ assert manager.real_token_mask(3).tolist() == [True, True, False]
+ assert manager.real_token_mask(4) is None
+ even = {"input_ids": torch.ones(1, 6, dtype = torch.long)}
+ manager._prepare_inputs(even)
+ manager._ulysses_shard(even)
+ assert manager.real_token_mask(3) is None
+ manager._clear_real_tokens()
+ odd = {"input_ids": torch.ones(1, 5, dtype = torch.long)}
+ with torch.no_grad(): # nothing to recompute: not noted
+ manager._prepare_inputs(odd)
+ manager._ulysses_shard(odd)
+ assert manager.real_token_mask(3) is None
diff --git a/tests/test_ulysses_hybrid.py b/tests/test_ulysses_hybrid.py
index c7b7c1d5656..f5fa51d0d91 100644
--- a/tests/test_ulysses_hybrid.py
+++ b/tests/test_ulysses_hybrid.py
@@ -331,7 +331,7 @@ def test_hybrid_gates():
self.conv1d = torch.nn.Conv1d(2, 2, 4, groups = 2)
model.model.layers[0].mixer = FakeMamba2()
- with pytest.raises(NotImplementedError, match = "Gated DeltaNet linear attention only"):
+ with pytest.raises(NotImplementedError, match = "linear attention only"):
cp._check_stateful_mixers(model, "ulysses", 2)
diff --git a/tests/test_ulysses_kimi.py b/tests/test_ulysses_kimi.py
new file mode 100644
index 00000000000..f379267e84d
--- /dev/null
+++ b/tests/test_ulysses_kimi.py
@@ -0,0 +1,1226 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Ulysses context parallelism for Kimi-Linear / Kimi K3 (KDA + MLA), on CPU gloo ranks.
+
+Kimi ships remote modeling code, so the layers here are stand-ins with the remote class names and
+attribute layout, and a plain full-sequence torch reference forward.
+"""
+
+import os
+import tempfile
+import types
+
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+import torch.nn as nn
+import torch.nn.functional as F
+
+import unsloth # noqa: F401
+from unsloth import context_parallel as cp
+from unsloth.utils import attention_dispatch as ad
+from unsloth.utils import ulysses_hybrid as uh
+
+transformers = pytest.importorskip("transformers")
+from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS # noqa: E402
+
+HIDDEN, HEADS, HEAD_DIM, VOCAB = 32, 4, 8, 64
+
+
+# moonshotai/Kimi-Linear-48B-A3B-Instruct modeling_kimi.py, verbatim: the MoE MLPs, the gate that adds its score
+# bias in place to the sigmoid output, and the inference-only sparse block (Unsloth's remote MoE shim trains it).
+_HUB_KIMI_MOE_SRC = r'''
+from __future__ import annotations
+import math
+import torch
+import torch.nn.functional as F
+from torch import nn
+from transformers.activations import ACT2FN
+
+
+class KimiBlockSparseMLP(nn.Module):
+ def __init__(self, config: KimiLinearConfig, hidden_size=None, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.ffn_dim = config.intermediate_size if intermediate_size is None else intermediate_size
+ self.hidden_dim = config.hidden_size if hidden_size is None else hidden_size
+
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) # gate
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False) # down
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) # up
+
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, hidden_states):
+ current_hidden_states = self.act_fn(
+ self.w1(hidden_states)) * self.w3(hidden_states)
+ current_hidden_states = self.w2(current_hidden_states)
+ return current_hidden_states
+
+
+class KimiMLP(nn.Module):
+ def __init__(self, config: KimiLinearConfig, hidden_size=None, intermediate_size=None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
+ self.gate_proj = nn.Linear(
+ self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(
+ self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(
+ self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(
+ self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+
+class KimiMoEGate(nn.Module):
+ """
+ MoEGate adapted from Deepseek-V3.
+ Parameter correspondences:
+ num_experts -> n_routed_experts
+ num_experts_per_token -> num_experts_per_tok
+ num_expert_group -> n_group
+ moe_router_activation_func -> scoring_func
+ """
+
+ def __init__(self, config: KimiLinearConfig):
+ super().__init__()
+ self.config = config
+ self.top_k = config.num_experts_per_token
+ self.num_experts = config.num_experts
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.moe_router_activation_func = config.moe_router_activation_func
+ self.num_expert_group = getattr(config, "num_expert_group", 1)
+ self.topk_group = getattr(config, "topk_group", 1)
+
+ # topk selection algorithm
+ self.moe_renormalize = config.moe_renormalize
+ self.gating_dim = config.hidden_size
+ self.weight = nn.Parameter(
+ torch.empty((self.num_experts, self.gating_dim)),
+ )
+
+ self.e_score_correction_bias = nn.Parameter(
+ torch.empty(self.num_experts),
+ )
+ self.reset_parameters()
+
+ def reset_parameters(self) -> None:
+ import torch.nn.init as init
+
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
+
+ def forward(self, hidden_states):
+ bsz, seq_len, h = hidden_states.shape
+ # compute gating score
+ hidden_states = hidden_states.view(-1, h)
+ logits = F.linear(
+ hidden_states.type(torch.float32), self.weight.type(
+ torch.float32), None,
+ )
+ if self.moe_router_activation_func == "sigmoid":
+ scores = logits.sigmoid()
+ elif self.moe_router_activation_func == "softmax":
+ scores = logits.softmax(dim=1)
+ else:
+ raise NotImplementedError(
+ f"insupportable scoring function for MoE gating: {self.moe_router_activation_func}",
+ )
+
+ # select top-k experts
+ assert not self.training
+ scores_for_choice = scores.view(bsz * seq_len, -1)
+ scores_for_choice += self.e_score_correction_bias.unsqueeze(0)
+ group_scores = (
+ scores_for_choice.view(
+ bsz * seq_len, self.num_expert_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
+ ) # [n, num_expert_group]
+ group_idx = torch.topk(
+ group_scores, k=self.topk_group, dim=-1, sorted=False,
+ )[
+ 1
+ ] # [n, top_k_group]
+ group_mask = torch.zeros_like(group_scores) # [n, num_expert_group]
+ group_mask.scatter_(1, group_idx, 1) # [n, num_expert_group]
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(
+ bsz * seq_len, self.num_expert_group, self.num_experts // self.num_expert_group,
+ )
+ .reshape(bsz * seq_len, -1)
+ ) # [n, e]
+ tmp_scores = scores_for_choice.masked_fill(
+ ~score_mask.bool(), 0.0) # [n, e]
+ _, topk_idx = torch.topk(
+ tmp_scores, k=self.top_k, dim=-1, sorted=False,
+ )
+ topk_weight = scores.gather(1, topk_idx)
+
+ # norm gate to sum 1
+ if self.top_k > 1 and self.moe_renormalize:
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weight = topk_weight / denominator
+ # must multiply the scaling factor
+ topk_weight = topk_weight * self.routed_scaling_factor
+
+ return topk_idx, topk_weight
+
+
+
+class KimiSparseMoeBlock(nn.Module):
+ """
+ Adapted from Deepseek-V3's MOE implementation
+ The namings are consistent with Kimi's version.
+ """
+
+ def __init__(self, config: KimiLinearConfig):
+ super().__init__()
+ self.config = config
+ self.hidden_dim = config.hidden_size
+ self.num_experts = config.num_experts
+ self.top_k = config.num_experts_per_token
+ self.moe_renormalize = config.moe_renormalize
+
+ self.ep_size = 1
+ self.experts_per_rank = config.num_experts
+ self.ep_rank = 0
+ self.experts = nn.ModuleList(
+ [
+ KimiBlockSparseMLP(
+ config, intermediate_size=config.moe_intermediate_size,
+ )
+ for _ in range(config.num_experts)
+ ],
+ )
+ self.gate = KimiMoEGate(config)
+ if config.num_shared_experts is not None:
+ intermediate_size = config.moe_intermediate_size * config.num_shared_experts
+ self.shared_experts = KimiMLP(
+ config=config, intermediate_size=intermediate_size,
+ )
+
+ def forward(self, hidden_states):
+ identity = hidden_states
+ orig_shape = hidden_states.shape
+ topk_idx, topk_weight = self.gate(hidden_states)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ if not self.training:
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
+ else:
+ raise NotImplementedError("Training mode is not supported in KimiSparseMoeBlock")
+ if self.config.num_shared_experts is not None:
+ y = y + self.shared_experts(identity)
+ return y
+
+ @torch.no_grad()
+ def moe_infer(self, x, topk_ids, topk_weight):
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
+ cnts.scatter_(1, topk_ids, 1)
+ tokens_per_expert = cnts.sum(dim=0)
+ idxs = topk_ids.view(-1).argsort()
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
+
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
+
+ outputs = []
+ start_idx = 0
+ for i, num_tokens in enumerate(tokens_per_expert):
+ end_idx = start_idx + num_tokens
+ if num_tokens == 0:
+ continue
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
+ expert_out = expert(tokens_for_this_expert)
+ outputs.append(expert_out)
+ start_idx = end_idx
+
+ outs = torch.cat(outputs, dim=0) if len(
+ outputs) else sorted_tokens.new_empty(0)
+
+ new_x = torch.empty_like(outs)
+ new_x[idxs] = outs
+ final_out = (
+ new_x.view(*topk_ids.shape, -1)
+ .type(topk_weight.dtype)
+ .mul_(topk_weight.unsqueeze(dim=-1))
+ .sum(dim=1)
+ .type(new_x.dtype)
+ )
+ return final_out
+
+'''
+_MOE_CONFIG = types.SimpleNamespace(
+ hidden_size = HIDDEN,
+ intermediate_size = 2 * HIDDEN,
+ moe_intermediate_size = 16,
+ hidden_act = "silu",
+ num_experts = 8,
+ num_experts_per_token = 2,
+ routed_scaling_factor = 2.446,
+ moe_router_activation_func = "sigmoid",
+ num_expert_group = 1,
+ topk_group = 1,
+ moe_renormalize = True,
+ num_shared_experts = 1,
+)
+
+
+def _hub_kimi_moe_module(name = "transformers_modules.tiny_kimi_cp.modeling_kimi"):
+ import linecache
+ import sys
+
+ if name in sys.modules:
+ return sys.modules[name]
+ filename = f"<{name}>"
+ linecache.cache[filename] = (
+ len(_HUB_KIMI_MOE_SRC),
+ None,
+ _HUB_KIMI_MOE_SRC.splitlines(True),
+ filename,
+ )
+ module = types.ModuleType(name)
+ module.__dict__["__name__"] = name
+ exec(compile(_HUB_KIMI_MOE_SRC, filename, "exec"), module.__dict__)
+ sys.modules[name] = module
+ return module
+
+
+class _Config(types.SimpleNamespace):
+ # Stands in for a PretrainedConfig: PEFT 0.18 reads model.config.to_dict().
+ def to_dict(self):
+ return dict(vars(self))
+
+
+def _acc(x):
+ # fp32 math for low precision, fp64 kept for the fp64 reference.
+ return torch.promote_types(x.dtype, torch.float32)
+
+
+class _ShortConv(nn.Conv1d):
+ # fla.modules.ShortConvolution: depthwise causal conv with a SiLU.
+ def __init__(
+ self,
+ channels,
+ kernel = 4,
+ ):
+ super().__init__(
+ channels, channels, kernel, groups = channels, bias = False, padding = kernel - 1
+ )
+ self.activation = "silu"
+
+ def forward(self, x):
+ return F.silu(super().forward(x.transpose(1, 2))[..., : x.shape[1]].transpose(1, 2))
+
+
+class _GatedNorm(nn.Module):
+ # fla FusedRMSNormGated(activation = "sigmoid").
+ def __init__(self, dim):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(dim) + 0.1 * torch.randn(dim))
+
+ def forward(self, x, g):
+ x = x.to(_acc(x))
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim = True) + 1e-6)
+ return (self.weight * x * torch.sigmoid(g.to(_acc(g)))).to(g.dtype)
+
+
+class KimiDeltaAttention(nn.Module):
+ def __init__(self, k3):
+ super().__init__()
+ proj = HEADS * HEAD_DIM
+ self.num_heads, self.head_dim = HEADS, HEAD_DIM
+ self.q_proj, self.k_proj, self.v_proj = (
+ nn.Linear(HIDDEN, proj, bias = False) for _ in range(3)
+ )
+ self.q_conv1d, self.k_conv1d, self.v_conv1d = (_ShortConv(proj) for _ in range(3))
+ self.A_log = nn.Parameter(0.5 * torch.randn(HEADS))
+ self.dt_bias = nn.Parameter(0.5 * torch.randn(proj))
+ self.f_a_proj = nn.Linear(HIDDEN, HEAD_DIM, bias = False)
+ self.f_b_proj = nn.Linear(HEAD_DIM, proj, bias = False)
+ self.b_proj = nn.Linear(HIDDEN, HEADS, bias = False)
+ self.gate_lower_bound = -5.0 if k3 else None
+ if k3: # use_full_rank_gate
+ self.g_proj = nn.Linear(HIDDEN, proj, bias = False)
+ else:
+ self.g_a_proj = nn.Linear(HIDDEN, HEAD_DIM, bias = False)
+ self.g_b_proj = nn.Linear(HEAD_DIM, proj, bias = False)
+ self.o_norm = _GatedNorm(HEAD_DIM)
+ self.o_proj = nn.Linear(proj, HIDDEN, bias = False)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask = None,
+ cache_params = None,
+ **kwargs,
+ ):
+ bsz, seq, _ = hidden_states.shape
+ shape = (bsz, seq, HEADS, HEAD_DIM)
+ q = self.q_conv1d(self.q_proj(hidden_states)).view(shape)
+ k = self.k_conv1d(self.k_proj(hidden_states)).view(shape)
+ v = self.v_conv1d(self.v_proj(hidden_states)).view(shape)
+ acc = _acc(hidden_states)
+ f = self.f_b_proj(self.f_a_proj(hidden_states)).view(shape).to(acc) + self.dt_bias.view(
+ HEADS, HEAD_DIM
+ )
+ a = self.A_log.to(acc).exp().view(HEADS, 1)
+ if self.gate_lower_bound is not None:
+ g = self.gate_lower_bound * torch.sigmoid(a * f)
+ else:
+ g = -a * F.softplus(f)
+ beta = self.b_proj(hidden_states).to(acc).sigmoid()
+ # fla l2norm (use_qk_l2norm_in_kernel): eps 1e-6 under the square root.
+ q, k = q.to(acc), k.to(acc)
+ q = q * torch.rsqrt(q.pow(2).sum(-1, keepdim = True) + 1e-6) * HEAD_DIM**-0.5
+ k = k * torch.rsqrt(k.pow(2).sum(-1, keepdim = True) + 1e-6)
+ state = q.new_zeros(bsz, HEADS, HEAD_DIM, HEAD_DIM)
+ outs = []
+ for t in range(seq):
+ state = state * g[:, t].exp().unsqueeze(-1)
+ pred = (k[:, t].unsqueeze(-1) * state).sum(-2)
+ state = state + k[:, t].unsqueeze(-1) * (
+ beta[:, t, :, None] * (v[:, t].to(acc) - pred)
+ ).unsqueeze(-2)
+ outs.append((q[:, t].unsqueeze(-1) * state).sum(-2))
+ o = torch.stack(outs, dim = 1).to(hidden_states.dtype)
+ if hasattr(self, "g_proj"):
+ gate = self.g_proj(hidden_states)
+ else:
+ gate = self.g_b_proj(self.g_a_proj(hidden_states))
+ o = self.o_norm(o, gate.view(shape))
+ o = self.o_proj(o.reshape(bsz, seq, -1))
+ if attention_mask is not None:
+ # The hub layer unpads on the 2D mask and pad_input leaves zero rows at the padding; with
+ # right padding the causal conv and scan never carry it into the real tokens.
+ o = o * attention_mask[:, -seq:, None].to(o.dtype)
+ return o
+
+
+def eager_attention_forward(
+ module,
+ query,
+ key,
+ value,
+ attention_mask,
+ scaling,
+ dropout = 0.0,
+ **kwargs,
+):
+ # The hub modeling file's own eager attention (Ulysses swaps this module global).
+ weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ weights = weights + attention_mask[:, :, :, : key.shape[-2]]
+ weights = F.softmax(weights, dim = -1, dtype = _acc(query)).to(query.dtype)
+ return torch.matmul(weights, value).transpose(1, 2).contiguous(), weights
+
+
+def _causal_mask(
+ length,
+ dtype,
+ padding = None,
+):
+ mask = torch.full((length, length), torch.finfo(dtype).min, dtype = dtype).triu(1)[None, None]
+ if padding is not None:
+ # As transformers' create_causal_mask (sdpa / eager): padded keys are masked for every query,
+ # so a padding query attends its row's real keys.
+ mask = mask.masked_fill(padding[:, None, None, :] == 0, torch.finfo(dtype).min)
+ return mask
+
+
+class KimiMLAAttention(nn.Module):
+ # No RoPE (mla_use_nope); query / key heads 12 wide, value heads 8.
+ def __init__(self, config, k3):
+ super().__init__()
+ self.config = config
+ self.num_heads, self.num_key_value_groups, self.is_causal = HEADS, 1, True
+ self.qk_nope, self.qk_rope, self.v_dim, self.kv_lora = 8, 4, 8, 16
+ self.q_dim = self.qk_nope + self.qk_rope
+ self.scaling = self.q_dim**-0.5
+ self.q_proj = nn.Linear(HIDDEN, HEADS * self.q_dim, bias = False)
+ self.kv_a_proj_with_mqa = nn.Linear(HIDDEN, self.kv_lora + self.qk_rope, bias = False)
+ self.kv_b_proj = nn.Linear(self.kv_lora, HEADS * (self.qk_nope + self.v_dim), bias = False)
+ self.o_proj = nn.Linear(HEADS * self.v_dim, HIDDEN, bias = False)
+ self.use_output_gate = k3 # mla_use_output_gate
+ if k3:
+ self.g_proj = nn.Linear(HIDDEN, HEADS * self.v_dim, bias = False)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask = None,
+ **kwargs,
+ ):
+ bsz, seq, _ = hidden_states.shape
+ q = self.q_proj(hidden_states).view(bsz, seq, HEADS, self.q_dim).transpose(1, 2)
+ kv, k_rot = self.kv_a_proj_with_mqa(hidden_states).split(
+ [self.kv_lora, self.qk_rope], dim = -1
+ )
+ kv = self.kv_b_proj(kv).view(bsz, seq, HEADS, -1).transpose(1, 2)
+ k_nope, value = kv.split([self.qk_nope, self.v_dim], dim = -1)
+ k_rot = k_rot.view(bsz, 1, seq, self.qk_rope).expand(-1, HEADS, -1, -1)
+ key = torch.cat([k_nope, k_rot], dim = -1)
+ implementation = self.config._attn_implementation
+ attention = (
+ eager_attention_forward
+ if implementation == "eager"
+ else ALL_ATTENTION_FUNCTIONS[implementation]
+ )
+ out, _ = attention(self, q, key, value, attention_mask, dropout = 0.0, scaling = self.scaling)
+ out = out.reshape(bsz, seq, -1)
+ if self.use_output_gate:
+ out = out * self.g_proj(hidden_states).sigmoid()
+ return self.o_proj(out)
+
+
+class _Layer(nn.Module):
+ def __init__(
+ self,
+ config,
+ linear,
+ k3,
+ moe = None,
+ ):
+ super().__init__()
+ self.self_attn = KimiDeltaAttention(k3) if linear else KimiMLAAttention(config, k3)
+ if moe is not None:
+ self.block_sparse_moe = moe # the hub KimiSparseMoeBlock
+ else:
+ self.mlp = nn.Sequential(
+ nn.Linear(HIDDEN, 2 * HIDDEN), nn.SiLU(), nn.Linear(2 * HIDDEN, HIDDEN)
+ )
+ self.norm1, self.norm2 = nn.LayerNorm(HIDDEN), nn.LayerNorm(HIDDEN)
+
+ def forward(
+ self,
+ h,
+ attention_mask = None,
+ ):
+ # Kimi hands the delta layers the 2D padding mask and MLA the causal mask.
+ if isinstance(self.self_attn, KimiDeltaAttention):
+ mask = attention_mask
+ else:
+ mask = _causal_mask(h.shape[1], h.dtype, attention_mask)
+ h = h + self.self_attn(hidden_states = self.norm1(h), attention_mask = mask)
+ mlp = getattr(self, "block_sparse_moe", None) or self.mlp
+ return h + mlp(self.norm2(h))
+
+
+class _KimiForCausalLM(nn.Module):
+ def __init__(
+ self,
+ k3,
+ moe = False,
+ attn = "sdpa",
+ gc = False,
+ ):
+ super().__init__()
+ self.gc = gc
+ self.config = _Config(
+ _attn_implementation = attn,
+ num_attention_heads = HEADS,
+ num_key_value_heads = HEADS,
+ output_router_logits = False,
+ vision_config = None,
+ )
+ blocks = [None] * 3
+ if moe:
+ hub = _hub_kimi_moe_module()
+ moe_config = types.SimpleNamespace(**vars(_MOE_CONFIG))
+ if moe is not True:
+ moe_config.num_experts = moe
+ self.config.model_type = "kimi_linear"
+ self.config.num_experts = moe_config.num_experts
+ blocks = [hub.KimiSparseMoeBlock(moe_config) for _ in blocks]
+ for block in blocks:
+ with torch.no_grad():
+ block.gate.e_score_correction_bias.normal_(0, 0.3) # nonzero, as trained
+ block.gate.e_score_correction_bias[-2:] = -5.0 # two experts no token picks
+ self.model = nn.Module()
+ self.model.layers = nn.ModuleList(
+ _Layer(self.config, linear, k3, block)
+ for linear, block in zip((True, False, True), blocks)
+ )
+ self.embed = nn.Embedding(VOCAB, HIDDEN)
+ self.lm_head = nn.Linear(HIDDEN, VOCAB, bias = False)
+
+ def forward(
+ self,
+ input_ids,
+ position_ids = None,
+ use_cache = False,
+ attention_mask = None,
+ **kwargs,
+ ):
+ h = self.embed(input_ids)
+ for layer in self.model.layers:
+ if self.gc:
+ # As HF gradient checkpointing runs under DDP: non-reentrant, recomputed in backward.
+ from torch.utils.checkpoint import checkpoint
+ h = checkpoint(layer, h, attention_mask, use_reentrant = False)
+ else:
+ h = layer(h, attention_mask)
+ return types.SimpleNamespace(logits = self.lm_head(h))
+
+
+def _model(k3, **kwargs):
+ torch.manual_seed(0)
+ model = _KimiForCausalLM(k3, **kwargs).train()
+ if kwargs.get("moe"):
+ from unsloth.models.remote_moe_shims import prepare_remote_moe_for_training
+
+ prepare_remote_moe_for_training(model, verbose = False)
+ block = model.model.layers[0].block_sparse_moe
+ # The gate (renamed MoEGate) is shimmed through its inference-only block.
+ for module in (block, block.gate):
+ assert getattr(type(module).forward, "_unsloth_remote_moe_shim", False)
+ return model
+
+
+def _manager(
+ size,
+ rank,
+ group = None,
+):
+ manager = object.__new__(cp.ContextParallelManager)
+ manager.size = size
+ manager.backend = "ulysses"
+ manager.mesh = types.SimpleNamespace(get_group = lambda: group, get_local_rank = lambda: rank)
+ return manager
+
+
+def _loss(logits, shift_labels, count):
+ return (
+ F.cross_entropy(
+ logits.to(_acc(logits)).flatten(0, 1),
+ shift_labels.flatten(),
+ ignore_index = -100,
+ reduction = "sum",
+ )
+ / count
+ )
+
+
+def _parity_worker(rank, world, k3, control):
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ model = _model(k3)
+ ids = torch.randint(0, VOCAB, (2, 13), generator = torch.Generator().manual_seed(1))
+ shift = F.pad(ids, (0, 1), value = -100)[:, 1:]
+ count = shift.ne(-100).sum()
+ _loss(model(input_ids = ids).logits, shift, count).backward()
+ reference = {n: p.grad.clone() for n, p in model.named_parameters()}
+ model.zero_grad(set_to_none = True)
+
+ manager = _manager(world, rank)
+ manager.attach_attention_hooks(model)
+ if control:
+ for module in model.modules():
+ if getattr(module, "_unsloth_cp_orig_forward", None) is not None:
+ module.forward = module._unsloth_cp_orig_forward
+ inputs = {"input_ids": ids.clone(), "labels": ids.clone()}
+ manager._prepare_inputs(inputs)
+ with manager.apply(inputs):
+ out = model(input_ids = inputs["input_ids"], position_ids = inputs["position_ids"])
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ for name, param in model.named_parameters():
+ grad = torch.zeros_like(param) if param.grad is None else param.grad
+ dist.all_reduce(grad)
+ torch.testing.assert_close(grad, reference[name], rtol = 1e-4, atol = 1e-6, msg = name)
+
+
+def _spawn(fn, world, *args):
+ # Fork: a spawned child would re-import unsloth without the conftest CUDA spoof.
+ if "fork" not in mp.get_all_start_methods():
+ pytest.skip("needs the fork start method")
+ with tempfile.TemporaryDirectory() as d:
+ mp.start_processes(
+ _entry,
+ args = (world, os.path.join(d, "init"), fn, args),
+ nprocs = world,
+ join = True,
+ start_method = "fork",
+ )
+
+
+def _entry(rank, world, init_file, fn, args):
+ torch.set_num_threads(1)
+ dist.init_process_group("gloo", init_method = f"file://{init_file}", rank = rank, world_size = world)
+ try:
+ fn(rank, world, *args)
+ finally:
+ dist.destroy_process_group()
+
+
[email protected]("k3", [False, True], ids = ["kimi_linear", "kimi_k3"])
+def test_ulysses_kimi_gradients_match_one_rank(k3):
+ _spawn(_parity_worker, 2, k3, False)
+
+
+def test_shard_local_kimi_delta_is_wrong():
+ # Negative control: the stock forward on a sequence shard restarts the scan at the shard seam.
+ with pytest.raises(Exception, match = "AssertionError"):
+ _spawn(_parity_worker, 2, False, True)
+
+
+def _shard_local(fn, size, *xs):
+ # Negative-control helper: run fn on each sequence shard separately, as a shard-local layer would.
+ n = xs[0].shape[1] // size
+ return torch.cat([fn(*(x[:, i * n : (i + 1) * n] for x in xs)) for i in range(size)], dim = 1)
+
+
+# Deliberately broken copies of ulysses_kimi_delta_forward: each must fail the parity check.
+_BROKEN = {
+ "shard_local_scan": (
+ (
+ "out = _kda_scan(q, k, v, g, b.float().sigmoid())",
+ "out = _shard_local(_kda_scan, size, q, k, v, g, b.float().sigmoid())",
+ ),
+ ),
+ "shard_local_conv": tuple(
+ (
+ f"{x} = _kda_short_conv(module.{x}_conv1d, {x}, rows)",
+ f"{x} = _shard_local(lambda t: _kda_short_conv(module.{x}_conv1d, t, rows), size, {x})",
+ )
+ for x in "qkv"
+ ),
+ "a_log_of_rank0": (
+ (
+ "module.A_log.reshape(-1)[rank * heads : (rank + 1) * heads]",
+ "module.A_log.reshape(-1)[:heads]",
+ ),
+ ),
+ "dt_bias_of_rank0": (
+ (
+ "module.dt_bias.reshape(-1).index_select(0, rows)",
+ "module.dt_bias.reshape(-1)[: heads * dim]",
+ ),
+ ),
+ "lower_bound_dropped": (('getattr(module, "gate_lower_bound", None)', "None"),),
+}
+
+
+def _install_broken(name):
+ import inspect
+
+ target = "ulysses_kimi_delta_forward"
+ src = inspect.getsource(getattr(uh, target))
+ for before, after in _BROKEN[name]:
+ assert src.count(before) == 1, before
+ src = src.replace(before, after)
+ namespace = dict(vars(uh), _shard_local = _shard_local)
+ exec(src, namespace)
+ setattr(uh, target, namespace[target])
+
+
+def _audit_batch(
+ kind,
+ seed,
+ seq = 13,
+):
+ """Right padded rows of unequal length. "full": every valid token is a label. "seam": labels
+ stop one token after the CP=2 seam (position 7), so the label at 6 crosses it and every shard
+ from the second on has none."""
+ ids = torch.randint(0, VOCAB, (2, seq), generator = torch.Generator().manual_seed(seed))
+ mask = torch.ones_like(ids)
+ mask[0, 11:] = 0
+ mask[1, 9 - seed % 2 :] = 0
+ labels = ids.masked_fill(mask == 0, -100)
+ if kind == "seam":
+ labels[:, 8:] = -100
+ return ids, mask, labels
+
+
+def _inject_lora(model, experts = False):
+ from peft import LoraConfig, inject_adapter_in_model
+
+ # The hub MoE: routed experts w1 / w2 / w3, the shared expert gate / up / down.
+ expert_targets = ["w1", "w2", "w3", "gate_proj", "up_proj", "down_proj"] if experts else []
+ targets = expert_targets + [
+ "q_proj",
+ "k_proj",
+ "v_proj",
+ "f_b_proj",
+ "b_proj",
+ "g_b_proj",
+ "g_proj",
+ "o_proj",
+ "kv_b_proj",
+ ]
+ model = inject_adapter_in_model(LoraConfig(r = 4, lora_alpha = 8, target_modules = targets), model)
+ torch.manual_seed(2)
+ for name, param in model.named_parameters():
+ param.requires_grad_("lora_" in name)
+ if "lora_B" in name:
+ with torch.no_grad():
+ param.normal_(0, 0.2) # nonzero B: the adapters change the forward
+ return model
+
+
+def _audit_worker(
+ rank,
+ world,
+ k3,
+ cp_size,
+ kind,
+ lora,
+ broken,
+ masked = False,
+):
+ import copy
+
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ dp_size = world // cp_size
+ dp_rank, cp_rank = divmod(rank, cp_size)
+ groups = [dist.new_group(list(range(d * cp_size, (d + 1) * cp_size))) for d in range(dp_size)]
+ model = _model(k3).double()
+ if lora:
+ model = _inject_lora(model)
+ batches = [_audit_batch(kind, seed = d) for d in range(dp_size)]
+ shifts = [F.pad(labels, (0, 1), value = -100)[:, 1:] for _, _, labels in batches]
+ count = sum(shift.ne(-100).sum() for shift in shifts)
+
+ # Independent single-process fp64 reference over every DP replica's batch. masked: the delta
+ # layers see the 2D padding mask as the hub model passes it (CP's decoder hook drops it).
+ for (ids, mask, _), shift in zip(batches, shifts):
+ _loss(
+ model(input_ids = ids, attention_mask = mask if masked else None).logits, shift, count
+ ).backward()
+ reference = copy.deepcopy(model) # deepcopy drops .grad
+ for param, ref in zip(model.parameters(), reference.parameters()):
+ ref.grad = None if param.grad is None else param.grad.clone()
+ model.zero_grad(set_to_none = True)
+
+ manager = _manager(cp_size, cp_rank, groups[dp_rank] if dp_size > 1 else None)
+ manager.attach_attention_hooks(model)
+ if broken is not None:
+ _install_broken(broken)
+ ids, mask, labels = batches[dp_rank]
+ inputs = {"input_ids": ids.clone(), "attention_mask": mask.clone(), "labels": labels.clone()}
+ with manager.apply(inputs):
+ out = model(
+ input_ids = inputs["input_ids"],
+ position_ids = inputs["position_ids"],
+ attention_mask = inputs["attention_mask"],
+ )
+ local_labels = inputs["shift_labels"].ne(-100).sum()
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ if kind == "seam" and cp_rank * inputs["input_ids"].shape[1] >= 7:
+ assert local_labels == 0 # this shard trains on nothing of its own
+ for (name, param), ref in zip(model.named_parameters(), reference.parameters()):
+ # None vs zero vs value, per rank: DDP needs every rank to agree with the reference.
+ assert (param.grad is None) == (ref.grad is None), name
+ if param.grad is None:
+ continue
+ dist.all_reduce(param.grad)
+ # The CP scan runs in fp32 (as fla does), the reference in fp64.
+ torch.testing.assert_close(
+ param.grad, ref.grad, rtol = 1e-4, atol = 1e-6, msg = lambda m: f"{name}: {m}"
+ )
+ if not lora:
+ assert all(p.grad is not None for p in model.parameters())
+ optimizers = [
+ torch.optim.AdamW(
+ [p for p in m.parameters() if p.requires_grad], lr = 1e-2, eps = 1e-4, weight_decay = 0.1
+ )
+ for m in (model, reference)
+ ]
+ for optimizer in optimizers:
+ optimizer.step()
+ for (name, param), ref in zip(model.named_parameters(), reference.parameters()):
+ torch.testing.assert_close(
+ param, ref, rtol = 1e-5, atol = 1e-5, msg = lambda m: f"{name} after AdamW: {m}"
+ )
+
+
+ "k3, world, cp_size, kind, lora",
+ [
+ (False, 2, 2, "full", False),
+ (True, 2, 2, "full", False),
+ (False, 2, 2, "seam", False),
+ (True, 2, 2, "seam", True),
+ (False, 2, 2, "full", True),
+ (True, 4, 4, "full", False),
+ (False, 4, 4, "seam", True),
+ (True, 4, 2, "full", True),
+ ],
+ ids = [
+ "linear-cp2",
+ "k3-cp2",
+ "linear-cp2-seam",
+ "k3-cp2-seam-lora",
+ "linear-cp2-lora",
+ "k3-cp4",
+ "linear-cp4-seam-lora",
+ "k3-dp2xcp2-lora",
+ ],
+)
+def test_ulysses_kimi_matches_fp64_reference(k3, world, cp_size, kind, lora):
+ """Padded rows of unequal length, a shard without labels, a label across the seam, LoRA with
+ nonzero B, one AdamW step: CP=2, CP=4 and DP2 x CP2 against one fp64 process."""
+ _spawn(_audit_worker, world, k3, cp_size, kind, lora, None)
+
+
+ "broken, k3",
+ [
+ ("shard_local_scan", False),
+ ("shard_local_conv", False),
+ ("a_log_of_rank0", False),
+ ("dt_bias_of_rank0", True),
+ ("lower_bound_dropped", True),
+ ],
+)
+def test_broken_kimi_delta_shards_fail_the_reference(broken, k3):
+ # Negative controls: a scan or conv restarted at the seam, another rank's per-head decay
+ # parameters, or K3's lower-bounded gate read as the standard one.
+ with pytest.raises(Exception, match = "not close"):
+ _spawn(_audit_worker, 2, k3, 2, "full", False, broken)
+
+
+ "k3, world, cp_size",
+ [(False, 2, 2), (True, 4, 4)],
+ ids = ["linear-cp2", "k3-cp4"],
+)
+def test_right_padded_kimi_under_cp_matches_a_masked_one_process(k3, world, cp_size):
+ """Under CP the decoder hook (#16862) and the self_attn hook give Kimi's delta layers no padding
+ mask (Kimi names them self_attn, not linear_attn). CP only accepts right padding, and the scan is
+ causal, so the real tokens match a one-process run whose delta layers do mask the padding."""
+ _spawn(_audit_worker, world, k3, cp_size, "full", True, None, True)
+
+
+def test_the_padding_mask_changes_only_padded_positions_of_kimi_delta():
+ # The control for the test above: the reference's mask is engaged (padded positions change)
+ # and real tokens do not depend on the right padding after them.
+ model = _model(False).double()
+ ids, mask, _ = _audit_batch("full", seed = 0)
+ with torch.no_grad():
+ plain = model(input_ids = ids).logits
+ masked = model(input_ids = ids, attention_mask = mask).logits
+ real = mask.bool()
+ torch.testing.assert_close(masked[real], plain[real], rtol = 1e-12, atol = 1e-12)
+ assert not torch.allclose(masked[~real], plain[~real])
+
+
+def test_left_padded_rows_are_refused_under_cp():
+ manager = _manager(2, 0)
+ ids = torch.randint(0, VOCAB, (2, 8))
+ mask = torch.ones_like(ids)
+ mask[0, :3] = 0 # left padding: the scan would carry pad tokens into the real ones
+ with pytest.raises(ValueError, match = "right-padded"):
+ manager._prepare_inputs({"input_ids": ids, "attention_mask": mask, "labels": ids.clone()})
+
+
+def _moe_worker(rank, world, cp_size, precision, attn, gc):
+ """Kimi-Linear with the hub MoE block (shimmed by Unsloth) under Ulysses: fp64 against one
+ process over every DP replica's batch, the idle-expert hook, one AdamW step."""
+ import copy
+
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ dp_size = world // cp_size
+ dp_rank, cp_rank = divmod(rank, cp_size)
+ groups = [dist.new_group(list(range(d * cp_size, (d + 1) * cp_size))) for d in range(dp_size)]
+ model = _model(False, moe = True, attn = attn, gc = gc).double()
+ if precision != "full":
+ model = _inject_lora(model, experts = precision == "lora_experts")
+ batches = [_audit_batch("full", seed = d) for d in range(dp_size)]
+ shifts = [F.pad(labels, (0, 1), value = -100)[:, 1:] for _, _, labels in batches]
+ count = sum(shift.ne(-100).sum() for shift in shifts)
+ for (ids, mask, _), shift in zip(batches, shifts):
+ _loss(model(input_ids = ids, attention_mask = mask).logits, shift, count).backward()
+ reference = copy.deepcopy(model)
+ for param, ref in zip(model.parameters(), reference.parameters()):
+ ref.grad = None if param.grad is None else param.grad.clone()
+ model.zero_grad(set_to_none = True)
+ idle = [ref.grad is None and ref.requires_grad for ref in reference.parameters()]
+ # Frozen experts (attention-only LoRA) have no gradient on either side.
+ assert any(idle) or precision == "lora", "no idle expert: the None vs zero check proves nothing"
+
+ calls = {"kda": 0, "mla": 0, "experts": 0}
+
+ def counted(key, fn):
+ def wrapper(*args, **kwargs):
+ calls[key] += 1
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+ uh.ulysses_kimi_delta_forward = counted("kda", uh.ulysses_kimi_delta_forward)
+ uh._ulysses_hf_attention = counted("mla", uh._ulysses_hf_attention)
+ cp.record_expert_tokens = counted("experts", cp.record_expert_tokens)
+
+ manager = _manager(cp_size, cp_rank, groups[dp_rank] if dp_size > 1 else None)
+ manager.attach_attention_hooks(model)
+ ids, mask, labels = batches[dp_rank]
+ inputs = {"input_ids": ids.clone(), "attention_mask": mask.clone(), "labels": labels.clone()}
+ with manager.apply(inputs):
+ out = model(
+ input_ids = inputs["input_ids"],
+ position_ids = inputs["position_ids"],
+ attention_mask = inputs["attention_mask"],
+ )
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ # Engaged: KDA and MLA ran their Ulysses routes, the MoE ran every expert (forward and, with
+ # checkpointing, the recompute).
+ assert calls["kda"] >= 2 and calls["mla"] >= 1 and calls["experts"] >= 3, calls
+ trainable = [p for p in model.parameters() if p.requires_grad]
+ for param in trainable:
+ # Every expert ran under CP, so DDP reduces a gradient for every trainable parameter.
+ assert param.grad is not None
+ dist.all_reduce(param.grad)
+ optimizer = torch.optim.AdamW(trainable, lr = 1e-2, eps = 1e-4, weight_decay = 0.1)
+ assert cp.install_idle_expert_grad_hook(optimizer, model)
+ for (name, param), ref, was_idle in zip(model.named_parameters(), reference.parameters(), idle):
+ if not param.requires_grad:
+ continue
+ if was_idle:
+ assert not param.grad.any(), name # zero now, dropped by the hook at the step
+ continue
+ torch.testing.assert_close(
+ param.grad, ref.grad, rtol = 1e-4, atol = 1e-6, msg = lambda m: f"{name}: {m}"
+ )
+ optimizer.step()
+ torch.optim.AdamW(
+ [p for p in reference.parameters() if p.requires_grad],
+ lr = 1e-2,
+ eps = 1e-4,
+ weight_decay = 0.1,
+ ).step()
+ for (name, param), ref in zip(model.named_parameters(), reference.parameters()):
+ assert (param.grad is None) == (ref.grad is None), name
+ torch.testing.assert_close(
+ param, ref, rtol = 1e-5, atol = 1e-5, msg = lambda m: f"{name} after AdamW: {m}"
+ )
+
+
+ "precision, attn, gc, world, cp_size",
+ [
+ ("full", "sdpa", False, 2, 2),
+ ("lora", "eager", True, 2, 2),
+ ("lora_experts", "sdpa", True, 2, 2),
+ ("lora_experts", "eager", False, 2, 2),
+ ("full", "eager", True, 4, 2),
+ ],
+ ids = [
+ "full-sdpa-cp2",
+ "lora-eager-gc-cp2",
+ "lora_experts-sdpa-gc-cp2",
+ "lora_experts-eager-cp2",
+ "full-eager-gc-dp2xcp2",
+ ],
+)
+def test_kimi_moe_under_ulysses_matches_one_process(precision, attn, gc, world, cp_size):
+ """The parallel_capabilities evidence for Kimi-Linear MoE x context parallel (aux loss off):
+ hub MoE block + gate (in-place score bias), KDA and MLA layers, right padded rows."""
+ _spawn(_moe_worker, world, cp_size, precision, attn, gc)
+
+
+def _pad_route_worker(rank, world, precision, attn, control):
+ """128 experts, right padded rows of a length the CP size divides: caller padding routes through
+ the MoE in one process, so an expert only padding picks has a zero gradient there (None when no
+ token picks it). CP must give padding the same activations, or such experts differ in None vs
+ zero and AdamW decays / steps a different set. Two AdamW steps, then the optimizer state."""
+ import copy
+
+ ad.HAS_FLASH_ATTENTION = False
+ ad.HAS_XFORMERS = False
+ if control:
+ # Negative control: the Ulysses mixers leave padding as the unmasked shards compute it.
+ cp.ContextParallelManager.caller_pad_lengths = lambda self, bsz, total: None
+ model = _model(False, moe = 128, attn = attn).double()
+ if precision != "full":
+ model = _inject_lora(model, experts = True)
+ reference = copy.deepcopy(model)
+ manager = _manager(world, rank)
+ manager.attach_attention_hooks(model)
+ trainable = [p for p in model.parameters() if p.requires_grad]
+ adamw = dict(lr = 1e-2, eps = 1e-4, weight_decay = 0.1)
+ optimizer = torch.optim.AdamW(trainable, **adamw)
+ ref_optimizer = torch.optim.AdamW(
+ [p for p in reference.parameters() if p.requires_grad], **adamw
+ )
+ assert cp.install_idle_expert_grad_hook(optimizer, model)
+ bad, pad_only = [], 0
+ for step in range(2):
+ ids, mask, labels = _audit_batch("full", seed = step, seq = 16)
+ shift = F.pad(labels, (0, 1), value = -100)[:, 1:]
+ count = shift.ne(-100).sum()
+ optimizer.zero_grad(set_to_none = True)
+ ref_optimizer.zero_grad(set_to_none = True)
+ _loss(reference(input_ids = ids, attention_mask = mask).logits, shift, count).backward()
+ # An expert only padding routes to: a gradient of zeros (not None) in one process.
+ pad_only += sum(
+ p.grad is not None and not p.grad.any()
+ for n, p in reference.named_parameters()
+ if ".experts." in n and "lora_B" not in n
+ )
+ inputs = {
+ "input_ids": ids.clone(),
+ "attention_mask": mask.clone(),
+ "labels": labels.clone(),
+ }
+ with manager.apply(inputs):
+ assert manager.caller_pad_lengths(2, 16) == (None if control else (11, 9 - step % 2))
+ out = model(
+ input_ids = inputs["input_ids"],
+ position_ids = inputs["position_ids"],
+ attention_mask = inputs["attention_mask"],
+ )
+ _loss(out.logits, inputs["shift_labels"], count).backward()
+ for param in trainable:
+ dist.all_reduce(param.grad)
+ optimizer.step()
+ ref_optimizer.step()
+ for (name, param), ref in zip(model.named_parameters(), reference.parameters()):
+ if (param.grad is None) != (ref.grad is None):
+ bad.append((step, name, "grad None vs zero"))
+ # The CP scan runs in fp32 (as fla does), the reference in fp64.
+ elif param.grad is not None and not torch.allclose(param.grad, ref.grad, 1e-4, 1e-6):
+ bad.append((step, name, "grad"))
+ if not torch.allclose(param, ref, rtol = 1e-5, atol = 1e-5):
+ bad.append((step, name, "param"))
+ mine, want = optimizer.state.get(param, {}), ref_optimizer.state.get(ref, {})
+ if bool(mine) != bool(want):
+ bad.append((step, name, "AdamW state on one side"))
+ elif mine and (
+ float(mine["step"]) != float(want["step"])
+ or not torch.allclose(mine["exp_avg"], want["exp_avg"], 1e-4, 1e-7)
+ or not torch.allclose(mine["exp_avg_sq"], want["exp_avg_sq"], 1e-3, 1e-12)
+ ):
+ bad.append((step, name, "AdamW state"))
+ assert pad_only, "no padding-only expert: the check proves nothing"
+ assert not bad, f"CP diverges from one process: {len(bad)}, first {bad[:3]}"
+
+
+ "precision, attn, world",
+ [
+ ("full", "sdpa", 2),
+ ("lora_experts", "eager", 2),
+ ("full", "eager", 4),
+ ("lora_experts", "sdpa", 4),
+ ],
+ ids = ["full-sdpa-cp2", "lora_experts-eager-cp2", "full-eager-cp4", "lora_experts-sdpa-cp4"],
+)
+def test_kimi_caller_padding_routes_experts_as_one_process(precision, attn, world):
+ _spawn(_pad_route_worker, world, precision, attn, False)
+
+
[email protected]("world", [2, 4], ids = ["cp2", "cp4"])
+def test_unmasked_caller_padding_misroutes_experts(world):
+ # The control for the test above: without the single-process padding activations it diverges.
+ with pytest.raises(Exception, match = "CP diverges from one process"):
+ _spawn(_pad_route_worker, world, "full", "sdpa", True)
+
+
+def test_flash_caller_padding_rows_are_zero_as_unpadded_flash():
+ # transformers' flash path unpads on the 2D mask and pads the output back with zeros; a sliding
+ # window under sdpa / eager is left as is (documented), real rows never change.
+ out = torch.randn(2, 6, 3, 4)
+ q = k = v = torch.randn(2, 3, 6, 4)
+
+ def never(*args, **kwargs):
+ raise AssertionError("flash rows need no attention call")
+
+ got = uh._caller_padding_rows(out, None, q, k, v, (4, 6), None, "flash_attention_2", never, {})
+ torch.testing.assert_close(got[0, :4], out[0, :4], rtol = 0, atol = 0)
+ assert not got[0, 4:].any()
+ torch.testing.assert_close(got[1], out[1], rtol = 0, atol = 0)
+ assert uh._caller_padding_rows(out, None, q, k, v, (4, 6), 3, "sdpa", never, {}) is out
+
+
+def test_kimi_gates():
+ model = _model(False)
+ kda = model.model.layers[0].self_attn
+ assert uh.is_ulysses_kimi_delta(kda) and uh.is_ulysses_mixer(kda)
+ assert not uh.is_ulysses_gated_delta(kda)
+ assert cp._supports_context_parallel(model, "ulysses")
+ assert not cp._supports_context_parallel(model, "ring")
+ cp._check_stateful_mixers(model, "ulysses", 2)
+ with pytest.raises(ValueError, match = "num_heads"):
+ cp._check_stateful_mixers(model, "ulysses", 8)
+ # MLA runs main's generic Ulysses route: its forward calls ALL_ATTENTION_FUNCTIONS.
+ assert uh.is_hf_registry_attention(model.model.layers[1].self_attn)
+
+ # An attention class next to the delta layers that bypasses the registry still blocks CP.
+ def own_kernel(
+ self,
+ hidden_states,
+ attention_mask = None,
+ **kwargs,
+ ):
+ return hidden_states
+
+ model.model.layers[1].self_attn.__class__ = type(
+ "OtherAttention", (KimiMLAAttention,), {"forward": own_kernel}
+ )
+ assert not cp._supports_context_parallel(model, "ulysses")
+
+
+def test_kimi_delta_refuses_packing_and_cache():
+ kda = _model(False).model.layers[0].self_attn
+ h = torch.zeros(1, 4, HIDDEN)
+ with pytest.raises(NotImplementedError, match = "packing"):
+ uh.ulysses_kimi_delta_forward(kda, h, packed_seq_lengths = torch.tensor([4]), group = None)
+ with pytest.raises(RuntimeError, match = "cache"):
+ uh.ulysses_kimi_delta_forward(kda, h, cache_params = object(), group = None)
+
+
+def test_kimi_delta_gate_matches_fla_reference():
+ f, A_log, dt = torch.randn(1, 3, 2, 4), torch.randn(2), torch.randn(8)
+ x = f + dt.view(2, 4)
+ expected = -A_log.exp().view(2, 1) * F.softplus(x)
+ torch.testing.assert_close(uh._kda_gate(f, A_log, dt, None), expected)
+ expected = -5.0 * torch.sigmoid(A_log.exp().view(2, 1) * x)
+ torch.testing.assert_close(uh._kda_gate(f, A_log, dt, -5.0), expected)
+
+
+def test_moe_unrouted_experts_get_zero_grads_under_context_parallelism(monkeypatch):
+ from unsloth.models.remote_moe_shims import _moe_train_dispatch
+
+ block = nn.Module()
+ block.experts = nn.ModuleList(nn.Linear(4, 4) for _ in range(3))
+ x = torch.randn(2, 4)
+ topk_idx = torch.tensor([[0], [0]]) # experts 1 and 2 get no tokens
+ topk_weight = torch.ones(2, 1)
+
+ _moe_train_dispatch(block, x, topk_idx, topk_weight).sum().backward()
+ assert block.experts[1].weight.grad is None
+
+ block.zero_grad(set_to_none = True)
+ monkeypatch.setattr(cp, "_ACTIVE_MANAGER", object())
+ out = _moe_train_dispatch(block, x, topk_idx, topk_weight)
+ out.sum().backward()
+ for expert in block.experts[1:]:
+ assert expert.weight.grad is not None and not expert.weight.grad.any()
+ torch.testing.assert_close(out, block.experts[0](x))
+
+
+def test_shimmed_remote_moe_is_not_blocked():
+ from unsloth.models.remote_moe_shims import _moe_forward_with_training_path
+
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.experts = nn.ModuleList([nn.Linear(2, 2)])
+
+ def forward(self, x):
+ return x
+
+ model = _model(False)
+ model.moe = Block()
+ assert "sparse MoE" in cp._hybrid_config_blocker(model)
+ Block.forward = _moe_forward_with_training_path(Block.forward)
+ assert cp._hybrid_config_blocker(model) is None
diff --git a/unsloth/context_parallel.py b/unsloth/context_parallel.py
index cb7a6d5d247..27411cfd022 100644
--- a/unsloth/context_parallel.py
+++ b/unsloth/context_parallel.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import contextlib
import functools
import types
+import weakref
from typing import Iterator, Optional
import torch
@@ -209,11 +210,11 @@ from .device_type import DEVICE_TYPE_TORCH
from .utils.ulysses import _document_positions, ulysses_head_plan
from .utils.ulysses_hybrid import (
GATED_DELTA_ATTENTION_CLASSES,
- check_gated_delta_heads,
+ check_ulysses_mixer_heads,
install_hf_attention_wrapper,
is_hf_registry_attention,
- is_ulysses_gated_delta,
- wrap_gated_delta_forward,
+ is_ulysses_mixer,
+ wrap_ulysses_mixer_forward,
)
# shift_labels is built before sharding so each shard's last token keeps its next-token target.
@@ -262,13 +263,156 @@ def _hybrid_config_blocker(model) -> Optional[str]:
if getattr(text_config, "output_router_logits", False):
# The load balancing loss is a product of per-sequence means, not a sum over shards.
return "the MoE router auxiliary loss (output_router_logits)"
- if any(isinstance(getattr(m, "experts", None), torch.nn.ModuleList) for m in model.modules()):
+ if any(
+ isinstance(getattr(m, "experts", None), torch.nn.ModuleList) and not _runs_every_expert(m)
+ for m in model.modules()
+ ):
# Per-expert modules run only for experts the local shard routes to, so with DDP's
# find_unused_parameters off an expert unused on one rank stalls the gradient reduction.
return "sparse MoE layers with per-expert modules (transformers 4.x Qwen3-Next)"
return None
+def _runs_every_expert(block) -> bool:
+ # Unsloth's train-mode remote MoE (Kimi-Linear) gives unrouted experts zero gradients under CP;
+ # expert parallel blocks (ep_size > 1) keep the remote forward, so they do not.
+ if (getattr(block, "ep_size", 1) or 1) > 1:
+ return False
+ return getattr(getattr(type(block), "forward", None), "_unsloth_remote_moe_shim", False)
+
+
+_EXPERT_TOKENS = "_unsloth_cp_expert_tokens"
+_EXPERT_STEPPED = "_unsloth_cp_expert_stepped"
+
+
+def record_expert_tokens(block, token_counts) -> None:
+ # Per-expert routed token counts (no host sync) since its grad was last None; only graph-building
+ # forwards count (checkpoint recompute double counts, harmless since only > 0 matters).
+ if not torch.is_grad_enabled():
+ return
+ if block.__dict__.pop(_EXPERT_STEPPED, False):
+ # First forward after an optimizer step (and the zero_grad after it).
+ start_expert_window([block])
+ seen = block.__dict__.get(_EXPERT_TOKENS)
+ block.__dict__[_EXPERT_TOKENS] = (
+ token_counts.detach().clone() if seen is None else seen.add_(token_counts)
+ )
+
+
+def forget_expert_tokens(block) -> None:
+ # A graph-building forward without context parallelism (e.g. a later trainer reusing the optimizer):
+ # its experts' None gradients are already the single-process ones, so the step must not drop any.
+ block.__dict__.pop(_EXPERT_TOKENS, None)
+ block.__dict__.pop(_EXPERT_STEPPED, None)
+
+
+def start_expert_window(blocks) -> None:
+ """A new gradient window starts (before its first forward): forget the counts of experts whose
+ gradients are None now. zero_grad(set_to_none = True) clears them all, also after a step the
+ optimizer skipped (fp16 GradScaler overflow); with set_to_none = False the single-process run
+ keeps a zero gradient, which AdamW steps, so the count carries over."""
+ for block in blocks:
+ seen = block.__dict__.get(_EXPERT_TOKENS)
+ block.__dict__.pop(_EXPERT_STEPPED, None)
+ if seen is None:
+ continue
+ keep = [
+ any(p.grad is not None for p in expert.parameters() if p.requires_grad)
+ for expert in block.experts
+ ]
+ if not any(keep):
+ del block.__dict__[_EXPERT_TOKENS]
+ elif not all(keep):
+ seen.mul_(torch.tensor(keep, dtype = seen.dtype, device = seen.device))
+
+
+def drop_idle_expert_grads(blocks, group = None) -> int:
+ """Set .grad = None on experts (incl. their LoRA adapters) that no rank routed a real token to
+ since their gradient was last None. Under CP they ran on no tokens so DDP sees a gradient, but
+ the single-process run leaves them None, so AdamW must not decay them or advance their state.
+ One all-reduce and one host sync for all layers. Returns the number of experts dropped.
+ Acts only on blocks a context parallel forward counted since the last step: with CP off (the
+ optimizer reused by a trainer without it) no block is counted and every gradient is kept."""
+ # Counted: a CP forward ran since the last step (it pops _EXPERT_STEPPED) and no non-CP forward
+ # since (forget_expert_tokens). All CP peers run the same forwards, so they agree on the collective.
+ blocks = [
+ b
+ for b in blocks
+ if b.__dict__.get(_EXPERT_TOKENS) is not None and not b.__dict__.get(_EXPERT_STEPPED)
+ ]
+ if not blocks:
+ return 0
+ counts = []
+ for block in blocks:
+ seen = block.__dict__[_EXPERT_TOKENS]
+ # The next forward starts a new window (start_expert_window), after the trainer's zero_grad.
+ block.__dict__[_EXPERT_STEPPED] = True
+ counts.append(seen.to(torch.long))
+ device = counts[0].device
+ total = torch.cat([c.to(device) for c in counts])
+ if dist.is_available() and dist.is_initialized():
+ dist.all_reduce(total, group = group)
+ idle = total.eq(0).tolist()
+ dropped = 0
+ offset = 0
+ for block in blocks:
+ for expert_index, expert in enumerate(block.experts):
+ if idle[offset + expert_index]:
+ for param in expert.parameters():
+ param.grad = None
+ dropped += 1
+ offset += len(block.experts)
+ return dropped
+
+
+def install_idle_expert_grad_hook(
+ optimizer,
+ model,
+ group = None,
+ window = None,
+) -> bool:
+ """Once per optimizer: a step pre-hook running drop_idle_expert_grads over model's every-expert
+ MoE blocks. It runs after backward (DDP reduction) and all gradient accumulation micro-steps.
+ ``window`` (the trainer's global_step, read per training_step) starts a new count window when it
+ changes: it advances even when GradScaler skips optimizer.step() and with it the pre-hook."""
+ while not isinstance(optimizer, torch.optim.Optimizer) or (
+ # accelerate's AcceleratedOptimizer subclasses Optimizer but steps the one it wraps.
+ isinstance(getattr(optimizer, "optimizer", None), torch.optim.Optimizer)
+ ):
+ optimizer = getattr(optimizer, "optimizer", None)
+ if optimizer is None:
+ return False
+ blocks = optimizer.__dict__.get("_unsloth_idle_expert_blocks")
+ if blocks is None:
+ if not isinstance(model, torch.nn.Module):
+ return False
+ found = [
+ m
+ for m in model.modules()
+ if isinstance(getattr(m, "experts", None), torch.nn.ModuleList)
+ and _runs_every_expert(m)
+ ]
+ if not found:
+ return False
+ blocks = [weakref.ref(b) for b in found]
+
+ def hook(_optimizer, _args, _kwargs):
+ drop_idle_expert_grads([b for b in (ref() for ref in blocks) if b is not None], group)
+
+ optimizer.__dict__["_unsloth_idle_expert_blocks"] = blocks
+ optimizer.__dict__["_unsloth_idle_expert_hook"] = optimizer.register_step_pre_hook(hook)
+ if window is not None and optimizer.__dict__.get("_unsloth_idle_expert_window") != window:
+ optimizer.__dict__["_unsloth_idle_expert_window"] = window
+ start_expert_window([b for b in (ref() for ref in blocks) if b is not None])
+ return True
+
+
+def _optimizer_window(trainer):
+ # Trainer.state.global_step: constant over a step's gradient accumulation micro-batches, advanced
+ # once per optimizer step attempt (also one GradScaler skips).
+ return getattr(getattr(trainer, "state", None), "global_step", None)
+
+
def _attention_modules(model) -> list:
if not hasattr(model, "named_modules"):
return []
@@ -307,8 +451,11 @@ def _supports_context_parallel(
mixers = _stateful_mixers(model)
if mixers:
# Hybrids: the family-specific linear attention forwards, and their HF full attention layers.
- return all(is_ulysses_gated_delta(m) for m, _ in mixers) and all(
- type(m).__name__ in GATED_DELTA_ATTENTION_CLASSES for m in _attention_modules(model)
+ # Kimi-Linear names its delta attention layers self_attn too; its MLA layers are generic HF attention.
+ return all(is_ulysses_mixer(m) for m, _ in mixers) and all(
+ type(m).__name__ in GATED_DELTA_ATTENTION_CLASSES or is_hf_registry_attention(m)
+ for m in _attention_modules(model)
+ if not is_ulysses_mixer(m)
)
return generic and _generic_hf_attention(model)
@@ -323,14 +470,14 @@ def _check_stateful_mixers(model, backend, size) -> None:
f"Unsloth: ring context parallelism cannot split the sequential scans of {kinds}; "
"use context_parallel_backend = 'ulysses'."
)
- unsupported = sorted({type(m).__name__ for m, _ in mixers if not is_ulysses_gated_delta(m)})
+ unsupported = sorted({type(m).__name__ for m, _ in mixers if not is_ulysses_mixer(m)})
if unsupported:
raise NotImplementedError(
- "Unsloth: Ulysses context parallelism supports Gated DeltaNet linear attention only, "
- f"not {unsupported}."
+ "Unsloth: Ulysses context parallelism supports Gated DeltaNet and Kimi delta "
+ f"linear attention only, not {unsupported}."
)
for module, _ in mixers:
- check_gated_delta_heads(module, size)
+ check_ulysses_mixer_heads(module, size)
def _self_attn_pre_forward_hook(_module, module_args, module_kwargs):
@@ -394,10 +541,16 @@ class ContextParallelManager:
return self.mesh.get_group()
def attach_attention_hooks(self, model: torch.nn.Module) -> None:
+ if any(
+ isinstance(getattr(m, "experts", None), torch.nn.ModuleList) and _runs_every_expert(m)
+ for m in model.modules()
+ ):
+ # Caller padding counts as expert usage in one process, so the mixers keep its activations.
+ self._match_caller_padding = True
if self.backend == "ulysses":
for module, _ in _stateful_mixers(model):
- if is_ulysses_gated_delta(module):
- wrap_gated_delta_forward(module, get_cp_manager)
+ if is_ulysses_mixer(module):
+ wrap_ulysses_mixer_forward(module, get_cp_manager)
# Fast forwards exchange inside run_attention; other HF layers run their attention after the exchange.
generic = not _uses_unsloth_attention(model)
for name, module in model.named_modules():
@@ -500,6 +653,10 @@ class ContextParallelManager:
labels = mask_packed_boundary_labels(labels, packed_seq_lengths)
inputs["shift_labels"] = F.pad(labels, (0, 1), value = -100)[:, 1:].contiguous()
pad = (-seq_len) % (self.size if ulysses else 2 * self.size)
+ padded = self.__dict__.get("_padded_input_ids")
+ if not pad and padded is not None and padded[0]() is input_ids:
+ return # prepared already (prediction_step, then apply): keep the real length
+ self._padded_input_ids = None
if pad:
for name in _BUFFER_NAMES:
tensor = inputs.get(name)
@@ -510,6 +667,64 @@ class ContextParallelManager:
inputs[name] = torch.cat([tensor, extra.to(tensor.dtype)], dim = 1)
else:
inputs[name] = F.pad(tensor, (0, pad), value = _PAD_VALUES.get(name, 0))
+ # The appended tokens are not in the single-process batch: the MoE must not count their routes.
+ self._padded_input_ids = (weakref.ref(inputs["input_ids"]), seq_len)
+
+ def _real_tokens(self, input_ids) -> Optional[torch.Tensor]:
+ # [batch, padded seq] True on tokens of the caller's batch, None when nothing was appended.
+ padded = self.__dict__.get("_padded_input_ids")
+ if padded is None or padded[0]() is not input_ids:
+ return None
+ positions = torch.arange(input_ids.shape[1], device = input_ids.device)
+ return positions.lt(padded[1]).expand(input_ids.shape[0], -1).contiguous()
+
+ def _note_real_tokens(self, local_ids, local) -> None:
+ # Keyed by the shard's token count, which is all the MoE dispatch sees. Graph-building forwards
+ # of one size are OR-ed (local None = all real): a pad token counted as real only keeps a zero
+ # gradient, while a real token counted as pad would drop a real one.
+ if not isinstance(local_ids, torch.Tensor) or not torch.is_grad_enabled():
+ return
+ masks = self.__dict__.setdefault("_real_token_masks", {})
+ key = local_ids.numel()
+ flat = None if local is None else local.reshape(-1)
+ if key not in masks:
+ masks[key] = flat
+ elif masks[key] is not None:
+ masks[key] = None if flat is None else masks[key] | flat
+
+ def real_token_mask(self, num_tokens: int) -> Optional[torch.Tensor]:
+ """Flat [num_tokens] bool mask of the local shard's tokens that are in the caller's batch (not
+ context parallel padding), or None when all are. Valid through backward, for recompute."""
+ return self.__dict__.get("_real_token_masks", {}).get(num_tokens)
+
+ def _clear_real_tokens(self) -> None:
+ self.__dict__.pop("_real_token_masks", None)
+ self.__dict__.pop("_caller_pad_lengths", None)
+
+ def _note_caller_padding(self, mask) -> None:
+ # Real length per row of the caller's mask, keyed by the full sequence shape the mixers see.
+ if not getattr(self, "_match_caller_padding", False) or not isinstance(mask, torch.Tensor):
+ return
+ if mask.ndim != 2:
+ return
+ padded = self.__dict__.get("_padded_input_ids")
+ caller_len = mask.shape[1] if padded is None else padded[1]
+ lengths = tuple(int(n) for n in mask.ne(0).sum(1).tolist())
+ if all(n >= caller_len for n in lengths):
+ return # no caller padding: the appended tokens are not counted (real_token_mask)
+ store = self.__dict__.setdefault("_caller_pad_lengths", {})
+ key = tuple(mask.shape)
+ seen = store.get(key)
+ # Same shape, different padding in one step: the longer length never treats a real token as pad.
+ store[key] = lengths if seen is None else tuple(max(a, b) for a, b in zip(seen, lengths))
+
+ def caller_pad_lengths(self, bsz: int, total: int) -> Optional[tuple]:
+ """Per row, how many leading tokens of the whole [bsz, total] sequence are the caller's real
+ tokens (the rest is right padding), or None when no row is padded. Set only for models whose
+ MoE counts expert usage (the remote shim): one process routes caller padding through the MoE
+ with its own activations (Kimi delta layers zero it, attention masks the padded keys), so the
+ Ulysses mixers reproduce them for the routes, and the expert counts, to match."""
+ return self.__dict__.get("_caller_pad_lengths", {}).get((bsz, total))
@contextlib.contextmanager
def _rotate_method_scope(self) -> Iterator[None]:
@@ -532,11 +747,17 @@ class ContextParallelManager:
def _ulysses_shard(self, inputs: dict) -> None:
# Contiguous shards; packed_seq_lengths stays global.
rank = self.mesh.get_local_rank()
+ self._note_caller_padding(inputs.get("attention_mask"))
+ real = self._real_tokens(inputs.get("input_ids"))
+ if real is not None:
+ local = real.shape[1] // self.size
+ real = real[:, rank * local : (rank + 1) * local]
for name in _BUFFER_NAMES:
tensor = inputs.get(name)
if isinstance(tensor, torch.Tensor) and tensor.ndim > 1:
local = tensor.shape[1] // self.size
inputs[name] = tensor[:, rank * local : (rank + 1) * local].contiguous()
+ self._note_real_tokens(inputs.get("input_ids"), real)
@contextlib.contextmanager
def _ulysses_scope(self, inputs: dict) -> Iterator[None]:
@@ -561,6 +782,15 @@ class ContextParallelManager:
@contextlib.contextmanager
def apply(self, inputs: dict) -> Iterator[None]:
self._prepare_inputs(inputs)
+ self._clear_real_tokens()
+ try:
+ with self._apply(inputs):
+ yield
+ finally:
+ self._clear_real_tokens()
+
+ @contextlib.contextmanager
+ def _apply(self, inputs: dict) -> Iterator[None]:
if self.backend == "ulysses":
with self._ulysses_scope(inputs):
yield
@@ -570,6 +800,9 @@ class ContextParallelManager:
for name in _BUFFER_NAMES
if isinstance(inputs.get(name), torch.Tensor) and inputs[name].ndim > 1
]
+ real = self._real_tokens(inputs.get("input_ids"))
+ if real is not None:
+ buffers.append(real) # sharded in place with the batch's load-balanced layout
global _ACTIVE_MANAGER
previous, _ACTIVE_MANAGER = _ACTIVE_MANAGER, self
# torch < 2.13 leaves its CP dispatcher installed when the step raises.
@@ -595,6 +828,7 @@ class ContextParallelManager:
no_restore_buffers = set(buffers),
),
):
+ self._note_real_tokens(inputs.get("input_ids"), real)
yield
except BaseException:
raised = True
@@ -1257,13 +1491,14 @@ def _check_cp_model(
ulysses_head_plan(heads // tp, kv_heads // tp if kv_heads % tp == 0 else kv_heads, size)
if _stateful_mixers(model) and not allow_hybrids:
raise NotImplementedError(
- "Unsloth: DPO / GRPO context parallelism does not support Gated DeltaNet hybrids yet."
+ "Unsloth: DPO / GRPO context parallelism does not support linear attention hybrids yet."
)
_check_stateful_mixers(model, backend, size)
blocker = _hybrid_config_blocker(model) if _stateful_mixers(model) else None
if blocker is not None:
raise NotImplementedError(
- f"Unsloth: context parallelism on Gated DeltaNet hybrids does not support {blocker}."
+ "Unsloth: context parallelism on linear attention hybrids does not support "
+ f"{blocker}."
)
blocker = _hybrid_config_blocker(model) if generic else None
if blocker is not None:
@@ -1287,7 +1522,7 @@ def _check_cp_model(
"Unsloth: context parallelism supports Unsloth's fast attention (Llama-style, Qwen3, Mistral, Granite, "
"Cohere) with either backend, "
"and with Ulysses any Hugging Face attention model (attention through ALL_ATTENTION_FUNCTIONS) "
- "and the Qwen3-Next / Qwen3.5 Gated DeltaNet hybrids."
+ "and the Qwen3-Next / Qwen3.5 Gated DeltaNet and Kimi-Linear hybrids."
)
@@ -1669,6 +1904,11 @@ def patch_sft_trainer(install_cp_methods: bool = False) -> None:
# Without gradient checkpointing the model would build a cache for the sharded scans.
if hasattr(inputs, "setdefault"):
inputs.setdefault("use_cache", False)
+ install_idle_expert_grad_hook(
+ getattr(self, "optimizer", None),
+ getattr(self, "model", None),
+ window = _optimizer_window(self),
+ )
# Forward and backward both inside, so gradient checkpointing recomputes with ring attention.
with manager.apply(inputs) if manager else contextlib.nullcontext():
return original_training_step(self, model, inputs, *args, **kwargs)
@@ -2179,9 +2419,17 @@ def patch_rl_trainer(trainer_cls, kind: str) -> None:
return original(self, *args, **kwargs)
for decoder in _decoders(self.model):
decoder._unsloth_cp_rl_stack.clear()
+ if name == "training_step":
+ install_idle_expert_grad_hook(
+ getattr(self, "optimizer", None), self.model, window = _optimizer_window(self)
+ )
# Backward, and checkpoint recompute in it, run Ulysses attention too, so the scope spans them.
- with _manager_scope(manager if activate_at_step else None):
- return original(self, *args, **kwargs)
+ manager._clear_real_tokens()
+ try:
+ with _manager_scope(manager if activate_at_step else None):
+ return original(self, *args, **kwargs)
+ finally:
+ manager._clear_real_tokens()
return wrapped
diff --git a/unsloth/models/remote_moe_shims.py b/unsloth/models/remote_moe_shims.py
index 68cee7d811c..3d1ed3c683f 100644
--- a/unsloth/models/remote_moe_shims.py
+++ b/unsloth/models/remote_moe_shims.py
@@ -13,6 +13,7 @@
"""Train-mode forwards for DeepSeek-V3-derived remote MoE ports, keyed on structure never repo name;
no-op for the native transformers models."""
+import contextlib
import functools
import os
import threading
@@ -133,17 +134,50 @@ def is_remote_deepseek_moe(module) -> bool:
)
+_ROUTER_SCORE_FUNCTIONS = frozenset(
+ (
+ torch.sigmoid,
+ torch.Tensor.sigmoid,
+ torch.special.expit,
+ torch.softmax,
+ torch.Tensor.softmax,
+ torch.nn.functional.softmax,
+ )
+)
+
+
+class _CopyRouterScores(torch.overrides.TorchFunctionMode):
+ """Kimi-Linear adds its score bias in place to the sigmoid / softmax output that op's backward
+ saved: hand the gate a copy instead. Only the scores are copied and no saved-tensor hooks are
+ pushed, so gradient checkpointing and activation offload still own the gate's saved tensors."""
+
+ def __torch_function__(
+ self,
+ func,
+ types,
+ args = (),
+ kwargs = None,
+ ):
+ out = func(*args, **(kwargs or {}))
+ if func in _ROUTER_SCORE_FUNCTIONS and isinstance(out, torch.Tensor) and out.requires_grad:
+ out = out.clone()
+ return out
+
+
def _gate_forward_without_training_assert(original):
@functools.wraps(original)
def forward(self, hidden_states):
- if not self.training:
- return original(self, hidden_states)
- # Gate has no children: flipping `training` only bypasses the assert.
- self.training = False
- try:
- return original(self, hidden_states)
- finally:
- self.training = True
+ # The block shim calls the gate with training already off, so this covers both paths.
+ copies = _CopyRouterScores() if torch.is_grad_enabled() else contextlib.nullcontext()
+ with copies:
+ if not self.training:
+ return original(self, hidden_states)
+ # Gate has no children: flipping `training` only bypasses the assert.
+ self.training = False
+ try:
+ return original(self, hidden_states)
+ finally:
+ self.training = True
forward._unsloth_remote_moe_shim = True
return forward
@@ -169,11 +203,37 @@ def _moe_train_dispatch(block, x, topk_idx, topk_weight):
flat_idx = topk_idx.reshape(-1)
order = torch.argsort(flat_idx, stable = True)
sorted_tokens = x[order // top_k]
- counts = torch.bincount(flat_idx, minlength = len(experts)).tolist()
+ token_counts = torch.bincount(flat_idx, minlength = len(experts))
+ counts = token_counts.tolist()
+ # Under context parallelism each rank routes a different shard, so an expert unused here may be
+ # used on a peer: run it on no tokens to give it a zero gradient instead of None, or DDP stalls.
+ from ..context_parallel import forget_expert_tokens, get_cp_manager, record_expert_tokens
+
+ manager = get_cp_manager()
+ every_expert = manager is not None
+ if not every_expert and torch.is_grad_enabled():
+ # Without CP an unrouted expert keeps its None gradient: the step must not drop the others.
+ forget_expert_tokens(block)
+ if every_expert:
+ # Lets the step drop zero grads of experts no rank routed to. CP-appended padding is excluded; caller
+ # padding counts (the Ulysses mixers route it as one process does).
+ real_token_mask = getattr(manager, "real_token_mask", None)
+ real = real_token_mask(num_tokens) if callable(real_token_mask) else None
+ if real is not None:
+ real = real.to(flat_idx.device).unsqueeze(1).expand(-1, top_k).reshape(-1)
+ unreal = len(experts) # pad routes go to an extra bin, dropped below (no host sync)
+ token_counts_real = torch.bincount(
+ flat_idx.masked_fill(~real, unreal), minlength = unreal + 1
+ )[:unreal]
+ else:
+ token_counts_real = token_counts
+ record_expert_tokens(block, token_counts_real)
outputs = []
start = 0
for expert_index, count in enumerate(counts):
if count == 0:
+ if every_expert:
+ outputs.append(experts[expert_index](sorted_tokens[:0]))
continue
expert = experts[expert_index]
outputs.append(expert(sorted_tokens[start : start + count]))
@@ -256,7 +316,8 @@ def prepare_remote_moe_for_training(model, verbose = True):
shimmed_classes.add(cls)
_rebind_accelerate_hook(module)
continue
- if is_remote_deepseek_gate(module) and cls in shimmable_gates:
+ # Renamed ports (Kimi-Linear's KimiMoEGate) are matched through their inference-only block.
+ if cls in shimmable_gates and _is_remote_code(cls):
cls.forward = _gate_forward_without_training_assert(cls.forward)
patched.append(cls.__name__)
shimmed_classes.add(cls)
diff --git a/unsloth/parallel_capabilities.py b/unsloth/parallel_capabilities.py
index 29657ce3d39..6596ba24c6b 100644
--- a/unsloth/parallel_capabilities.py
+++ b/unsloth/parallel_capabilities.py
@@ -850,6 +850,12 @@ _MOE_COMPILE = _GLOO + "test_moe_block_compile_under_cp_is_compile_clean"
_MOE_CP_GC = "test_moe_under_cp_with_unsloth_checkpointing_matches_one_process"
_MOE_CP_GC_COMPILE = "test_moe_block_compile_under_cp_with_unsloth_checkpointing_is_compile_clean"
_MOE_PP = "tests/test_pp_moe_aux_gloo.py::test_pp2_moe_aux_matches_gradient_accumulation"
+# Kimi-Linear (remote code): KDA + MLA layers and the hub MoE block / gate under Unsloth's shim, right padded rows,
+# fp64 against one process, the idle-expert hook and one AdamW step. HF checkpointing only (no Unsloth checkpoint run).
+_KIMI_MOE = "tests/test_ulysses_kimi.py::test_kimi_moe_under_ulysses_matches_one_process"
+_KIMI_EAGER = "eager: remote code, no compiled region"
+# Families whose cp rows also ran Unsloth's checkpoint (path A and B); the others match HF checkpointing only.
+_MOE_UNSLOTH_GC_FAMILIES = ("qwen3_moe",)
# (family, precision, aux, mode) -> (parity, engagement, compile) for the rows a test proves.
_MOE_EVIDENCE = {
("qwen3_moe", "lora+experts", False, "ddp"): (_MOE_TEST + "[lora-ddp]",) * 2
@@ -880,6 +886,14 @@ _MOE_EVIDENCE = {
+ ("eager: no compiled region",),
("qwen3_moe", "lora+experts", False, "pp"): (_MOE_PP + "[lora_aux_off_1f1b_mask]",) * 2
+ ("eager: no compiled region",),
+ ("kimi_linear", "full", False, "cp"): (_KIMI_MOE + "[full-sdpa-cp2|full-eager-gc-dp2xcp2]",) * 2
+ + (_KIMI_EAGER,),
+ ("kimi_linear", "lora", False, "cp"): (_KIMI_MOE + "[lora-eager-gc-cp2]",) * 2 + (_KIMI_EAGER,),
+ ("kimi_linear", "lora+experts", False, "cp"): (
+ _KIMI_MOE + "[lora_experts-sdpa-gc-cp2|lora_experts-eager-cp2]",
+ )
+ * 2
+ + (_KIMI_EAGER,),
}
@@ -939,7 +953,7 @@ def _moe_cells():
name = f"MoE {family} x {precision} x aux {'on' if aux else 'off'} x {mode}"
if evidence:
note = compiled_note = ""
- if mode in ("cp", "fsdp2_cp"):
+ if mode in ("cp", "fsdp2_cp") and family in _MOE_UNSLOTH_GC_FAMILIES:
match = {**match, "memory": _WITH_UNSLOTH_GC}
case = f"{precision.split('+')[0]}-{mode}2" # lora-cp2, lora-fsdp2_cp2, full-cp2
note = (
@@ -950,6 +964,18 @@ def _moe_cells():
# No evidence run swapped layers; block swap x tp / pp is its own cell.
match = {**match, "block_swap": (False,)}
cells.append(Cell(name, match, *evidence, note = note))
+ if mode in ("cp", "fsdp2_cp") and family not in _MOE_UNSLOTH_GC_FAMILIES:
+ cells.append(
+ Cell(
+ name + ", Unsloth checkpoint",
+ {**match, "memory": ("unsloth_offload",)},
+ None,
+ None,
+ None,
+ note = "only HF gradient checkpointing ran under cp for this family; "
+ "use_gradient_checkpointing = True (not 'unsloth') runs the measured cell",
+ )
+ )
if not evidence[2].startswith("eager:"):
cells.append(
Cell(
diff --git a/unsloth/utils/ulysses_hybrid.py b/unsloth/utils/ulysses_hybrid.py
index f66fe36048f..69fbcf1b2d4 100644
--- a/unsloth/utils/ulysses_hybrid.py
+++ b/unsloth/utils/ulysses_hybrid.py
@@ -2,8 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
"""Ulysses context parallelism for Hugging Face attention (any model whose attention calls ALL_ATTENTION_FUNCTIONS
-runs its own attention function after the exchange) and for hybrid models, whose scans need the full sequence so
-they run on heads."""
+runs its own attention function after the exchange) and for hybrid models (Gated DeltaNet, Kimi delta attention),
+whose scans need the full sequence so they run on heads."""
import builtins
import functools
@@ -18,9 +18,14 @@ from .ulysses import _AllToAll
__all__ = [
"GATED_DELTA_ATTENTION_CLASSES",
"is_ulysses_gated_delta",
+ "is_ulysses_kimi_delta",
+ "is_ulysses_mixer",
"check_gated_delta_heads",
+ "check_ulysses_mixer_heads",
"ulysses_gated_delta_forward",
+ "ulysses_kimi_delta_forward",
"wrap_gated_delta_forward",
+ "wrap_ulysses_mixer_forward",
"install_hf_attention_wrapper",
"is_hf_registry_attention",
"hf_attention_forward",
@@ -42,6 +47,19 @@ def is_ulysses_gated_delta(module) -> bool:
return all(hasattr(module, n) for n in ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a"))
+def is_ulysses_kimi_delta(module) -> bool:
+ if type(module).__name__ != "KimiDeltaAttention":
+ return False
+ needed = ("q_proj", "k_proj", "v_proj", "q_conv1d", "k_conv1d", "v_conv1d", "A_log", "dt_bias")
+ if not all(hasattr(module, n) for n in needed + ("b_proj", "o_norm", "o_proj")):
+ return False
+ return hasattr(module, "f_a_proj") or hasattr(module, "f_proj")
+
+
+def is_ulysses_mixer(module) -> bool:
+ return is_ulysses_gated_delta(module) or is_ulysses_kimi_delta(module)
+
+
def check_gated_delta_heads(module, cp_size) -> None:
for name in ("num_k_heads", "num_v_heads"):
heads = getattr(module, name)
@@ -52,6 +70,16 @@ def check_gated_delta_heads(module, cp_size) -> None:
)
+def check_ulysses_mixer_heads(module, cp_size) -> None:
+ if not is_ulysses_kimi_delta(module):
+ return check_gated_delta_heads(module, cp_size)
+ if module.num_heads % cp_size != 0:
+ raise ValueError(
+ f"Unsloth: Ulysses context parallelism needs Kimi delta attention num_heads "
+ f"({module.num_heads}) to be divisible by context_parallel_size ({cp_size})."
+ )
+
+
def _kernel_params(fn):
# transformers' hub wrapper silently drops keyword arguments its bound implementation does not name.
from .packing import _hub_closure
@@ -211,7 +239,187 @@ def ulysses_gated_delta_forward(
return module.out_proj(out.reshape(bsz, local_len, -1))
-def wrap_gated_delta_forward(module, get_cp_manager) -> None:
[email protected]_cache(maxsize = 1)
+def _fla_causal_conv1d():
+ # fla moved the functional conv between releases.
+ try:
+ from fla.modules.conv.causal_conv1d import causal_conv1d
+ return causal_conv1d
+ except ImportError:
+ pass
+ try:
+ from fla.modules.convolution import causal_conv1d
+ return causal_conv1d
+ except ImportError:
+ return None
+
+
+def _kda_short_conv(conv, x, rows):
+ """Causal depthwise conv (+ SiLU) of a fla ShortConvolution on this rank's channels. x [B, T, C]."""
+ weight = conv.weight.squeeze(1).index_select(0, rows)
+ bias = None if conv.bias is None else conv.bias.index_select(0, rows)
+ activation = getattr(conv, "activation", "silu")
+ causal_conv1d = _fla_causal_conv1d() if x.is_cuda else None
+ if causal_conv1d is not None:
+ try:
+ out = causal_conv1d(
+ x = x.contiguous(),
+ weight = weight.contiguous(),
+ bias = bias,
+ initial_state = None,
+ output_final_state = False,
+ activation = activation,
+ )
+ return out[0] if isinstance(out, tuple) else out
+ except TypeError:
+ pass # another fla signature: the torch conv below is exact, only slower
+ out = F.conv1d(
+ x.transpose(1, 2).to(weight.dtype),
+ weight.unsqueeze(1),
+ bias,
+ padding = weight.shape[-1] - 1,
+ groups = weight.shape[0],
+ )[..., : x.shape[1]].transpose(1, 2)
+ return F.silu(out) if activation in ("silu", "swish") else out
+
+
+def _kda_gate(f, A_log, dt_bias, lower_bound):
+ """KDA per-channel log decay [B, T, H, K] in fp32 (fla naive_kda_gate / naive_kda_lowerbound_gate)."""
+ heads, dim = f.shape[-2:]
+ a = A_log.reshape(1, 1, heads, 1).float().exp()
+ g = f.float() + dt_bias.reshape(1, 1, heads, dim).float()
+ if lower_bound is not None:
+ # Kimi K3 bounds the decay: lower_bound * sigmoid(exp(A_log) * (f + dt_bias)).
+ return lower_bound * torch.sigmoid(a * g)
+ return -a * F.softplus(g)
+
+
+def _torch_kda(q, k, v, g, beta):
+ """Exact token-by-token KDA delta rule (CPU reference).
+
+ q, k, g [B, T, H, K]; v [B, T, H, V]; beta [B, T, H].
+ """
+ # fla's use_qk_l2norm_in_kernel: x * rsqrt(sum(x ** 2) + 1e-6), not F.normalize.
+ q, k = q.float(), k.float()
+ q = q * torch.rsqrt(q.pow(2).sum(-1, keepdim = True) + 1e-6) * q.shape[-1] ** -0.5
+ k = k * torch.rsqrt(k.pow(2).sum(-1, keepdim = True) + 1e-6)
+ v, g, beta = v.float(), g.float(), beta.float()
+ state = q.new_zeros(q.shape[0], q.shape[2], q.shape[3], v.shape[3])
+ outs = []
+ for t in range(q.shape[1]):
+ state = state * g[:, t].exp().unsqueeze(-1)
+ delta = beta[:, t, :, None] * (v[:, t] - torch.einsum("bhk,bhkv->bhv", k[:, t], state))
+ state = state + torch.einsum("bhk,bhv->bhkv", k[:, t], delta)
+ outs.append(torch.einsum("bhk,bhkv->bhv", q[:, t], state))
+ return torch.stack(outs, dim = 1)
+
+
+def _kda_scan(q, k, v, g, beta):
+ if q.is_cuda:
+ try:
+ from fla.ops.kda import chunk_kda
+ except ImportError:
+ chunk_kda = None
+ if chunk_kda is not None:
+ # g is the finished log decay, so the kernel's own gate is left off.
+ out, _ = chunk_kda(
+ q = q.contiguous(),
+ k = k.contiguous(),
+ v = v.contiguous(),
+ g = g.contiguous(),
+ beta = beta.contiguous(),
+ initial_state = None,
+ output_final_state = False,
+ use_qk_l2norm_in_kernel = True,
+ )
+ return out
+ return _torch_kda(q, k, v, g, beta).to(v.dtype)
+
+
+def _caller_pad_lengths(manager, bsz, total):
+ lookup = getattr(manager, "caller_pad_lengths", None)
+ return lookup(bsz, total) if callable(lookup) else None
+
+
+def _real_positions(lengths, positions):
+ # [bsz, len(positions)] True where the position is one of the row's caller tokens.
+ limit = torch.tensor(lengths, device = positions.device)
+ return positions[None, :] < limit[:, None]
+
+
+def ulysses_kimi_delta_forward(
+ module,
+ hidden_states,
+ attention_mask = None,
+ cache_params = None,
+ *,
+ group,
+ caller_lengths = None,
+ **kwargs,
+):
+ """Training forward of a Kimi-Linear / Kimi K3 KimiDeltaAttention on a contiguous sequence shard.
+ caller_lengths (per row, the real length of the whole sequence): the output is zero past it, as the
+ hub layer's pad_input leaves caller padding when it unpads on the 2D mask."""
+ if cache_params is not None:
+ raise RuntimeError("Unsloth: Ulysses context parallelism does not support a cache.")
+ if kwargs.get("packed_seq_lengths") is not None or kwargs.get("cu_seqlens") is not None:
+ raise NotImplementedError(
+ "Unsloth: Ulysses context parallelism does not support packing for Kimi delta "
+ "attention."
+ )
+ if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:
+ mask = attention_mask[:, -hidden_states.shape[1] :, None]
+ hidden_states = (hidden_states * mask).to(hidden_states.dtype)
+
+ size = dist.get_world_size(group)
+ rank = dist.get_rank(group)
+ check_ulysses_mixer_heads(module, size)
+ bsz, local_len, _ = hidden_states.shape
+ total = local_len * size
+ heads, dim = module.num_heads // size, module.head_dim
+
+ q = module.q_proj(hidden_states)
+ k = module.k_proj(hidden_states)
+ v = module.v_proj(hidden_states)
+ if hasattr(module, "f_a_proj"):
+ f = module.f_b_proj(module.f_a_proj(hidden_states))
+ else:
+ f = module.f_proj(hidden_states)
+ b = module.b_proj(hidden_states)
+ # Kimi-Linear projects the output gate through a low rank; K3 (use_full_rank_gate) does not.
+ if hasattr(module, "g_a_proj"):
+ gate = module.g_b_proj(module.g_a_proj(hidden_states))
+ else:
+ gate = module.g_proj(hidden_states)
+
+ pieces = [x.reshape(bsz, local_len, size, -1) for x in (q, k, v, f, b)]
+ widths = [p.shape[-1] for p in pieces]
+ mixed = _AllToAll.apply(torch.cat(pieces, dim = -1), 2, 1, group).squeeze(2)
+ q, k, v, f, b = torch.split(mixed, widths, dim = -1)
+
+ rows = torch.arange(rank * heads * dim, (rank + 1) * heads * dim, device = q.device)
+ q = _kda_short_conv(module.q_conv1d, q, rows).reshape(bsz, total, heads, dim)
+ k = _kda_short_conv(module.k_conv1d, k, rows).reshape(bsz, total, heads, dim)
+ v = _kda_short_conv(module.v_conv1d, v, rows).reshape(bsz, total, heads, dim)
+
+ g = _kda_gate(
+ f.reshape(bsz, total, heads, dim),
+ module.A_log.reshape(-1)[rank * heads : (rank + 1) * heads],
+ module.dt_bias.reshape(-1).index_select(0, rows),
+ getattr(module, "gate_lower_bound", None),
+ )
+ out = _kda_scan(q, k, v, g, b.float().sigmoid())
+ out = _AllToAll.apply(out.reshape(bsz, total, heads, dim), 1, 2, group)
+
+ out = module.o_norm(out, gate.reshape(bsz, local_len, -1, dim))
+ out = module.o_proj(out.reshape(bsz, local_len, -1))
+ if caller_lengths is not None:
+ local = torch.arange(rank * local_len, (rank + 1) * local_len, device = out.device)
+ out = out.masked_fill(~_real_positions(caller_lengths, local)[..., None], 0)
+ return out
+
+
+def _wrap_ulysses_forward(module, get_cp_manager, name) -> None:
if getattr(module, "_unsloth_cp_orig_forward", None) is not None:
return
forward = module.forward
@@ -225,12 +433,29 @@ def wrap_gated_delta_forward(module, get_cp_manager) -> None:
packed = getattr(manager, "packed_seq_lengths", None)
if packed is not None:
kwargs["packed_seq_lengths"] = packed
- return ulysses_gated_delta_forward(module, *args, group = manager.group, **kwargs)
+ if name == "ulysses_kimi_delta_forward":
+ hidden = kwargs.get("hidden_states", args[0] if args else None)
+ if isinstance(hidden, torch.Tensor) and hidden.ndim == 3:
+ kwargs["caller_lengths"] = _caller_pad_lengths(
+ manager, hidden.shape[0], hidden.shape[1] * manager.size
+ )
+ # Looked up per call so tests can substitute the exchange.
+ return globals()[name](module, *args, group = manager.group, **kwargs)
module._unsloth_cp_orig_forward = forward
module.forward = wrapped
+def wrap_gated_delta_forward(module, get_cp_manager) -> None:
+ _wrap_ulysses_forward(module, get_cp_manager, "ulysses_gated_delta_forward")
+
+
+def wrap_ulysses_mixer_forward(module, get_cp_manager) -> None:
+ if is_ulysses_kimi_delta(module):
+ return _wrap_ulysses_forward(module, get_cp_manager, "ulysses_kimi_delta_forward")
+ return wrap_gated_delta_forward(module, get_cp_manager)
+
+
# Keyword arguments that describe the local sequence shard: rebuilt for the whole sequence after the exchange.
_SHARD_LOCAL_KWARGS = (
"position_ids",
@@ -397,6 +622,7 @@ def _ulysses_hf_attention(
attention_fn,
implementation,
packed_seq_lengths = None,
+ caller_lengths = None,
**kwargs,
):
"""Ulysses around the model's own attention function: q / k / v go from sequence shards to head shards,
@@ -461,9 +687,56 @@ def _ulysses_hf_attention(
out, _ = attention_fn(shard, query, key, value, mask, **kwargs)
# [B, T, H / N, D] -> [B, T / N, H, D]
out = out.reshape(bsz, total, plan.local_heads, -1)
+ if caller_lengths is not None and cu_seqlens is None:
+ out = _caller_padding_rows(
+ out,
+ shard,
+ query,
+ key,
+ value,
+ caller_lengths,
+ window,
+ implementation,
+ attention_fn,
+ kwargs,
+ )
return head_to_seq(out, group), None
+def _caller_padding_rows(
+ out, shard, query, key, value, lengths, window, implementation, attention_fn, kwargs
+):
+ """The rows of right padded positions as one process computes them from the caller's 2D mask, so
+ the MoE routes them alike (real rows never attend padding, so they are unchanged). Flash unpads:
+ padding rows are zero. sdpa / eager mask the padded keys: a padding query attends the row's real
+ keys only. Left as is: a row without real tokens, and sdpa / eager with a sliding window (a
+ padding query past the window has no key at all, which softmax turns into NaN)."""
+ total = out.shape[1]
+ if _is_flash(implementation):
+ real = _real_positions(lengths, torch.arange(total, device = out.device))
+ return out.masked_fill(~real[:, :, None, None], 0)
+ if window is not None:
+ return out
+ rows = []
+ for row, length in enumerate(lengths):
+ if length <= 0 or length >= total:
+ rows.append(out[row])
+ continue
+ # Every real key precedes the padding queries: no mask and is_causal = False, so no
+ # [pad, real] mask is materialised (sdpa and eager both honour the explicit flag).
+ pad, _ = attention_fn(
+ shard,
+ query[row : row + 1, :, length:],
+ key[row : row + 1, :, :length],
+ value[row : row + 1, :, :length],
+ None,
+ **{**kwargs, "is_causal": False},
+ )
+ pad = pad.reshape(total - length, out.shape[2], -1)
+ rows.append(torch.cat([out[row, :length], pad.to(out.dtype)], dim = 0))
+ return torch.stack(rows, dim = 0)
+
+
def _ulysses_attention_wrapper(current, implementation, get_cp_manager):
@functools.wraps(current)
def attention(module, query, key, value, attention_mask, *args, **kwargs):
@@ -488,6 +761,9 @@ def _ulysses_attention_wrapper(current, implementation, get_cp_manager):
group = manager.group,
attention_fn = current,
implementation = implementation,
+ caller_lengths = _caller_pad_lengths(
+ manager, query.shape[0], query.shape[2] * manager.size
+ ),
**kwargs,
)