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
Make the packed-boundary guard reachable on the fused cross-entropy path (#8959)
Daniel Han2886dfc3834e
diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.pyindex 14dde6b4d1b..6532f203de2 100644--- a/tests/utils/test_packing.py+++ b/tests/utils/test_packing.py@@ -22,6 +22,7 @@ from unsloth.utils.packing import (configure_sample_packing,enable_padding_free_metadata,enable_sample_packing,+ mask_packed_boundary_labels,mask_packed_sequence_boundaries,patch_hybrid_linear_attention_varlen,)@@ -1364,3 +1365,218 @@ def test_packing_skip_warning_keeps_custom_collator_reason(monkeypatch, caplog):assert len(messages) == 1assert "custom data collator" in messages[0]assert "UNSLOTH_RETURN_LOGITS" not in messages[0]+++# --- packed-boundary guard on the fused-CE path ---------------------------------------+# mask_packed_sequence_boundaries needs shifted labels, so fused-CE paths (which shift+# internally) call mask_packed_boundary_labels, the pre-shift equivalent.+++def test_mask_packed_boundary_labels_masks_next_document_first_token():+ labels = torch.arange(6, dtype = torch.long).view(1, 6)+ out = mask_packed_boundary_labels(labels, torch.tensor([2, 1, 3], dtype = torch.int32))+ # Docs start at 0, 2, 3; masking their first token stops the previous doc predicting+ # it. Slot 0 is the out-of-range redirect: harmless, the shift discards labels[0].+ assert out.reshape(-1).tolist() == [-100, 1, -100, -100, 4, 5]+ # out-of-place+ assert labels.reshape(-1).tolist() == [0, 1, 2, 3, 4, 5]+ assert out.shape == labels.shape+ assert out.dtype == labels.dtype+++def test_mask_packed_boundary_labels_matches_the_shifted_guard():+ """The two entry points must mask exactly the same CE targets."""+ labels = torch.arange(100, 112, dtype = torch.long).view(1, 12)+ lengths = torch.tensor([5, 4, 3], dtype = torch.int32)++ # Route A: shift, then the in-place guard.+ shift_a = torch.empty_like(labels)+ shift_a[..., :-1] = labels[..., 1:]+ shift_a[..., -1] = -100+ mask_packed_sequence_boundaries(shift_a, lengths)++ # Route B: the raw-label guard, then shift (what fused CE does).+ masked = mask_packed_boundary_labels(labels, lengths)+ shift_b = torch.empty_like(masked)+ shift_b[..., :-1] = masked[..., 1:]+ shift_b[..., -1] = -100++ assert torch.equal(shift_a, shift_b)+++def test_mask_packed_boundary_labels_is_idempotent_on_trl_masked_labels():+ """TRL already sets labels[position_ids == 0] = -100, so the guard is a no-op on it."""+ lengths = torch.tensor([2, 1, 3], dtype = torch.int32)+ labels = torch.arange(6, dtype = torch.long).view(1, 6)+ position_ids = torch.tensor([[0, 1, 0, 0, 1, 2]], dtype = torch.long)+ trl_labels = labels.clone()+ trl_labels[position_ids == 0] = -100++ once = mask_packed_boundary_labels(trl_labels, lengths)+ twice = mask_packed_boundary_labels(once, lengths)+ assert torch.equal(once, trl_labels)+ assert torch.equal(twice, once)+++def test_mask_packed_boundary_labels_is_a_noop_without_packing():+ labels = torch.arange(6, dtype = torch.long).view(1, 6)+ assert mask_packed_boundary_labels(labels, None) is labels+ assert mask_packed_boundary_labels(labels, torch.tensor([], dtype = torch.int32)) is labels+ assert mask_packed_boundary_labels(None, torch.tensor([2, 4])) is None+++def test_mask_packed_boundary_labels_tolerates_pad_to_multiple_of():+ # Trailing pad beyond sum(seq_lengths) stays -100, and no index goes OOB.+ labels = torch.tensor([[10, 11, 12, 13, -100, -100]], dtype = torch.long)+ out = mask_packed_boundary_labels(labels, torch.tensor([2, 2], dtype = torch.int32))+ assert out.reshape(-1).tolist() == [10, 11, -100, 13, -100, -100]+++def test_mask_packed_boundary_labels_lengths_covering_whole_row():+ # cumsum == numel: the redirect must not corrupt a real target.+ labels = torch.arange(4, dtype = torch.long).view(1, 4)+ out = mask_packed_boundary_labels(labels, [2, 2])+ assert out.reshape(-1).tolist() == [-100, 1, -100, 3]+++# ==========================================================================+# Each test below fails when its production hunk is reverted.+# 1 + 2. the fused-CE call sites (llama.py / mistral.py)+# ==========================================================================+class _StubInner(torch.nn.Module):+ def __init__(self, hidden):+ super().__init__()+ self.hidden = hidden++ def forward(self, **kwargs):+ from transformers.modeling_outputs import BaseModelOutputWithPast+ return BaseModelOutputWithPast(+ last_hidden_state = self.hidden,+ past_key_values = None,+ hidden_states = None,+ attentions = None,+ )+++def _make_stub_causal_lm(+ hidden_size = 8,+ vocab = 16,+ seq = 8,+):+ hidden = torch.zeros(1, seq, hidden_size)+ model = _StubInner(hidden)+ lm_head = torch.nn.Linear(hidden_size, vocab, bias = False)+ stub = SimpleNamespace(+ model = model,+ lm_head = lm_head,+ # Mistral's `elif self.training:` mask branch is only reached without xformers,+ # so omitting this passes locally but AttributeErrors on CI.+ training = True,+ config = SimpleNamespace(+ output_attentions = False,+ output_hidden_states = False,+ use_return_dict = True,+ model_type = "llama",+ final_logit_softcapping = 0,+ logit_scale = 0,+ torch_dtype = torch.float32,+ ),+ )+ return stub++[email protected]("module_name", ["llama", "mistral"])+def test_fused_ce_branch_masks_packed_boundaries(monkeypatch, module_name):+ """The fused-CE branch must hand boundary-masked labels to the kernel."""+ import importlib++ mod = importlib.import_module(f"unsloth.models.{module_name}")+ seq = 8+ stub = _make_stub_causal_lm(seq = seq)++ seen = {}++ def _fake_fused(**kwargs):+ seen["labels"] = kwargs["labels"].clone()+ return torch.zeros((), requires_grad = False)++ monkeypatch.setattr(mod, "unsloth_fused_ce_loss", _fake_fused)+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS", raising = False)+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES", raising = False)++ if module_name == "llama":+ forward = mod.CausalLM_fast_forward(lambda *a, **k: None)+ else:+ forward = mod.MistralForCausalLM_fast_forward++ labels = torch.arange(seq, dtype = torch.long).view(1, seq)+ forward(+ stub,+ input_ids = torch.zeros(1, seq, dtype = torch.long),+ labels = labels,+ packed_seq_lengths = torch.tensor([3, 5], dtype = torch.int32),+ )++ got = seen["labels"].reshape(-1).tolist()+ # slot 3 (first token of doc 2) is dropped; slot 0 is the harmless redirect.+ assert got == [-100, 1, 2, -100, 4, 5, 6, 7], got+ # out-of-place+ assert labels.reshape(-1).tolist() == list(range(seq))+++# 3. the collator wrappers must leave boundary targets in place: unsloth_zoo counts+# num_items_in_batch off this batch and already deducts them+class _UnmaskedPackingCollator:+ """Padding-free collator that does NOT pre-mask boundaries, like TRL < 0.24 - a test+ built on TRL 0.24+ output would pass either way."""++ def __init__(self):+ self.padding_free = True+ self.return_position_ids = False++ def torch_call(self, examples):+ ids = [i for ex in examples for i in ex["input_ids"]]+ return {+ "input_ids": torch.tensor([ids], dtype = torch.long),+ "labels": torch.tensor([ids], dtype = torch.long),+ }+++def _zoo_num_items_in_batch(batch):+ """The count unsloth_zoo._unsloth_get_batch_samples derives from a batch."""+ count = int((batch["labels"][..., 1:] != -100).sum())+ lengths = batch.get("packed_seq_lengths")+ if lengths is not None:+ count -= int(torch.count_nonzero(lengths > 0)) - 1+ return count++[email protected]("wrapper", [enable_sample_packing, enable_padding_free_metadata])+def test_collator_keeps_boundary_targets_for_the_num_items_deduction(wrapper):+ model = SimpleNamespace(max_seq_length = 16, children = lambda: [])+ trainer = SimpleNamespace(+ args = SimpleNamespace(remove_unused_columns = True),+ data_collator = _UnmaskedPackingCollator(),+ )+ wrapper(model, trainer)++ batch = trainer.data_collator.torch_call(+ [+ {"input_ids": [10, 11, 12], "seq_lengths": [2, 1]},+ {"input_ids": [13, 14, 15], "seq_lengths": [3]},+ ]+ )+ assert batch["labels"].reshape(-1).tolist() == [10, 11, 12, 13, 14, 15]+ # docs [10,11] [12] [13,14,15] -> 1 + 0 + 2 real CE targets+ assert _zoo_num_items_in_batch(batch) == 3+++# 4. idempotence, discriminating (an identity helper must not pass)+def test_guard_is_idempotent_and_actually_masks():+ lengths = torch.tensor([2, 1, 3], dtype = torch.int32)+ labels = torch.arange(6, dtype = torch.long).view(1, 6)+ once = mask_packed_boundary_labels(labels, lengths)+ twice = mask_packed_boundary_labels(once, lengths)+ assert torch.equal(twice, once)+ # idempotence alone is trivial for an identity helper, so pin the values+ assert once.reshape(-1).tolist() == [-100, 1, -100, -100, 4, 5]diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex d73942c27fd..5d1dbfd079d 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -35,6 +35,7 @@ from .loader_utils import ()from ..utils.packing import (get_packed_info_from_kwargs,+ mask_packed_boundary_labels,mask_packed_sequence_boundaries,)from ..utils.attention_dispatch import (@@ -1475,6 +1476,15 @@ def CausalLM_fast_forward(fast_forward_inference):if self.config.model_type == "falcon_h1":hidden_states = hidden_states * self.config.lm_head_multiplier+ # Packed-boundary guard on raw labels (the fused kernel shifts internally).+ # This branch RETURNS, so mask_packed_sequence_boundaries() below is dead on+ # packed training paths: it needs UNSLOTH_RETURN_LOGITS=1, which itself forces+ # packing off (unsloth/trainer.py). Out-of-place, no-op without packed_seq_lengths.+ labels = mask_packed_boundary_labels(+ labels,+ kwargs.get("packed_seq_lengths"),+ )+### DISABLED since T4 breaks# OutOfResources: out of resource: shared memory, Required: 98304, Hardware limit: 65536. Reducing block sizes or `num_stages` may help.# loss = fused_linear_cross_entropy(diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.pyindex da6468fdd15..ce4b3fa9aa4 100644--- a/unsloth/models/mistral.py+++ b/unsloth/models/mistral.py@@ -19,6 +19,7 @@ from unsloth_zoo.utils import _get_dtypefrom unsloth_zoo.hf_utils import dtype_from_configfrom ..utils.packing import (get_packed_info_from_kwargs,+ mask_packed_boundary_labels,mask_packed_sequence_boundaries,)from ..utils.attention_dispatch import (@@ -334,6 +335,13 @@ def MistralForCausalLM_fast_forward(n_items = kwargs.get("n_items", None)logit_softcapping = getattr(self.config, "final_logit_softcapping", 0)+ # Packed-boundary guard, see llama.py. This branch returns, so+ # mask_packed_sequence_boundaries() below is never reached.+ labels = mask_packed_boundary_labels(+ labels,+ kwargs.get("packed_seq_lengths"),+ )+# loss = fused_linear_cross_entropy(# hidden_states = hidden_states,# lm_weight = lm_head,diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex f8d539fb93a..26963f991d6 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -169,6 +169,10 @@ def enable_sample_packing(if isinstance(ids, Iterable):seq_lengths.append(len(ids))if seq_lengths:+ # Boundary labels are NOT masked here: unsloth_zoo's+ # _unsloth_get_batch_samples counts num_items_in_batch off this batch and+ # already subtracts the N-1 boundary targets, so masking here would deduct+ # twice on TRL < 0.24 (no pre-masking). The guard runs in the forward.batch["packed_seq_lengths"] = torch.tensor(seq_lengths, dtype = torch.int32)if "attention_mask" in batch:batch.pop("attention_mask")@@ -211,6 +215,8 @@ def enable_padding_free_metadata(model, trainer):batch = original_torch_call(examples)if seq_lengths:+ # Labels left alone for the same reason as enable_sample_packing:+ # num_items_in_batch is counted off this batch.batch["packed_seq_lengths"] = torch.tensor(seq_lengths,dtype = torch.int32,@@ -667,6 +673,48 @@ def mask_packed_sequence_boundaries(return True+def mask_packed_boundary_labels(+ labels: Optional[torch.Tensor],+ seq_lengths: Any,+ *,+ ignore_index: int = -100,+) -> Optional[torch.Tensor]:+ """Same guard as :func:`mask_packed_sequence_boundaries`, but on RAW (unshifted)+ labels and out-of-place, for fused cross-entropy paths that shift internally.++ The shift maps target slot ``i`` to ``labels[i + 1]``, so masking shift slot+ ``cumsum - 1`` is exactly masking ``labels[cumsum]``, the first token of each+ following document.++ Returns ``labels`` unchanged when ``seq_lengths`` is absent or empty, else a NEW+ tensor; the caller's batch is never mutated. Idempotent, and a no-op on TRL's+ padding-free collator output (``labels[position_ids == 0] = -100``).++ Contract: ``sum(seq_lengths) <= labels.numel()``. Out-of-range entries (the final+ cumsum, or malformed lengths) redirect to index 0, which the shift discards and so+ is never a CE target; this avoids device syncs and data-dependent shapes in the+ compiled fused-CE path.+ """+ if labels is None or not isinstance(labels, torch.Tensor):+ return labels+ lengths = _normalize_packed_lengths(seq_lengths, device = labels.device)+ if lengths is None:+ return labels++ total_tokens = labels.numel()+ if total_tokens == 0:+ return labels++ positions = torch.cumsum(lengths, dim = 0)+ positions = torch.where(+ positions < total_tokens,+ positions,+ torch.zeros_like(positions),+ )+ flat = labels.reshape(-1).index_fill(0, positions, ignore_index)+ return flat.view(labels.shape)++def clear_packed_caches():"""Release cached masks/metadata to free device memory."""_PACKED_INFO_CACHE.clear()@@ -684,5 +732,6 @@ __all__ = ["build_xformers_block_causal_mask","build_sdpa_packed_attention_mask","mask_packed_sequence_boundaries",+ "mask_packed_boundary_labels","clear_packed_caches",]