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
Fix packed document boundaries in Qwen PLE (#14011)
cherry77-cloud926339022ae8
diff --git a/tests/utils/test_qwen4_exp_ple_packing.py b/tests/utils/test_qwen4_exp_ple_packing.pynew file mode 100644index 00000000000..63266ec079f--- /dev/null+++ b/tests/utils/test_qwen4_exp_ple_packing.py@@ -0,0 +1,218 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Packed Qwen4Exp (Qwen3.8-Flash-Next) PLE keeps documents apart, on a tiny random model built+from the real transformers classes. GDN gets exact per-document reference kernels so PLE is the+only mixer that could leak."""++import importlib.util+import inspect+import sys++import pytest+import torch++qm = pytest.importorskip("transformers.models.qwen4_exp.modeling_qwen4_exp")+from transformers.models.qwen4_exp.configuration_qwen4_exp import Qwen4ExpTextConfig++import unsloth.utils.packing as packing_module+from unsloth.utils.packing import patch_hybrid_linear_attention_varlen++EOS = 7+LENGTHS = [11, 1, 17, 9]+++def _segments(+ T,+ seq_idx = None,+ cu_seqlens = None,+):+ if cu_seqlens is not None:+ bounds = cu_seqlens.tolist()+ elif seq_idx is not None:+ ids = seq_idx.reshape(-1)+ bounds = [0] + (torch.nonzero(ids[1:] != ids[:-1]).flatten() + 1).tolist() + [T]+ else:+ bounds = [0, T]+ return list(zip(bounds[:-1], bounds[1:]))+++def _hub(torch_function, implementation):+ # Shape of transformers' kernel-hub wrapper, which the packing gate inspects.+ applicable_params = tuple(inspect.signature(implementation).parameters)++ def wrapped(*args, **kwargs):+ if implementation is None:+ return torch_function(*args, **kwargs)+ return implementation(*args, **{k: v for k, v in kwargs.items() if k in applicable_params})++ return wrapped+++def _torch_fallback(name):+ # unsloth_zoo may have replaced the global on GPU: read a pristine copy of the modeling file.+ closure = packing_module._hub_closure(getattr(qm, name))+ if "torch_function" not in closure:+ spec = importlib.util.spec_from_file_location(+ "transformers.models.qwen4_exp._pristine", qm.__file__+ )+ pristine = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = pristine # auto_docstring inspects the module+ try:+ spec.loader.exec_module(pristine)+ finally:+ sys.modules.pop(spec.name, None)+ fn = getattr(pristine, name)+ # With the `kernels` package installed the hub decorator nests one more wrapper.+ return packing_module._hub_closure(fn).get("torch_function") or inspect.unwrap(fn)+ return closure["torch_function"]+++def reference_gdn_kernels(monkeypatch):+ conv_t = _torch_fallback("causal_conv1d_fn")+ gdn_t = _torch_fallback("torch_chunk_gated_delta_rule")++ def conv_ref(+ hidden_states,+ weight,+ bias = None,+ activation = None,+ seq_idx = None,+ ):+ T = hidden_states.shape[-1]+ parts = [+ conv_t(hidden_states[..., s:e], weight, bias, activation)+ for s, e in _segments(T, seq_idx)+ ]+ return torch.cat(parts, -1)++ def gdn_ref(+ query,+ key,+ value,+ g,+ beta,+ chunk_size = 64,+ initial_state = None,+ output_final_state = False,+ use_qk_l2norm_in_kernel = False,+ cu_seqlens = None,+ ):+ outs = [+ gdn_t(+ query[:, s:e],+ key[:, s:e],+ value[:, s:e],+ g[:, s:e],+ beta[:, s:e],+ chunk_size = chunk_size,+ use_qk_l2norm_in_kernel = use_qk_l2norm_in_kernel,+ )[0]+ for s, e in _segments(query.shape[1], cu_seqlens = cu_seqlens)+ ]+ return torch.cat(outs, 1), None++ monkeypatch.setattr(qm, "causal_conv1d_fn", _hub(conv_t, conv_ref))+ monkeypatch.setattr(qm, "torch_chunk_gated_delta_rule", _hub(gdn_t, gdn_ref))+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")+++def _tiny_model():+ torch.manual_seed(0)+ config = Qwen4ExpTextConfig(+ vocab_size = 512,+ hidden_size = 64,+ num_hidden_layers = 4,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 16,+ linear_conv_kernel_dim = 4,+ linear_key_head_dim = 16,+ linear_value_head_dim = 16,+ linear_num_key_heads = 2,+ linear_num_value_heads = 4,+ moe_intermediate_size = 32,+ shared_expert_intermediate_size = 32,+ num_experts = 4,+ num_experts_per_tok = 2,+ full_attention_interval = 4,+ hc_count = 4,+ hc_lowrank = 8,+ ple_layer_ids = [2],+ ple_embed_dim = 48,+ ple_conv_kernel_size = 4,+ ngram_size = 3,+ heads_per_ngram = 2,+ ngram_vocab_size_base = 1000,+ split_ngram_parts = 4,+ indexer_n_heads = 2,+ indexer_kv_heads = 1,+ indexer_head_dim = 16,+ indexer_budget = 2048,+ indexer_compress_ratio = 4,+ output_gate_type = "sigmoid",+ eos_token_id = EOS,+ bos_token_id = EOS,+ rope_parameters = {+ "mrope_interleaved": True,+ "mrope_section": [1, 1, 0],+ "partial_rotary_factor": 0.25,+ "rope_theta": 10000000,+ "rope_type": "default",+ },+ )+ config._attn_implementation = "sdpa"+ model = qm.Qwen4ExpForCausalLM(config).eval()+ # HF init zeroes the PLE conv; a trained checkpoint does not.+ (ple,) = [m for m in model.modules() if isinstance(m, qm.Qwen4ExpTextPLELayer)]+ with torch.no_grad():+ ple.conv1d.weight.copy_(+ 0.5 * torch.randn(ple.conv1d.weight.shape, generator = torch.Generator().manual_seed(3))+ )+ return model, ple++[email protected]("eos", [True, False])+def test_packed_ple_matches_separate_documents(reference_gdn_kernels, eos):+ model, ple = _tiny_model()+ assert patch_hybrid_linear_attention_varlen(model) is True++ g = torch.Generator().manual_seed(1)+ docs = [torch.randint(8, 512, (n,), generator = g) for n in LENGTHS]+ if eos:+ for d in docs:+ d[-1] = EOS+ ids = torch.cat(docs)[None]+ embed = model.get_input_embeddings()++ def run(input_ids, **kwargs):+ x = embed(input_ids).detach().requires_grad_(True)+ n = input_ids.shape[1]+ position_ids = kwargs.pop("position_ids", torch.arange(n)[None])+ out = model(+ inputs_embeds = x,+ ple_input_ids = input_ids,+ position_ids = position_ids,+ use_cache = False,+ **kwargs,+ )+ return x, out.logits++ x, packed = run(+ ids,+ position_ids = torch.cat([torch.arange(n) for n in LENGTHS])[None],+ packed_seq_lengths = torch.tensor(LENGTHS, dtype = torch.int32),+ )+ alone = torch.cat([run(d[None])[1] for d in docs], dim = 1)+ torch.testing.assert_close(packed, alone, rtol = 1e-5, atol = 1e-5)++ start = sum(LENGTHS[:2])+ packed[0, start : start + LENGTHS[2]].sum().backward()+ grad = x.grad[0].abs().sum(-1)+ assert grad[start : start + LENGTHS[2]].sum() > 0+ assert grad[:start].sum() == 0 and grad[start + LENGTHS[2] :].sum() == 0++ kinds = {kind for _, kind in packing_module._iter_stateful_mixers(model)}+ assert kinds == {"gated_delta", "ple"}+ assert ple._unsloth_varlen_conv_hit and ple._unsloth_varlen_embedding_hitdiff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex a07b3784c47..202c67c346d 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -352,7 +352,7 @@ def _hybrid_packing_enabled() -> bool:# Auto-packed mixers (CUDA only). MoE router aux loss is computed over the whole packed row, not per document.-_HYBRID_AUTO_KINDS = ("gated_delta",)+_HYBRID_AUTO_KINDS = ("gated_delta", "ple")HYBRID_PACKING_STATS = {"probe_runs": 0,@@ -397,9 +397,11 @@ _QKV_CONVS = ("q_conv1d", "k_conv1d", "v_conv1d")def _stateful_mixer_kind(module) -> Optional[str]:"""How a token mixer carries state across positions: "gated_delta" / "ssd" (Mamba2-style- chunked scan) / "short_conv" take boundary metadata, "unsupported" leaks with no kernel+ chunked scan) / "short_conv" / "ple" take boundary metadata, "unsupported" leaks with no kernelfix (Mamba1 selective scan, lightning attention, RWKV), None is stateless."""name = type(module).__name__+ if name == "Qwen4ExpTextPLELayer":+ return "ple"if name.endswith("GatedDeltaNet"):if hasattr(module, "conv1d"):return "gated_delta"@@ -720,6 +722,11 @@ def _hybrid_varlen_dispatched(module) -> bool:kind = _stateful_mixer_kind(module)if kind == "short_conv":return bool(getattr(module, "_unsloth_varlen_conv_hit", False))+ if kind == "ple":+ return bool(+ getattr(module, "_unsloth_varlen_conv_hit", False)+ and getattr(module, "_unsloth_varlen_embedding_hit", False)+ )if kind == "ssd":if getattr(module, "_unsloth_varlen_fused_hit", False):return True@@ -1054,6 +1061,55 @@ def _wrap_short_conv_forward(module) -> None:module.forward = forward+def _ple_input_with_gaps(tensor, varlen, gap, fill_value):+ positions = torch.arange(tensor.shape[1], device = tensor.device)+ positions = positions + varlen[1][0].to(device = tensor.device, dtype = torch.long) * gap+ length = tensor.shape[1] + (varlen[0].numel() - 2) * gap+ expanded = tensor.new_full((tensor.shape[0], length, *tensor.shape[2:]), fill_value)+ return expanded.index_copy(1, positions, tensor), positions+++def _wrap_ple_boundaries(module) -> None:+ # PLE's dilated conv has no seq_idx kernel: pad zero history before each document, gather real outputs.+ conv_orig = module._short_conv+ embedding = module.ple_embedding+ embedding_orig = embedding.forward++ def packed_input(tensor, past_key_values):+ varlen = getattr(module, "_unsloth_varlen", None)+ if past_key_values is not None or varlen is None or tensor.shape[:2] != varlen[1].shape:+ return None+ return varlen++ @wraps(conv_orig)+ def short_conv(hidden_states, past_key_values):+ varlen = packed_input(hidden_states, past_key_values)+ if varlen is None:+ return conv_orig(hidden_states, past_key_values)+ expanded, positions = _ple_input_with_gaps(+ hidden_states, varlen, module.short_conv_state_len, 0+ )+ output = conv_orig(expanded, past_key_values)+ module._unsloth_varlen_conv_hit = True+ return output.index_select(1, positions)++ @wraps(embedding_orig)+ def ngram_embedding(input_ids, past_key_values):+ varlen = packed_input(input_ids, past_key_values)+ if varlen is None:+ return embedding_orig(input_ids, past_key_values)+ # Boundaries need not hold EOS: synthetic EOS history resets the n-gram hash like a separate forward.+ expanded, positions = _ple_input_with_gaps(+ input_ids, varlen, embedding.context_len, embedding.eos_token_id+ )+ output = embedding_orig(expanded, past_key_values)+ module._unsloth_varlen_embedding_hit = True+ return output.index_select(1, positions)++ module._short_conv = short_conv+ embedding.forward = ngram_embedding++def _uses_hub_conv(module) -> bool:globs = getattr(inspect.getmodule(type(module)), "__dict__", {})return "implementation" in _hub_closure(globs.get("causal_conv1d_fn"))@@ -1154,6 +1210,7 @@ _HYBRID_PROBE_LENGTHS = (5, 1, 70, 7)_HYBRID_PROBE_RTOL = {torch.float32: 1e-4, torch.bfloat16: 2e-2, torch.float16: 1e-2}_HYBRID_SNAPSHOT_ATTRS = ("forward",+ "_short_conv","causal_conv1d_fn","chunk_gated_delta_rule","_unsloth_varlen",@@ -1164,6 +1221,7 @@ _HYBRID_SNAPSHOT_ATTRS = ("_unsloth_varlen_conv_hit","_unsloth_varlen_scan_hit","_unsloth_varlen_kwargs_hit",+ "_unsloth_varlen_embedding_hit",)_MISSING = object()@@ -1172,6 +1230,8 @@ def _snapshot_mixers(modules):saved = []for module in modules:owners = [module] + [getattr(module, c, None) for c in _QKV_CONVS]+ if _stateful_mixer_kind(module) == "ple":+ owners.append(module.ple_embedding)for owner in owners:if isinstance(owner, torch.nn.Module):state = {k: owner.__dict__.get(k, _MISSING) for k in _HYBRID_SNAPSHOT_ATTRS}@@ -1189,6 +1249,9 @@ def _restore_mixers(saved) -> None:def _auto_hybrid_device_ok(module) -> bool:+ # Native torch ops; the n-gram table may stay on CPU.+ if _stateful_mixer_kind(module) == "ple":+ return Trueweight = next(module.parameters(), None)return torch.version.hip is None and weight is not None and weight.device.type == "cuda"@@ -1269,11 +1332,11 @@ def _hybrid_exactness_probe(module) -> Optional[str]:def patch_hybrid_linear_attention_varlen(model) -> bool:"""Feed seq_idx / cu_seqlens to hybrid mixers; True when packing is active. Fail-closed, idempotent."""mixers = _iter_stateful_mixers(model)- # Short-conv-only models (LFM2) reset at seq_idx on both kernel and torch paths, so they pack by default.- short_conv_only = bool(mixers) and all(kind == "short_conv" for _, kind in mixers)+ # LFM2 short convs and PLE have boundary-safe torch paths, so they also pack without CUDA.+ torch_varlen_only = bool(mixers) and all(kind in ("short_conv", "ple") for _, kind in mixers)mode = _hybrid_packing_mode()auto_eligible = bool(mixers) and all(kind in _HYBRID_AUTO_KINDS for _, kind in mixers)- if not short_conv_only:+ if not torch_varlen_only:if mode == "off" or (mode == "auto" and not auto_eligible):return Falseunsupported = sorted({type(m).__name__ for m, kind in mixers if kind == "unsupported"})@@ -1282,7 +1345,8 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:gated_delta_modules = [m for m, kind in mixers if kind in ("gated_delta", "gated_delta_qkv")]mamba2_modules = [m for m, kind in mixers if kind == "ssd"]short_conv_modules = [m for m, kind in mixers if kind == "short_conv"]- hybrid_modules = gated_delta_modules + mamba2_modules + short_conv_modules+ ple_modules = [m for m, kind in mixers if kind == "ple"]+ hybrid_modules = gated_delta_modules + mamba2_modules + short_conv_modules + ple_modulesif not hybrid_modules:return _hybrid_reject("no stateful mixers found")kwargs_modules = [@@ -1302,7 +1366,7 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:hub_short_convs = [m for m in short_conv_modules if _uses_hub_conv(m)]probe_target = _probe_target(gated_delta_modules + kwargs_modules)- if mode == "auto" and not short_conv_only:+ if mode == "auto" and not torch_varlen_only:if probe_target is None:return _hybrid_reject("no gated-delta mixer the exactness probe can run")# Every stateful mixer, kwargs-mode ones included (transformers 5.16+ Qwen mixers move there).@@ -1395,6 +1459,11 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:_wrap_short_conv_forward(module)module._unsloth_varlen = Nonemodule._unsloth_varlen_wrapped = True+ for module in ple_modules:+ if not getattr(module, "_unsloth_varlen_wrapped", False):+ _wrap_ple_boundaries(module)+ module._unsloth_varlen = None+ module._unsloth_varlen_wrapped = Trueif probe_target is not None:reason = _hybrid_exactness_probe(probe_target)@@ -1490,6 +1559,7 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:module._unsloth_varlen_scan_hit = Falsemodule._unsloth_varlen_fused_hit = Falsemodule._unsloth_varlen_kwargs_hit = False+ module._unsloth_varlen_embedding_hit = Falseouter, _PACKED[0] = _PACKED[0], varlentry:out = forward_orig(*args, **kwargs)