Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Context parallel: register the Qwen3.5 hybrid cp x native FSDP2 cell, add coverage tests (#17039)
Daniel Han624426928432
diff --git a/tests/test_cp_ulysses_generic_gloo.py b/tests/test_cp_ulysses_generic_gloo.pyindex 053f8fa6ba7..564182be93a 100644--- a/tests/test_cp_ulysses_generic_gloo.py+++ b/tests/test_cp_ulysses_generic_gloo.py@@ -7,7 +7,8 @@ attention sinks survive the exchange. Two gloo CPU ranks vs one process: the losConfigs are the tiny test repos' (tiny_models.py: hf-internal-testing/tiny-random-Gemma3ForCausalLM,trl-internal-testing/tiny-Qwen3ForCausalLM, trl-internal-testing/tiny-GptOssForCausalLM) with random weights, a-small vocabulary, and a window shorter than a shard so it crosses the seam."""+small vocabulary, and a window shorter than a shard so it crosses the seam. DeepSeek-V2 and MiniMax-M2 have no tiny+repo: their configs are written out (_built_config)."""import osimport tempfile@@ -36,9 +37,75 @@ REPOS = {}+def _built_config(kind):+ """Configs with no tiny hub repo: written out (random weights). DeepSeek-V2: multi-head latent attention,+ query / key head dim 24 (nope 16 + rope 8) against value head dim 16, YaRN scaling, MoE after one dense layer.+ MiniMax-M2: grouped query attention (4 heads / 2 kv heads) with q / k norms over all heads, MoE layers."""+ if kind == "deepseek_v2":+ from transformers import DeepseekV2Config+ return DeepseekV2Config(+ vocab_size = 96,+ hidden_size = 64,+ intermediate_size = 128,+ moe_intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 4,+ kv_lora_rank = 16,+ q_lora_rank = 24,+ qk_rope_head_dim = 8,+ v_head_dim = 16,+ qk_nope_head_dim = 16,+ n_routed_experts = 4,+ n_shared_experts = 1,+ num_experts_per_tok = 2,+ first_k_dense_replace = 1,+ rope_parameters = {+ "rope_type": "yarn",+ "rope_theta": 10000.0,+ "factor": 4.0,+ "beta_fast": 32,+ "beta_slow": 1,+ "mscale": 0.707,+ "mscale_all_dim": 0.707,+ "original_max_position_embeddings": 64,+ },+ attention_dropout = 0.0,+ use_cache = False,+ pad_token_id = 0,+ )+ from transformers.models.minimax_m2 import MiniMaxM2Config++ return MiniMaxM2Config(+ vocab_size = 96,+ hidden_size = 64,+ intermediate_size = 128,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 16,+ num_local_experts = 4,+ num_experts_per_tok = 2,+ output_router_logits = False,+ attention_dropout = 0.0,+ use_cache = False,+ bos_token_id = 1,+ eos_token_id = 2,+ pad_token_id = 0,+ )+++BUILT = ("deepseek_v2", "minimax_m2")++def _config(kind):from transformers import AutoConfig+ if kind in BUILT:+ try:+ return _built_config(kind)+ except ImportError as e: # an older transformers without the architecture+ pytest.skip(f"{kind}: {e}")try:config = AutoConfig.from_pretrained(REPOS[kind])except Exception as e: # offline host without the tiny repo cached@@ -250,10 +317,22 @@ _OUT = os.environ.get("UNSLOTH_TEST_PARITY_OUT", "")("qwen3", "sdpa", False), # plain causal: sdpa's is_causal path("qwen3", "sdpa", True),("gpt_oss", "eager", False), # attention sinks (local heads' slice) + sliding window+ ("deepseek_v2", "sdpa", False), # MLA: query / key and value head dims differ, YaRN scale+ ("deepseek_v2", "eager", False),+ ("minimax_m2", "sdpa", False), # GQA with q / k norms over all heads, MoE],)def test_generic_ulysses_matches_one_process(kind, implementation, packed):_config(kind) # skip before forking when the repo is unavailable+ if kind in BUILT and int(transformers.__version__.split(".")[0]) < 5:+ model = _model(kind, implementation)+ if not cp._supports_context_parallel(model, "ulysses"):+ # A refusal before training, not a wrong gradient: transformers 4.x builds DeepSeek-V2's experts as+ # per-expert modules, which the support check declines (_hybrid_config_blocker).+ pytest.skip(+ f"{kind}: generic Ulysses is declined on transformers {transformers.__version__}: "+ f"{cp._hybrid_config_blocker(model)}"+ )_spawn(_parity_worker, 2, kind, implementation, packed, _OUT)diff --git a/tests/test_fsdp2_native_units.py b/tests/test_fsdp2_native_units.pyindex 65f5e9d2d5d..665da0e8b03 100644--- a/tests/test_fsdp2_native_units.py+++ b/tests/test_fsdp2_native_units.py@@ -266,6 +266,109 @@ def test_native_fsdp2_units_and_grads(arch, repo, loader, lora, tmp_path):assert r["dummy_viable"], r+def _gemma4_kv_shared(shared):+ """Tiny Gemma 4 text model (random init, no weights); the last `shared` layers reuse the kv of the last+ non-shared layer of their type, which the decoder hands across layers (shared_kv_states)."""+ import transformers++ config = transformers.Gemma4TextConfig(+ vocab_size = 256,+ hidden_size = 64,+ intermediate_size = 128,+ num_hidden_layers = 4,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 16,+ global_head_dim = 16,+ num_kv_shared_layers = shared,+ layer_types = ["sliding_attention", "full_attention"] * 2,+ sliding_window = 8,+ hidden_size_per_layer_input = 16,+ vocab_size_per_layer_input = 256,+ tie_word_embeddings = False,+ )+ config._attn_implementation = "eager"+ torch.manual_seed(0)+ return transformers.Gemma4ForCausalLM(config).float().train()+++def _kv_shared_worker(rank, world, port, shared, reshard, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group("gloo", rank = rank, world_size = world)+ try:+ native = _load_native()+ ref, model = _gemma4_kv_shared(shared), _gemma4_kv_shared(shared)+ attn = [layer.self_attn for layer in model.model.layers]+ batch = _batch(model)+ ref_loss = ref(**batch).loss+ ref_loss.backward()+ ref_grads = {n: p.grad.clone() for n, p in ref.named_parameters() if p.grad is not None}+ native.shard_model(+ model, native.FSDP2Config(param_dtype = torch.float32, reshard_after_forward = reshard)+ )+ assert native.is_native_fsdp2(model)+ loss = model(**batch).loss+ loss.backward()+ from torch.distributed.tensor import DTensor++ worst, missing = 0.0, []+ for n, p in model.named_parameters():+ if p.grad is None:+ if n in ref_grads:+ missing.append(n)+ continue+ g = p.grad.full_tensor() if isinstance(p.grad, DTensor) else p.grad+ r = ref_grads[n]+ worst = max(worst, (g - r).abs().max().item() / (r.abs().max().item() + 1e-8))+ result = {+ "loss": loss.item(),+ "ref_loss": ref_loss.item(),+ "worst_rel_grad": worst,+ "missing": missing,+ "n_grads": len(ref_grads),+ "kv_shared": sum(bool(getattr(a, "is_kv_shared_layer", False)) for a in attn),+ "kv_stored": sum(bool(getattr(a, "store_full_length_kv", False)) for a in attn),+ "units": len(native.find_shard_units(model)),+ }+ if rank == 0:+ import json+ with open(out, "w", encoding = "utf-8") as f:+ json.dump(result, f)+ finally:+ dist.destroy_process_group()+++def test_gemma4_kv_shared_layers_match_one_process(tmp_path):+ """Gemma 4 with num_kv_shared_layers > 0 under native FSDP2 (reshard_after_forward = True): the shared+ layers read kv that an earlier, already resharded unit computed; loss and every gradient match the+ unsharded model."""+ import json++ import torch.multiprocessing as mp+ import transformers++ if not hasattr(transformers, "Gemma4TextConfig"):+ pytest.skip(f"transformers {transformers.__version__} has no Gemma 4")+ out = str(tmp_path / "result.json")+ mp.spawn(_kv_shared_worker, args = (2, _free_port(), 2, True, out), nprocs = 2, join = True)+ with open(out, encoding = "utf-8") as f:+ r = json.load(f)+ assert r["kv_shared"] == 2 and r["kv_stored"] >= 1, r # the case under test+ assert r["units"] >= 4, r+ assert not r["missing"] and r["n_grads"] > 0, r+ assert abs(r["loss"] - r["ref_loss"]) <= 1e-5 * max(1.0, abs(r["ref_loss"])), r+ assert r["worst_rel_grad"] < 1e-4, r++def test_native_selection_env(monkeypatch):native = _load_native()monkeypatch.setenv("WORLD_SIZE", "2")diff --git a/tests/test_parallel_capabilities_evidence.py b/tests/test_parallel_capabilities_evidence.pyindex a4da1ca491e..cfef87515e0 100644--- a/tests/test_parallel_capabilities_evidence.py+++ b/tests/test_parallel_capabilities_evidence.py@@ -62,6 +62,54 @@ def _packed(**kw):return caps.Query(**base)+# Hybrid (Gated DeltaNet + attention) cp x native FSDP2.+++def _hybrid(**kw):+ base = dict(+ trainer = "sft",+ family = "qwen3_5",+ hybrid = True,+ cp = 2,+ dp = 2,+ fsdp2 = True,+ cp_backend = "ulysses",+ attention = "sdpa",+ compile = "eager",+ mode = "lora",+ torch = (2, 13),+ )+ base.update(kw)+ return caps.Query(**base)+++def test_hybrid_qwen3_5_cp_x_native_fsdp2_is_supported_under_strict(clean_env):+ status, cell = caps.cell_status(_hybrid())+ assert status == "supported", cell+ assert "hybrid" in cell.name and not cell.missing()+ assert "test_hybrid_qwen3_5_cp_with_native_fsdp2_matches_one_process" in cell.parity+ clean_env.setenv("UNSLOTH_PARALLEL_STRICT", "1")+ caps.check(_hybrid())+++ "kw",+ [+ {"family": "qwen3_next"},+ {"attention": "eager"},+ {"dp": 4},+ {"mode": "full"},+ {"memory": "gc"},+ {"compile": "block"},+ ],+)+def test_hybrid_cp_x_native_fsdp2_outside_the_measured_cell_stays_unverified(kw, clean_env):+ assert caps.cell_status(_hybrid(**kw))[0] == "unverified"+ clean_env.setenv("UNSLOTH_PARALLEL_STRICT", "1")+ with pytest.raises(NotImplementedError, match = "no numeric parity"):+ caps.check(_hybrid(**kw))++# Packed / padding-free rows x cp Ulysses.diff --git a/tests/test_parallel_cp_compose_gloo.py b/tests/test_parallel_cp_compose_gloo.pyindex 73c2330aaae..f101adf018c 100644--- a/tests/test_parallel_cp_compose_gloo.py+++ b/tests/test_parallel_cp_compose_gloo.py@@ -57,6 +57,36 @@ def _checkpoint(tmp, arch = "llama"):from test_tp_native_oracle import LLAMA, QWEN3, QWEN3_MOE, build+ if arch == "qwen3_5":+ # Hybrid: Gated DeltaNet (linear attention) layers beside attention, 4 heads / 2 kv heads, 4 value heads+ # over 2 key heads in the linear layers, so Ulysses cp 2 splits both kinds. No hub weights: random init.+ import transformers++ tok = AutoTokenizer.from_pretrained(QWEN3)+ config = transformers.Qwen3_5TextConfig(+ vocab_size = len(tok),+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = N_LAYERS,+ layer_types = ["linear_attention", "full_attention"] * (N_LAYERS // 2),+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 8,+ linear_num_key_heads = 2,+ linear_num_value_heads = 4,+ linear_key_head_dim = 8,+ linear_value_head_dim = 8,+ linear_conv_kernel_dim = 4,+ attention_dropout = 0.0,+ tie_word_embeddings = False,+ )+ torch.manual_seed(0)+ model = transformers.Qwen3_5ForCausalLM(config)+ model.generation_config.pad_token_id = None+ path = os.path.join(tmp, "ckpt")+ model.save_pretrained(path, safe_serialization = True)+ tok.save_pretrained(path)+ return pathif arch in ("qwen3_moe", "qwen3", "qwen3_moe_wide"):# qwen3_moe: 4 heads / 2 kv heads, 4 experts (2 per token), router aux loss off as shipped.# qwen3_moe_wide: hidden and expert widths of 32, so Unsloth's Triton grouped GEMM takes the experts (it@@ -437,6 +467,21 @@ def _case_train(load = tp_env.tensor_parallel_env_load(load)peft = tp_env.tensor_parallel_env_peft(peft)model = load(ckpt, load_in_4bit = False)+ gdn_calls = []+ if arch == "qwen3_5":+ # The torch Gated DeltaNet kernels (fla / Triton need CUDA), and a counter on Unsloth's GDN exchange.+ from test_ulysses_hybrid import _force_torch_kernels++ from unsloth.utils import ulysses_hybrid as gdn++ _force_torch_kernels(model)+ original_gdn = gdn.ulysses_gated_delta_forward++ def counted_gdn(*a, **k):+ gdn_calls.append(1)+ return original_gdn(*a, **k)++ gdn.ulysses_gated_delta_forward = counted_gdngc_stats = {"checkpoint_calls": 0, "offloaded": 0, "restored": 0}if gc != "none":_install_unsloth_checkpoint(model, gc, gc_stats)@@ -716,6 +761,7 @@ def _case_train("query": query,"exchanges": exchanges,"n_layers": int(trainer.model.config.num_hidden_layers),+ "gdn_calls": len(gdn_calls),}if dist.is_initialized():dist.barrier()@@ -1122,6 +1168,46 @@ def test_cp_with_native_fsdp2_matches_one_process(env, sft_cp):_close(res, ref, what = (env, rank))+def _needs_qwen3_5():+ import transformers+ if not hasattr(transformers, "Qwen3_5TextConfig"):+ pytest.skip(f"transformers {transformers.__version__} has no Qwen3.5")+++def test_hybrid_qwen3_5_under_cp_matches_one_process():+ """Qwen3.5 hybrid (Gated DeltaNet + attention) under Ulysses cp 2: both layer kinds exchange, one process's+ numbers."""+ _needs_qwen3_5()+ ref = _ref(2, arch = "qwen3_5")+ assert ref["gdn_calls"] == 0 and ref["ulysses_calls"] == 0+ for rank, res in enumerate(_spawn("train", 2, bs = 2, cp = 2, arch = "qwen3_5")):+ assert "error" not in res, (rank, res.get("error"), res.get("trace"))+ assert res["cp_group"] == [0, 1] and res["seen_lengths"] == [SEQ // 2]+ # Every forward of a training step: N_LAYERS // 2 linear attention and as many attention layers.+ assert res["gdn_calls"] >= N_LAYERS // 2 and res["ulysses_calls"] >= N_LAYERS // 2, res+ _close(res, ref, what = ("qwen3_5 cp2", rank))+++ "env, sft_cp",+ [({"UNSLOTH_FSDP2": "1"}, True), ({"UNSLOTH_PARALLEL": "cp=2,fsdp=1"}, False)],+ ids = ["fsdp2_env_cp_config", "unsloth_parallel"],+)+def test_hybrid_qwen3_5_cp_with_native_fsdp2_matches_one_process(env, sft_cp):+ """The registry's hybrid cp x native FSDP2 cell: strict mode (unverified layouts refused) trains it, FSDP2+ shards over (dp_shard, cp), the Gated DeltaNet and attention exchanges run, one process's numbers."""+ _needs_qwen3_5()+ ref = _ref(4, arch = "qwen3_5")+ env = {**env, "UNSLOTH_PARALLEL_STRICT": "1"}+ for rank, res in enumerate(_spawn("train", 4, env, bs = 2, cp = 2, sft_cp = sft_cp, arch = "qwen3_5")):+ assert "error" not in res, (rank, res.get("error"), res.get("trace"))+ assert res["native_fsdp2"] and res["cp_group"] == [rank - rank % 2, rank - rank % 2 + 1]+ assert res["seen_lengths"] == [SEQ // 2]+ assert res["gdn_calls"] >= N_LAYERS // 2 and res["ulysses_calls"] >= N_LAYERS // 2, res+ assert "FSDP2 shards and reduces over dp_shard x cp" in (res["banner"] or ""), res["banner"]+ _close(res, ref, what = ("qwen3_5", env, rank), state_atol = 1e-5)++def test_dense_qwen3_under_cp_matches_one_process():"""The control for the MoE cell below: the same family without experts trains like one process."""ref = _ref(2, arch = "qwen3")diff --git a/unsloth/parallel_capabilities.py b/unsloth/parallel_capabilities.pyindex 6596ba24c6b..9a4c034f0b0 100644--- a/unsloth/parallel_capabilities.py+++ b/unsloth/parallel_capabilities.py@@ -655,6 +655,7 @@ _PARITY = _GLOO + "test_cp_x_tp_from_unsloth_parallel_matches_one_process"_CP_DP = {k: v for k, v in _CP_TP.items() if k != "block_swap"}_CP_DP.update(tp = (1,), moe = (False,))_FSDP2_CP = _GLOO + "test_cp_with_native_fsdp2_matches_one_process"+_HYBRID_FSDP2_CP = _GLOO + "test_hybrid_qwen3_5_cp_with_native_fsdp2_matches_one_process"_MOE_CP = _GLOO + "test_moe_without_aux_loss_under_cp_matches_one_process"# Packed rows under generic Ulysses (HF attention, DDP over cp)._PACKED_CP = {@@ -695,6 +696,26 @@ CELLS = (note = _UNSLOTH_GC+ "test_cp_with_native_fsdp2_and_unsloth_checkpointing_matches_one_process",),+ Cell(+ "hybrid (Gated DeltaNet + attention) cp x native FSDP2 (dp_shard x cp), eager",+ {+ **_CP_DP,+ "family": ("qwen3_5",),+ "hybrid": (True,),+ "attention": ("sdpa",),+ "memory": ("none",),+ "fsdp2": (True,),+ "compile": ("eager",),+ "dp": (2,),+ "cp": (2,),+ },+ parity = _HYBRID_FSDP2_CP,+ engagement = _HYBRID_FSDP2_CP+ + " (FSDP2 mesh covers the cp group, seq / cp tokens, Gated DeltaNet and attention Ulysses exchanges, "+ "UNSLOTH_PARALLEL_STRICT=1)",+ compile = "eager: no compiled region",+ note = "cp alone: " + _GLOO + "test_hybrid_qwen3_5_under_cp_matches_one_process",+ ),Cell("cp x tp (DDP dp), eager",{**_CP_TP, "fsdp2": (False,), "compile": ("eager",), "dp": (1, 2), "tp": (2,), "cp": (2,)},