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.

Decide accepts_loss_kwargs from the loss head so gradient accumulation gets num_items_in_batch for every model (#12946)

Daniel Han99cee6418bed
diff --git a/tests/test_accepts_loss_kwargs_head_walk.py b/tests/test_accepts_loss_kwargs_head_walk.py
new file mode 100644
index 00000000000..2152f6cfdb6
--- /dev/null
+++ b/tests/test_accepts_loss_kwargs_head_walk.py
@@ -0,0 +1,1063 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+"""Under LoRA the accepts_loss_kwargs walk must reach the loss head, not the backbone."""
+
+import os
+import sys
+
+import pytest
+import torch
+from torch import nn
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from test_accepts_loss_kwargs_remote_mean_loss import _load, _models # noqa: E402
+
+
+_HEADS = '''
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+
+def unsloth_fused_ce_loss(**kwargs):
+ return kwargs
+
+
+def unsloth_fused_lm_head_loss(*args, **kwargs):
+ return kwargs
+
+
+class Backbone(nn.Module):
+ accepts_loss_kwargs = False
+
+ def forward(self, input_ids=None, **kwargs):
+ return input_ids
+
+
+class HFStyle(nn.Module):
+ base_model_prefix = "model"
+
+ @property
+ def base_model(self):
+ return getattr(self, self.base_model_prefix)
+
+
+class NativeForConditionalGeneration(HFStyle):
+ """Qwen2.5-VL / Gemma 3 shape: backbone declares False, head loss divides by the count."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ return self.loss_function(logits, labels, vocab_size=1, **kwargs)
+
+
+class StaleFlagForConditionalGeneration(NativeForConditionalGeneration):
+ """Gemma 4 on transformers 5.17: a stale False on the head itself."""
+ accepts_loss_kwargs = False
+
+
+class LegacyMeanForConditionalGeneration(HFStyle):
+ """Gemma 4 on transformers 5.5: attention filtered CrossEntropyLoss mean, kwargs unused."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ loss = None
+ if labels is not None:
+ shift_logits = logits[..., :-1, :]
+ shift_labels = labels[..., 1:]
+ if attention_mask is not None:
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :]
+ shift_logits = shift_logits[shift_attention_mask != 0].contiguous()
+ shift_labels = shift_labels[shift_attention_mask != 0].contiguous()
+ loss_fct = nn.CrossEntropyLoss()
+ loss = loss_fct(shift_logits.view(-1, 1), shift_labels.view(-1))
+ return loss
+
+
+def Compiled_forward(self, input_ids=None, labels=None, **kwargs):
+ hidden_states = self.model(input_ids)
+ n_items = None
+ if (kwargs) != () and type(kwargs) is dict:
+ n_items = (kwargs).get("num_items_in_batch", None)
+ if labels is None:
+ loss = None
+ elif n_items is not None:
+ loss = unsloth_fused_ce_loss(hidden_states=hidden_states, labels=labels, n_items=n_items)
+ else:
+ loss = self.loss_function(hidden_states, labels, vocab_size=1, **kwargs)
+ return loss
+
+
+class CompiledForConditionalGeneration(HFStyle):
+ """The compile cache's standalone class: a thin forward into the rewritten function."""
+ accepts_loss_kwargs = False
+
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return Compiled_forward(self, input_ids=input_ids, labels=labels, **kwargs)
+
+
+def _temporary_patch_wrap(forward):
+ # zoo temporary_patches/gemma4_moe.py: a functools.wraps wrapper over the compiled forward,
+ # so the class forward's own co_filename is the patch module, not the compile cache.
+ import functools
+
+ @functools.wraps(forward)
+ def wrapped(self, *args, **kwargs):
+ return forward(self, *args, **kwargs)
+ return wrapped
+
+
+class WrappedCompiledForConditionalGeneration(CompiledForConditionalGeneration):
+ forward = _temporary_patch_wrap(CompiledForConditionalGeneration.forward)
+
+
+class AstLegacyForCausalLM(HFStyle):
+ """zoo AST legacy route: fused, but the count is never passed, so the loss is a mean."""
+ accepts_loss_kwargs = True
+
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.lm_head = nn.Linear(1, 1)
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ hidden_states = self.model(input_ids)
+ if labels is not None:
+ loss = unsloth_fused_lm_head_loss(hidden_states, self.lm_head, labels)
+ else:
+ loss = None
+ return loss
+
+
+class MixedAuxForCausalLM(HFStyle):
+ """Main loss divides by the count, an auxiliary head loss is a plain mean (CSM depth decoder)."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ loss = self.loss_function(logits, labels, vocab_size=1, **kwargs)
+ aux = CrossEntropyLoss()(logits.view(-1, 1), labels.view(-1))
+ return loss + aux
+
+
+class ReturnLogitsFallbackForConditionalGeneration(HFStyle):
+ """zoo regex rewrite of a stock `loss_function(...)` without **kwargs (Qwen3-VL <= 5.16.1):
+ the fused branch gets the count, the UNSLOTH_RETURN_LOGITS=1 branch still returns a mean."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ n_items = kwargs.get("num_items_in_batch", None)
+ logits = self.model(input_ids)
+ if os.environ.get("UNSLOTH_RETURN_LOGITS", "0") == "0":
+ return unsloth_fused_ce_loss(hidden_states = logits, labels = labels, n_items = n_items)
+ return self.loss_function(logits, labels, vocab_size = 1)
+
+
+class CopiedKwargsForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **lm_kwargs):
+ loss_kwargs = dict(lm_kwargs)
+ logits = self.model(input_ids)
+ return self.loss_function(logits, labels, vocab_size=1, **loss_kwargs)
+
+
+class PoppedCountForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ kwargs.pop("num_items_in_batch", None)
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **kwargs)
+
+
+class FilteredCountForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ kwargs = {k: v for k, v in kwargs.items() if k != "num_items_in_batch"}
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **kwargs)
+
+
+class SwallowedCountForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, num_items_in_batch=None, **kwargs):
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **kwargs)
+
+
+class NestedLossForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ def compute(**kwargs):
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **kwargs)
+ return compute()
+
+
+class WrongKeyForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ n_items = kwargs.get("packed_seq_lengths")
+ if "num_items_in_batch" in kwargs:
+ pass
+ return unsloth_fused_ce_loss(hidden_states = self.model(input_ids), labels = labels, n_items = n_items)
+
+
+class OuterRewardModule(nn.Module):
+ """A user module holding an HF head but computing its own mean loss (ShieldGemma2-style shape)."""
+ def __init__(self):
+ super().__init__()
+ self.model = StaleFlagForConditionalGeneration()
+
+ def forward(self, input_ids=None, labels=None):
+ logits = self.model.model(input_ids)
+ return CrossEntropyLoss()(logits.view(-1, 1), labels.view(-1))
+
+
+class GuardedFallbackForConditionalGeneration(HFStyle):
+ """zoo regex rewrite after the count is threaded: fused branch, RETURN_LOGITS branch with the
+ count, non-causal branch passing it only when there is one."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ n_items = None
+ if n_items is None and 'kwargs' in locals():
+ n_items = kwargs.get("num_items_in_batch", None)
+ if n_items is None: n_items = kwargs.get("n_items", None)
+ logits = self.model(input_ids)
+ if os.environ.get("UNSLOTH_RETURN_LOGITS", "0") == "0":
+ return unsloth_fused_ce_loss(hidden_states = logits, labels = labels, n_items = n_items)
+ elif self.loss_function.__name__.endswith("ForCausalLMLoss"):
+ return self.loss_function(logits, labels, vocab_size = 1, num_items_in_batch = n_items)
+ return self.loss_function(logits, labels, vocab_size = 1, **({} if n_items is None else {'num_items_in_batch': n_items}))
+
+
+class UncountedStockLossForCausalLM(HFStyle):
+ """transformers 5.16 XGLM: a stock loss_function called without the count reduces by the mean."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.loss_function(self.model(input_ids), labels, vocab_size = 1)
+
+
+def _user_loss(logits, labels, vocab_size = None, **kwargs):
+ # Takes the keyword, still averages.
+ return CrossEntropyLoss()(logits.view(-1, 1), labels.view(-1))
+
+
+class CustomLossForCausalLM(NativeForConditionalGeneration):
+ def __init__(self):
+ super().__init__()
+ self.loss_function = _user_loss
+
+
+class DelegatedMethodMeanForCausalLM(HFStyle):
+ """ProphetNet: labels handed to a method that averages them."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def _compute_loss(self, logits, labels, ignore_index = -100):
+ return torch.nn.functional.nll_loss(logits, labels.view(-1), reduction = "mean")
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ loss = None
+ if labels is not None:
+ loss = self._compute_loss(logits, labels)
+ return loss
+
+
+class _PredLayer(nn.Module):
+ def forward(self, x, y = None):
+ return torch.nn.functional.cross_entropy(x, y.view(-1), reduction = "mean")
+
+
+class DelegatedChildMeanLMHeadModel(HFStyle):
+ """XLM: labels handed positionally to a child module whose forward averages them."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.pred_layer = _PredLayer()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.pred_layer(self.model(input_ids), labels)
+
+
+class _TextDecoder(nn.Module):
+ def forward(self, input_ids = None, labels = None, reduction = "mean", **kwargs):
+ loss_fct = CrossEntropyLoss(reduction = reduction, label_smoothing = 0.1)
+ return loss_fct(input_ids, labels)
+
+
+class DelegatedReductionForConditionalGeneration(HFStyle):
+ """BLIP captioning: labels plus an explicit reduction="mean" handed to the text decoder."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.text_decoder = _TextDecoder()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.text_decoder(input_ids = input_ids, labels = labels, reduction = "mean")
+
+
+class _CountingDecoder(nn.Module):
+ def forward(self, input_ids = None, labels = None, **kwargs):
+ return unsloth_fused_ce_loss(hidden_states = input_ids, labels = labels, n_items = kwargs.get("num_items_in_batch", None))
+
+
+class DelegatedCountForConditionalGeneration(HFStyle):
+ """Labels and **kwargs (the count) handed to a child that divides by it."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.decoder = _CountingDecoder()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.decoder(input_ids = input_ids, labels = labels, **kwargs)
+
+
+class DelegatedNoCountForConditionalGeneration(DelegatedCountForConditionalGeneration):
+ """Same child, but the count never reaches it, so it falls back to a mean."""
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.decoder(input_ids = input_ids, labels = labels)
+
+
+class CompositeMeanEncoderDecoderModel(HFStyle):
+ """EncoderDecoderModel: the count moved to the decoder's kwargs, the loss its own CE mean."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ kwargs_decoder = {}
+ if "num_items_in_batch" in kwargs:
+ kwargs_decoder["num_items_in_batch"] = kwargs.pop("num_items_in_batch", None)
+ logits = self.model(input_ids, **kwargs_decoder)
+ loss_fct = CrossEntropyLoss()
+ return loss_fct(logits.reshape(-1, 1), labels.view(-1))
+
+
+def Thin_forward(self, input_ids = None, labels = None, **kwargs):
+ logits = self.model(input_ids)
+ return CrossEntropyLoss()(logits.view(-1, 1), labels.view(-1))
+
+
+class ThinCompiledForConditionalGeneration(HFStyle):
+ """Qwen2-Audio in the compile cache: a thin class forward over a mean CE implementation."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids = None, labels = None, **kwargs):
+ return Thin_forward(self, input_ids = input_ids, labels = labels, **kwargs)
+
+
+class ClearedCarrierForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ extra = dict(kwargs)
+ extra.clear()
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **extra)
+
+
+class UpdatedCarrierForCausalLM(HFStyle):
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ kwargs.update(dict(scale = 1))
+ return self.loss_function(self.model(input_ids), labels, vocab_size=1, **kwargs)
+
+
+class ForwardingWrapper(nn.Module):
+ """A user wrapper under a custom attribute name, handing its **kwargs to the head."""
+ def __init__(self, head):
+ super().__init__()
+ self.inner = head
+
+ def forward(self, *args, **kwargs):
+ return self.inner(*args, **kwargs)
+
+
+class DroppingWrapper(nn.Module):
+ """A user wrapper that calls the head without the count."""
+ def __init__(self, head):
+ super().__init__()
+ self.inner = head
+
+ def forward(self, input_ids = None, labels = None, **kwargs):
+ return self.inner(input_ids = input_ids, labels = labels)
+
+
+def mask_attention_mask_out(labels = None, attention_mask = None):
+ return labels
+
+
+class WrappedLabelsReductionForConditionalGeneration(DelegatedReductionForConditionalGeneration):
+ """BLIP in the compile cache: labels handed on wrapped by the compiler's attention-mask helper."""
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
+ return self.text_decoder(
+ input_ids = input_ids,
+ labels = mask_attention_mask_out(labels = labels, attention_mask = attention_mask),
+ reduction = "mean",
+ )
+
+
+def unsloth_loss_count_kwargs(loss_function, n_items):
+ return {} if n_items is None else {"num_items_in_batch": n_items}
+
+
+class CountKwargsForCausalLM(HFStyle):
+ """zoo hook rewrite: the count reaches loss_function through unsloth_loss_count_kwargs."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ return self.loss_function(
+ logits, labels, vocab_size=1,
+ **unsloth_loss_count_kwargs(self.loss_function, kwargs.get("num_items_in_batch", None)),
+ )
+
+
+class FlaggedForwardingWrapper(nn.Module):
+ """A user wrapper with its own stale flag, forwarding **kwargs to an `inner` head."""
+ accepts_loss_kwargs = False
+
+ def __init__(self, inner):
+ super().__init__()
+ self.inner = inner
+
+ def forward(self, *args, **kwargs):
+ return self.inner(*args, **kwargs)
+
+
+class NoneCountWrapper(nn.Module):
+ """Names the count but hands its child None, so the count never reaches the head."""
+ def __init__(self, inner):
+ super().__init__()
+ self.inner = inner
+
+ def forward(self, input_ids=None, labels=None):
+ return self.inner(input_ids=input_ids, labels=labels, num_items_in_batch=None)
+
+
+class KwOnlyMeanDelegateForCausalLM(HFStyle):
+ """Hands labels to a helper whose keyword-only reduction defaults to a mean."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def _loss(self, logits, labels, *, reduction="mean"):
+ return torch.nn.functional.cross_entropy(logits, labels, reduction=reduction)
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ return self._loss(logits, labels)
+
+
+class MarkedForConditionalGeneration(NativeForConditionalGeneration):
+ _unsloth_counts_unshifted_labels = True
+
+
+class FallbackCountReadForCausalLM(HFStyle):
+ """zoo count route: n_items falls back to the alias when num_items_in_batch is present but None."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ return unsloth_count_aware_cross_entropy(logits, labels, n_items=(kwargs.get('num_items_in_batch', None) if kwargs.get('num_items_in_batch', None) is not None else kwargs.get('n_items', None)), shift=False)
+
+
+class LoraLike(nn.Module):
+ """peft BaseTuner: the wrapped model under `model`, unknown attributes forwarded to it."""
+ def __init__(self, model):
+ super().__init__()
+ self.model = model
+
+ def __getattr__(self, name):
+ try:
+ return super().__getattr__(name)
+ except AttributeError:
+ return getattr(self.model, name)
+
+
+
+class _MeanDecoder(nn.Module):
+ def forward(self, input_ids = None, labels = None, **kwargs):
+ return CrossEntropyLoss()(input_ids.view(-1, 1), labels.view(-1))
+
+
+class CountedWithDelegatedMeanForCausalLM(HFStyle):
+ """Main loss divides by the count, an auxiliary mean is computed by a child receiving labels."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.aux_decoder = _MeanDecoder()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ loss = self.loss_function(logits, labels, vocab_size=1, **kwargs)
+ return loss + self.aux_decoder(input_ids = logits, labels = labels)
+
+
+class MixedDelegatesForConditionalGeneration(HFStyle):
+ """One child divides by the count, another averages: not provably either."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.decoder = _CountingDecoder()
+ self.aux_decoder = _MeanDecoder()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.decoder(input_ids = input_ids, labels = labels, **kwargs) + self.aux_decoder(input_ids = input_ids, labels = labels)
+
+
+class DelegatedPositionalSumForConditionalGeneration(HFStyle):
+ """reduction="sum" passed positionally must override the child's "mean" default."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+ self.text_decoder = _TextDecoder()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.text_decoder(input_ids, labels, "sum")
+
+
+def Dropping_forward(self, input_ids=None, labels=None, **kwargs):
+ return unsloth_fused_ce_loss(hidden_states=input_ids, labels=labels, n_items=kwargs.get("num_items_in_batch", None))
+
+
+class DroppingThinForConditionalGeneration(HFStyle):
+ """A thin class forward that never hands its **kwargs to the implementation."""
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return Dropping_forward(self, input_ids=input_ids, labels=labels)
+
+
+class OwnsModuleChildForCausalLM(nn.Module):
+ """A loss head whose backbone is `transformer` and which also owns a child named `module`."""
+ def __init__(self):
+ super().__init__()
+ self.transformer = Backbone()
+ self.module = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ return self.loss_function(self.transformer(input_ids), labels, vocab_size=1, **kwargs)
+
+class PeftModelForCausalLM(nn.Module):
+ def __init__(self, model):
+ super().__init__()
+ self.base_model = LoraLike(model)
+
+ def get_base_model(self):
+ return self.base_model.model
+
+ def forward(self, *args, **kwargs):
+ return self.get_base_model()(*args, **kwargs)
+'''
+
+
+def ns():
+ return _load()
+
+
+def mods(tmp_path):
+ return _models(tmp_path, _HEADS, "loss_heads_for_ga_test")
+
+
+def _trainer_sees(model):
+ head = model.get_base_model() if hasattr(model, "get_base_model") else model
+ if hasattr(head, "accepts_loss_kwargs"):
+ return head.accepts_loss_kwargs
+ import inspect
+
+ return any(
+ p.kind == inspect.Parameter.VAR_KEYWORD
+ for p in inspect.signature(head.forward).parameters.values()
+ )
+
+
+def test_old_getattr_walk_lands_on_the_backbone(mods):
+ peft = mods.PeftModelForCausalLM(mods.NativeForConditionalGeneration())
+ assert type(peft.base_model.base_model).__name__ == "Backbone"
+
+
+def test_walk_reaches_the_head_under_peft(ns, mods):
+ head = mods.NativeForConditionalGeneration()
+ peft = mods.PeftModelForCausalLM(head)
+ chain = [type(m).__name__ for m in ns["_loss_kwargs_chain"](peft)]
+ assert chain == [
+ "PeftModelForCausalLM",
+ "LoraLike",
+ "NativeForConditionalGeneration",
+ "Backbone",
+ ]
+ assert ns["_loss_head"](peft) is head
+
+
[email protected]("wrap", ["data_parallel", "torch_compile"])
+def test_walk_reaches_the_head_through_training_wrappers(ns, mods, wrap):
+ head = mods.NativeForConditionalGeneration()
+ peft = mods.PeftModelForCausalLM(head)
+ outer = torch.nn.DataParallel(peft) if wrap == "data_parallel" else torch.compile(peft)
+ assert any(m is head for m in ns["_loss_kwargs_chain"](outer))
+ assert ns["_loss_head"](outer) is head
+
+
[email protected]("attr", ["module", "_orig_mod", "_fsdp_wrapped_module"])
+def test_a_plain_module_with_a_wrapper_named_child_is_not_a_training_wrapper(ns, mods, attr):
+ outer = nn.Module()
+ outer.add_module(attr, mods.NativeForConditionalGeneration())
+ assert ns["_loss_head"](outer) is None
+
+
+ "cls",
+ [
+ "NativeForConditionalGeneration",
+ "StaleFlagForConditionalGeneration",
+ "CompiledForConditionalGeneration",
+ "WrappedCompiledForConditionalGeneration",
+ ],
+)
+def test_a_consuming_head_gets_the_count_despite_a_false_flag(ns, mods, cls):
+ head = getattr(mods, cls)()
+ peft = mods.PeftModelForCausalLM(head)
+ result = ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert result.startswith("True"), result
+ assert _trainer_sees(peft) is True
+ assert _trainer_sees(head) is True
+
+
+def test_full_finetuning_head_gets_the_count(ns, mods):
+ head = mods.StaleFlagForConditionalGeneration()
+ ns["apply_accepts_loss_kwargs_fix"](head)
+ assert head.accepts_loss_kwargs is True
+
+
+def test_a_legacy_mean_head_falls_back(ns, mods):
+ head = mods.LegacyMeanForConditionalGeneration()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is False
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is False
+
+
+def test_fused_without_the_count_is_a_mean_even_if_declared(ns, mods):
+ head = mods.AstLegacyForCausalLM()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is False
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is False
+
+
+def test_mixed_main_and_aux_mean_is_undecided(ns, mods):
+ assert ns["_forward_consumes_num_items_in_batch"](mods.MixedAuxForCausalLM()) is None
+
+
+def test_a_mean_fallback_branch_is_undecided(ns, mods, monkeypatch):
+ head = mods.ReturnLogitsFallbackForConditionalGeneration()
+ monkeypatch.setitem(ns, "_zoo_counts_fallback_branches", lambda: True)
+ assert ns["_forward_consumes_num_items_in_batch"](head) is None
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is False
+
+
+def test_an_older_zoo_keeps_the_fused_branch_answer(ns, mods, monkeypatch):
+ # An older unsloth_zoo never gives these fallbacks the count; only the fused branch trains.
+ head = mods.ReturnLogitsFallbackForConditionalGeneration()
+ monkeypatch.setitem(ns, "_zoo_counts_fallback_branches", lambda: False)
+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS", raising = False)
+ assert ns["_forward_consumes_num_items_in_batch"](head) is True
+ monkeypatch.setenv("UNSLOTH_RETURN_LOGITS", "1")
+ assert ns["_forward_consumes_num_items_in_batch"](head) is None
+ monkeypatch.delenv("UNSLOTH_RETURN_LOGITS")
+ monkeypatch.setitem(ns, "_zoo_counts_fallback_branches", lambda: True)
+ assert ns["_forward_consumes_num_items_in_batch"](head) is None
+
+
+def test_copied_kwargs_dict_counts(ns, mods):
+ assert ns["_forward_consumes_num_items_in_batch"](mods.CopiedKwargsForCausalLM()) is True
+
+
+def test_a_second_call_redecides_its_own_shadow(ns, mods):
+ head = mods.StaleFlagForConditionalGeneration()
+ ns["apply_accepts_loss_kwargs_fix"](head)
+ assert head.accepts_loss_kwargs is True
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is True
+ legacy = mods.AstLegacyForCausalLM.forward.__get__(head)
+ head.forward = legacy
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is False
+
+
+def test_a_user_assignment_on_the_head_still_wins(ns, mods):
+ head = mods.LegacyMeanForConditionalGeneration()
+ head.accepts_loss_kwargs = True
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert head.accepts_loss_kwargs is True
+ assert peft.accepts_loss_kwargs is True
+
+
+def test_remote_mean_loss_stays_false_under_the_peft_walk(ns, tmp_path, mods):
+ remote = _models(tmp_path)
+ head = remote.NemotronHForCausalLM()
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert head.accepts_loss_kwargs is False
+ assert _trainer_sees(peft) is False
+
+
+def _bare(cls):
+ obj = cls.__new__(cls)
+ nn.Module.__init__(obj)
+ return obj
+
+
+ "module, name",
+ [
+ ("transformers.models.gemma4.modeling_gemma4", "Gemma4ForConditionalGeneration"),
+ (
+ "transformers.models.qwen2_5_vl.modeling_qwen2_5_vl",
+ "Qwen2_5_VLForConditionalGeneration",
+ ),
+ ("transformers.models.gemma3.modeling_gemma3", "Gemma3ForConditionalGeneration"),
+ ("transformers.models.llama.modeling_llama", "LlamaForCausalLM"),
+ ],
+)
+def test_installed_transformers_heads_consume(ns, module, name):
+ import importlib
+
+ try:
+ cls = getattr(importlib.import_module(module), name)
+ except Exception as exc:
+ pytest.skip(reason = f"{name} not in the installed transformers: {exc}")
+ import inspect
+
+ source = inspect.getsource(cls.forward)
+ result = ns["_forward_consumes_num_items_in_batch"](_bare(cls))
+ import ast
+ import textwrap
+
+ counted = any(
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "loss_function"
+ and any(kw.arg in (None, "num_items_in_batch") for kw in node.keywords)
+ for node in ast.walk(ast.parse(textwrap.dedent(source)))
+ )
+ if not counted:
+ assert result is not True
+ return
+ assert result is True
+
+
+ "cls",
+ [
+ "PoppedCountForCausalLM",
+ "FilteredCountForCausalLM",
+ "SwallowedCountForCausalLM",
+ "NestedLossForCausalLM",
+ "WrongKeyForCausalLM",
+ ],
+)
+def test_a_count_dropped_before_the_loss_is_not_consuming(ns, mods, cls):
+ assert ns["_forward_consumes_num_items_in_batch"](getattr(mods, cls)()) is not True
+
+
+def test_an_outer_module_with_its_own_loss_is_not_its_inner_head(ns, mods):
+ outer = mods.OuterRewardModule()
+ assert ns["_loss_head"](outer) is None
+ peft = mods.PeftModelForCausalLM(outer)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is not True
+
+
+def test_a_fully_threaded_fallback_is_consuming(ns, mods):
+ head = mods.GuardedFallbackForConditionalGeneration()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is True
+
+
+def test_the_count_aware_cross_entropy_helper_is_a_counted_loss(ns, tmp_path):
+ from test_accepts_loss_kwargs_remote_mean_loss import _models as _mk
+
+ src = (
+ _HEADS
+ + """
+
+def unsloth_count_aware_cross_entropy(logits, labels, n_items = None, **kwargs):
+ return logits
+
+
+class AlignedCountedForCausalLM(HFStyle):
+ _unsloth_counts_unshifted_labels = True
+
+ def __init__(self):
+ super().__init__()
+ self.model = Backbone()
+
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ n_items = kwargs.get("num_items_in_batch", None)
+ logits = self.model(input_ids)
+ return unsloth_count_aware_cross_entropy(logits, labels, n_items = n_items, shift = False)
+
+
+class AlignedUncountedForCausalLM(AlignedCountedForCausalLM):
+ def forward(self, input_ids=None, labels=None, **kwargs):
+ logits = self.model(input_ids)
+ return unsloth_count_aware_cross_entropy(logits, labels, shift = False)
+"""
+ )
+ m = _mk(tmp_path, src, "count_aware_heads")
+ assert ns["_forward_consumes_num_items_in_batch"](m.AlignedCountedForCausalLM()) is True
+ assert ns["_forward_consumes_num_items_in_batch"](m.AlignedUncountedForCausalLM()) is False
+
+
+ "cls",
+ [
+ "UncountedStockLossForCausalLM",
+ "DelegatedMethodMeanForCausalLM",
+ "DelegatedChildMeanLMHeadModel",
+ "DelegatedReductionForConditionalGeneration",
+ "DelegatedNoCountForConditionalGeneration",
+ "CompositeMeanEncoderDecoderModel",
+ "ThinCompiledForConditionalGeneration",
+ "WrappedLabelsReductionForConditionalGeneration",
+ ],
+)
+def test_a_mean_loss_reached_through_labels_is_false(ns, mods, cls):
+ head = getattr(mods, cls)()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is False
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert _trainer_sees(peft) is False
+
+
+def test_labels_and_the_count_handed_to_a_counting_child_consume(ns, mods):
+ head = mods.DelegatedCountForConditionalGeneration()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is True
+
+
+def test_a_user_loss_function_is_undecided(ns, mods):
+ assert ns["_forward_consumes_num_items_in_batch"](mods.CustomLossForCausalLM()) is None
+
+
[email protected]("cls", ["ClearedCarrierForCausalLM", "UpdatedCarrierForCausalLM"])
+def test_a_mutated_carrier_is_not_consuming(ns, mods, cls):
+ assert ns["_forward_consumes_num_items_in_batch"](getattr(mods, cls)()) is not True
+
+
+def test_a_forwarding_wrapper_head_is_shadowed_too(ns, mods):
+ head = mods.StaleFlagForConditionalGeneration()
+ wrapper = mods.ForwardingWrapper(head)
+ peft = mods.PeftModelForCausalLM(wrapper)
+ assert ns["_loss_head"](peft) is head
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert wrapper.accepts_loss_kwargs is True
+ assert head.accepts_loss_kwargs is True
+ assert ns["_instance_accepts_loss_kwargs"](peft) is None
+
+
+def test_a_wrapper_dropping_the_count_is_not_transparent(ns, mods):
+ head = mods.NativeForConditionalGeneration()
+ assert ns["_loss_head"](mods.DroppingWrapper(head)) is None
+
+
+ "module, name",
+ [
+ ("transformers.models.xlm.modeling_xlm", "XLMWithLMHeadModel"),
+ ("transformers.models.encoder_decoder.modeling_encoder_decoder", "EncoderDecoderModel"),
+ ("transformers.models.speecht5.modeling_speecht5", "SpeechT5ForSpeechToText"),
+ (
+ "transformers.models.prophetnet.modeling_prophetnet",
+ "ProphetNetForConditionalGeneration",
+ ),
+ ],
+)
+def test_installed_transformers_delegated_or_composite_heads(ns, module, name):
+ import importlib
+
+ try:
+ cls = getattr(importlib.import_module(module), name)
+ except Exception as exc:
+ pytest.skip(reason = f"{name} not in the installed transformers: {exc}")
+ head = _bare(cls)
+ assert ns["_loss_head"](head) is head
+ assert ns["_forward_consumes_num_items_in_batch"](head) is not True
+
+
+def test_installed_transformers_classification_heads_are_still_not_loss_heads(ns):
+ from transformers.models.llama.modeling_llama import LlamaForSequenceClassification
+ assert ns["_loss_head"](_bare(LlamaForSequenceClassification)) is None
+
+
+def test_the_count_through_unsloth_loss_count_kwargs_is_consuming(ns, mods):
+ assert ns["_forward_consumes_num_items_in_batch"](mods.CountKwargsForCausalLM()) is True
+
+
+def test_a_wrapper_with_its_own_stale_flag_gets_the_decision(ns, mods):
+ outer = mods.FlaggedForwardingWrapper(mods.NativeForConditionalGeneration())
+ ns["apply_accepts_loss_kwargs_fix"](outer)
+ assert outer.accepts_loss_kwargs is True
+ assert outer.inner.accepts_loss_kwargs is True
+
+
+def test_a_wrapper_passing_a_none_count_is_not_transparent(ns, mods):
+ outer = mods.NoneCountWrapper(mods.NativeForConditionalGeneration())
+ assert ns["_loss_head"](outer) is None
+
+
+def test_a_keyword_only_mean_default_in_a_delegate_is_false(ns, mods):
+ head = mods.KwOnlyMeanDelegateForCausalLM()
+ assert ns["_forward_consumes_num_items_in_batch"](head) is False
+
+
+def test_the_count_convention_is_recorded_for_the_batch_counter(ns, mods):
+ shifted = mods.PeftModelForCausalLM(mods.NativeForConditionalGeneration())
+ ns["apply_accepts_loss_kwargs_fix"](shifted)
+ assert ns["_num_items_labels"](shifted) == "shifted"
+ assert shifted.get_base_model().__dict__["_unsloth_num_items_labels"] == "shifted"
+
+ unshifted = mods.PeftModelForCausalLM(mods.MarkedForConditionalGeneration())
+ ns["apply_accepts_loss_kwargs_fix"](unshifted)
+ assert ns["_num_items_labels"](unshifted) == "unshifted"
+
+ mean = mods.PeftModelForCausalLM(mods.AstLegacyForCausalLM())
+ ns["apply_accepts_loss_kwargs_fix"](mean)
+ assert ns["_num_items_labels"](mean) is None
+
+
+def test_a_recorded_convention_is_dropped_when_the_forward_stops_counting(ns, mods):
+ head = mods.NativeForConditionalGeneration()
+ peft = mods.PeftModelForCausalLM(head)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert ns["_num_items_labels"](peft) == "shifted"
+ head.forward = mods.AstLegacyForCausalLM.forward.__get__(head)
+ head.lm_head = nn.Linear(1, 1)
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert ns["_num_items_labels"](peft) is None
+
+
+def test_the_dispatcher_reads_the_recorded_convention_through_a_training_wrapper(ns, mods):
+ pytest.importorskip("unsloth_zoo.loss_utils").__dict__.get(
+ "counts_unshifted_labels"
+ ) or pytest.skip(reason = "unsloth_zoo without the unshifted-label count")
+ peft = mods.PeftModelForCausalLM(mods.MarkedForConditionalGeneration())
+ ns["apply_accepts_loss_kwargs_fix"](peft)
+ assert ns["_head_counts_unshifted_labels"](torch.nn.DataParallel(peft)) is True
+ plain = mods.PeftModelForCausalLM(mods.NativeForConditionalGeneration())
+ ns["apply_accepts_loss_kwargs_fix"](plain)
+ assert ns["_head_counts_unshifted_labels"](torch.nn.DataParallel(plain)) is False
+
+
+def test_a_conditional_count_read_is_consuming(ns, mods):
+ assert ns["_forward_consumes_num_items_in_batch"](mods.FallbackCountReadForCausalLM()) is True
+
+
+def test_a_counted_loss_beside_a_delegated_mean_is_undecided(ns, mods):
+ assert (
+ ns["_forward_consumes_num_items_in_batch"](mods.CountedWithDelegatedMeanForCausalLM())
+ is None
+ )
+
+
+def test_mixed_delegated_verdicts_are_undecided(ns, mods):
+ assert (
+ ns["_forward_consumes_num_items_in_batch"](mods.MixedDelegatesForConditionalGeneration())
+ is None
+ )
+
+
+def test_a_positional_reduction_overrides_the_delegate_default(ns, mods):
+ assert (
+ ns["_forward_consumes_num_items_in_batch"](
+ mods.DelegatedPositionalSumForConditionalGeneration()
+ )
+ is None
+ )
+
+
+def test_a_thin_forward_that_drops_kwargs_is_not_unwrapped(ns, mods):
+ assert (
+ ns["_forward_consumes_num_items_in_batch"](mods.DroppingThinForConditionalGeneration())
+ is False
+ )
+
+
+def test_a_child_named_module_is_not_walked_as_a_wrapper(ns, mods):
+ head = mods.OwnsModuleChildForCausalLM()
+ assert ns["_loss_kwargs_child"](head) is not head.module
+
+
+def test_a_compiled_wrapper_keeps_the_value_and_its_marker_together(ns, mods):
+ head = mods.StaleFlagForConditionalGeneration()
+ compiled = torch.compile(head, backend = "eager")
+ ns["apply_accepts_loss_kwargs_fix"](compiled)
+ inner = compiled._orig_mod.__dict__
+ assert inner["accepts_loss_kwargs"] is True and ns["_is_guess"](inner)
+ assert compiled.__dict__["accepts_loss_kwargs"] is True and ns["_is_guess"](compiled.__dict__)
diff --git a/tests/test_accepts_loss_kwargs_remote_mean_loss.py b/tests/test_accepts_loss_kwargs_remote_mean_loss.py
index 3b36255efd5..a6050e23cfa 100644
--- a/tests/test_accepts_loss_kwargs_remote_mean_loss.py
+++ b/tests/test_accepts_loss_kwargs_remote_mean_loss.py
@@ -32,8 +32,13 @@ from torch.nn import CrossEntropyLoss
_UTILS = pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "models" / "_utils.py"
_NAMES = {
- "_unsloth_compile_cache_leaves",
- "_forward_is_unsloth_compiled",
+ "_head_counts_unshifted_labels",
+ "_loss_kwargs_levels",
+ "_NUM_ITEMS_LABELS",
+ "_record_num_items_labels",
+ "_num_items_labels",
+ "_training_wrapper_types",
+ "_is_training_wrapper",
"_find_concrete_accepts_loss_kwargs",
"_shadow_accepts_loss_kwargs",
"_forward_ignores_num_items_in_batch",
@@ -51,6 +56,29 @@ _NAMES = {
"_is_guess",
"_TORCH_CE",
"apply_accepts_loss_kwargs_fix",
+ "_UNSLOTH_WRAPPED_MODULE_ATTRS",
+ "_LOSS_KWARGS_CHILDREN",
+ "_loss_kwargs_child",
+ "_LOSS_HEAD_NAMES",
+ "_loss_head",
+ "_call_forwards_count",
+ "_forward_function_node",
+ "_N_ITEMS_KEYWORDS",
+ "_FUSED_LOSS_CALLEES",
+ "_kwargs_carriers",
+ "_classify_loss_forward",
+ "_resolve_callee",
+ "_ce_reductions",
+ "_known_loss_function",
+ "_zoo_counts_fallback_branches",
+ "_old_zoo_fallbacks_only",
+ "_CARRIER_MUTATORS",
+ "_nested_scope_ids",
+ "_pass_through_child",
+ "_local_assignments",
+ "_is_count_get",
+ "_forward_consumes_num_items_in_batch",
+ "_head_default_accepts_loss_kwargs",
}
@@ -244,6 +272,9 @@ class _PeftLike(nn.Module):
self.base_model = types.SimpleNamespace(model = inner)
self.base_model.base_model = None
+ def get_base_model(self):
+ return self.base_model.model
+
def forward(self, *args, **kwargs):
return None
diff --git a/tests/test_seq2seq_auto_class.py b/tests/test_seq2seq_auto_class.py
index 9fe5886a8d2..2ce6705e1b9 100644
--- a/tests/test_seq2seq_auto_class.py
+++ b/tests/test_seq2seq_auto_class.py
@@ -91,6 +91,67 @@ def test_get_batch_samples_dispatch():
_utils._unsloth_get_batch_samples = original
+def test_a_marked_head_is_counted_by_unsloth_zoo(monkeypatch):
+ from types import SimpleNamespace
+ from unsloth.models import _utils
+
+ calls = []
+ dispatch = _utils._make_seq2seq_aware_get_batch_samples(
+ lambda self, *a, **k: calls.append("stock") or "stock"
+ )
+ monkeypatch.setattr(
+ _utils,
+ "_unsloth_get_batch_samples",
+ lambda self, *a, **k: calls.append("unsloth") or "unsloth",
+ )
+
+ class MarkedHead:
+ _unsloth_counts_unshifted_labels = True
+
+ def __init__(self, name):
+ self.config = _config(name)
+
+ class Peft:
+ def __init__(self, head):
+ self.config = head.config
+ self._head = head
+
+ def get_base_model(self):
+ return self._head
+
+ zoo = pytest.importorskip("unsloth_zoo.loss_utils")
+ if not hasattr(zoo, "counts_unshifted_labels"):
+ pytest.skip(reason = "unsloth_zoo predates the unshifted-label marker")
+ for name in ("T5Gemma2Config", "WhisperConfig", "LlamaConfig"):
+ assert dispatch(SimpleNamespace(model = MarkedHead(name)), iter([]), 1) == "unsloth"
+ assert dispatch(SimpleNamespace(model = Peft(MarkedHead(name))), iter([]), 1) == "unsloth"
+ unmarked = SimpleNamespace(config = _config("T5Gemma2Config"))
+ assert dispatch(SimpleNamespace(model = unmarked), iter([]), 1) == "stock"
+
+
+def test_an_older_zoo_without_the_marker_keeps_stock_seq2seq(monkeypatch):
+ import builtins
+ from types import SimpleNamespace
+ from unsloth.models import _utils
+
+ real_import = builtins.__import__
+
+ def no_marker(
+ name,
+ globals = None,
+ locals = None,
+ fromlist = (),
+ level = 0,
+ ):
+ if name == "unsloth_zoo.loss_utils" and fromlist and "counts_unshifted_labels" in fromlist:
+ raise ImportError("old unsloth_zoo")
+ return real_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", no_marker)
+ head = SimpleNamespace(config = _config("T5Gemma2Config"), _unsloth_counts_unshifted_labels = True)
+ assert _utils._head_counts_unshifted_labels(head) is False
+
+
@pytest.mark.parametrize(
"name, expected",
[
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 9b76c8e5caf..c23a085c9c8 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -4815,8 +4815,18 @@ def _unsloth_pre_compute_loss(self, model, inputs, *args, **kwargs):
inner_model = inner_model.model
name = inner_model.__class__.__name__
+ if getattr(self, "model_accepts_loss_kwargs", True):
+ reason = (
+ f"`num_items_in_batch` could not be counted for {name}'s labels, "
+ "so each micro-batch loss is a mean."
+ )
+ else:
+ reason = (
+ f"{name} does not accept `num_items_in_batch`: its forward does not "
+ "pass it to the loss."
+ )
logger.warning_once(
- f"Unsloth: Not an error, but {name} does not accept `num_items_in_batch`.\n"
+ f"Unsloth: Not an error, but {reason}\n"
"Using gradient accumulation will be very slightly less accurate.\n"
"Read more on gradient accumulation issues here: https://unsloth.ai/blog/gradient"
)
@@ -5006,10 +5016,35 @@ def _is_seq2seq_lm_config(config):
return False
+def _head_counts_unshifted_labels(model):
+ # unsloth_zoo marks heads that average unshifted labels and counts them; an older zoo has neither.
+ try:
+ from unsloth_zoo.loss_utils import counts_unshifted_labels
+ except Exception:
+ return False
+ if model is None:
+ return False
+ recorded = _num_items_labels(model)
+ if recorded is not None:
+ return recorded == "unshifted"
+ try:
+ head = _loss_head(model)
+ except Exception:
+ head = None
+ if head is None:
+ try:
+ head = model.get_base_model() if hasattr(model, "get_base_model") else model
+ except Exception:
+ head = model
+ return counts_unshifted_labels(head)
+
+
def _make_seq2seq_aware_get_batch_samples(original):
def _unsloth_get_batch_samples_dispatch(self, *args, **kwargs):
# Seq2Seq labels are unshifted, so the causal labels[..., 1:] token count drops one per row and inflates the GA loss.
- if _is_seq2seq_lm_config(getattr(self.model, "config", None)):
+ if _head_counts_unshifted_labels(getattr(self, "model", None)):
+ return _unsloth_get_batch_samples(self, *args, **kwargs)
+ if _is_seq2seq_lm_config(getattr(getattr(self, "model", None), "config", None)):
return original(self, *args, **kwargs)
return _unsloth_get_batch_samples(self, *args, **kwargs)
@@ -5195,128 +5230,752 @@ def patch_gradient_accumulation_fix(Trainer):
Trainer._unsloth_init_wrapped_for_accelerate_gas = True
-def _unsloth_compile_cache_leaves():
- leaves = {"unsloth_compiled_cache", "unsloth_cache", "unsloth_compiled"}
- loc = os.environ.get("UNSLOTH_COMPILE_LOCATION", "") or ""
- loc = loc.rstrip("/\\")
- if loc:
- leaves.add(os.path.basename(loc) or loc)
- return leaves
+# Real children only: PEFT's LoraModel forwards `base_model` to the backbone, skipping the loss head.
+_LOSS_KWARGS_CHILDREN = ("base_model", "model") + _UNSLOTH_WRAPPED_MODULE_ATTRS
-def _forward_is_unsloth_compiled(model):
- # True iff forward was installed from the Unsloth compile cache directory. __module__ stays the transformers module, so check co_filename.
- leaves = _unsloth_compile_cache_leaves()
+def _loss_kwargs_child(m):
+ d = getattr(m, "__dict__", None) or {}
+ modules = d.get("_modules") or {}
+ for name in _LOSS_KWARGS_CHILDREN:
+ if name in _UNSLOTH_WRAPPED_MODULE_ATTRS and not _is_training_wrapper(m):
+ continue
+ nxt = modules.get(name)
+ if nxt is None:
+ nxt = d.get(name)
+ if nxt is not None and nxt is not m:
+ return nxt
+ if isinstance(m, torch.nn.Module) and not any(k in type(m).__name__ for k in _LOSS_HEAD_NAMES):
+ return _pass_through_child(m, modules)
+ return None
- def check(m):
- if m is None:
- return False
- fwd = getattr(type(m), "forward", None)
- if fwd is None:
- return False
- code = getattr(fwd, "__code__", None)
- fn = getattr(code, "co_filename", "") if code is not None else ""
- fn = fn.replace("\\", "/")
- parts = set(fn.split("/"))
- return any(leaf in parts for leaf in leaves)
- if check(model):
- return True
+def _loss_kwargs_chain(model):
seen = set()
m = model
- for _ in range(4):
+ for _ in range(8):
if m is None or id(m) in seen:
break
seen.add(id(m))
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- if nxt is None or nxt is m:
- break
- if check(nxt):
- return True
- m = nxt
- return False
+ yield m
+ m = _loss_kwargs_child(m)
+ try:
+ head = model.get_base_model() if hasattr(model, "get_base_model") else None
+ except Exception:
+ head = None
+ if head is not None and id(head) not in seen:
+ yield head
def _find_concrete_accepts_loss_kwargs(model):
- # Walk the wrapper chain for the first class declaring accepts_loss_kwargs in its own __mro__ dict, avoiding PEFT __getattr__ forwarding and our own shadow.
- seen = set()
- m = model
- for _ in range(6):
- if m is None or id(m) in seen:
- break
- seen.add(id(m))
+ # First class declaring accepts_loss_kwargs in its own __mro__ dict, avoiding PEFT __getattr__ forwarding and our own shadow.
+ for m in _loss_kwargs_chain(model):
for klass in type(m).__mro__:
if "accepts_loss_kwargs" in klass.__dict__:
return klass.__dict__[
"accepts_loss_kwargs"
], f"{klass.__name__}.accepts_loss_kwargs"
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- if nxt is None or nxt is m:
- break
- m = nxt
return None, "no explicit accepts_loss_kwargs on any wrapper level"
+# Marks a value Unsloth wrote, so a later call re-decides it instead of reading it as a declaration.
_GUESSED_LOSS_KWARGS = "_unsloth_guessed_accepts_loss_kwargs"
-def _shadow_accepts_loss_kwargs(
- model,
- value,
- guessed = False,
-):
- # Set the attribute at every wrapper level so HF's hasattr check resolves wherever accelerator or peft unwrap lands.
- # guessed marks values the source heuristic wrote, so a later call re-checks them instead of trusting them.
- seen = set()
- m = model
- for _ in range(8):
- if m is None or id(m) in seen:
- break
- seen.add(id(m))
+def _loss_kwargs_levels(model):
+ levels = list(_loss_kwargs_chain(model))
+ try:
+ head = _loss_head(model)
+ except Exception:
+ head = None
+ if head is not None and all(head is not m for m in levels):
+ levels.append(head)
+ return levels
+
+
+def _shadow_accepts_loss_kwargs(model, value):
+ for m in _loss_kwargs_levels(model):
+ d = getattr(m, "__dict__", None)
+ if d is None:
+ continue
+ if "accepts_loss_kwargs" in d and not _is_guess(d):
+ continue
+ # Via __dict__: OptimizedModule forwards setattr to _orig_mod, parting the value from its marker.
try:
- setattr(m, "accepts_loss_kwargs", value)
- if guessed:
- m.__dict__[_GUESSED_LOSS_KWARGS] = value
- else:
- m.__dict__.pop(_GUESSED_LOSS_KWARGS, None)
+ d["accepts_loss_kwargs"] = value
+ d[_GUESSED_LOSS_KWARGS] = value
except Exception:
pass
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- if nxt is None or nxt is m:
- break
- m = nxt
-def apply_accepts_loss_kwargs_fix(model):
- # Shadow accepts_loss_kwargs on the model so HF Trainer sees it via hasattr(unwrapped_model). Priority: compiled forward -> True, else the first class attr in the chain, else the HF default (#4982).
- if _forward_is_unsloth_compiled(model):
- _shadow_accepts_loss_kwargs(model, True)
- return "True (Unsloth compiled forward)"
+_LOSS_HEAD_NAMES = (
+ "CausalLM",
+ "ForConditionalGeneration",
+ "LMHead",
+ "VisionText2Text",
+ "EncoderDecoderModel",
+ "ForSpeechToText",
+)
+
+def _training_wrapper_types():
+ types_ = [torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel]
+ try:
+ from torch._dynamo.eval_frame import OptimizedModule
+ types_.append(OptimizedModule)
+ except Exception:
+ pass
+ try:
+ from torch.distributed.fsdp import FullyShardedDataParallel
+ types_.append(FullyShardedDataParallel)
+ except Exception:
+ pass
+ return tuple(types_)
+
+
+def _is_training_wrapper(m):
+ # Only real training wrappers: a user module with a child named `module` keeps its own loss.
+ return isinstance(m, _training_wrapper_types())
+
+
+def _loss_head(model):
+ m, seen = model, set()
+ while m is not None and id(m) not in seen:
+ seen.add(id(m))
+ if hasattr(m, "get_base_model"):
+ try:
+ m = m.get_base_model()
+ except Exception:
+ return None
+ continue
+ modules = getattr(m, "__dict__", {}).get("_modules") or {}
+ wrapped = (
+ next((modules[a] for a in _UNSLOTH_WRAPPED_MODULE_ATTRS if a in modules), None)
+ if _is_training_wrapper(m)
+ else None
+ )
+ if wrapped is not None:
+ m = wrapped
+ continue
+ if type(m).__module__.startswith("peft."):
+ m = modules.get("model")
+ continue
+ if any(k in type(m).__name__ for k in _LOSS_HEAD_NAMES):
+ return m
+ m = _pass_through_child(m, modules)
+ return None
+
+
+def _pass_through_child(m, modules):
+ try:
+ tree = ast.parse(textwrap.dedent(inspect.getsource(inspect.unwrap(type(m).forward))))
+ except Exception:
+ return None
+ node = next(
+ (n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))), None
+ )
+ if node is None:
+ return None
+ body = [
+ s for s in node.body if not (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant))
+ ]
+ if (
+ len(body) != 1
+ or not isinstance(body[0], ast.Return)
+ or not isinstance(body[0].value, ast.Call)
+ ):
+ return None
+ call = body[0].value
+ func = call.func
+ if not (
+ isinstance(func, ast.Attribute)
+ and isinstance(func.value, ast.Name)
+ and func.value.id == "self"
+ and func.attr in modules
+ ):
+ return None
+ kwarg = node.args.kwarg.arg if node.args.kwarg is not None else None
+ params = {a.arg for a in node.args.args + node.args.kwonlyargs}
+
+ def carries_count(value):
+ if isinstance(value, ast.Name):
+ return value.id == "num_items_in_batch" and value.id in params
+ return _is_count_get(value)
+
+ forwards_count = any(
+ (
+ kw.arg is None
+ and kwarg is not None
+ and isinstance(kw.value, ast.Name)
+ and kw.value.id == kwarg
+ and "num_items_in_batch" not in params
+ )
+ or (kw.arg == "num_items_in_batch" and carries_count(kw.value))
+ for kw in call.keywords
+ )
+ return modules[func.attr] if forwards_count else None
+
+
+def _call_forwards_count(node, call):
+ """Does `call` hand on the count `node` received: its **kwargs, or its own num_items_in_batch?"""
+ kwarg = node.args.kwarg.arg if node.args.kwarg is not None else None
+ params = {a.arg for a in node.args.posonlyargs + node.args.args + node.args.kwonlyargs}
+ return any(
+ (
+ kw.arg is None
+ and kwarg is not None
+ and isinstance(kw.value, ast.Name)
+ and kw.value.id == kwarg
+ and "num_items_in_batch" not in params
+ )
+ or (
+ kw.arg == "num_items_in_batch"
+ and isinstance(kw.value, ast.Name)
+ and kw.value.id == "num_items_in_batch"
+ and "num_items_in_batch" in params
+ )
+ for kw in call.keywords
+ )
+
+
+def _forward_function_node(forward, depth = 0):
+ try:
+ forward = inspect.unwrap(forward)
+ except ValueError:
+ return None
+ func = getattr(forward, "__func__", forward)
+ try:
+ source = textwrap.dedent(inspect.getsource(func))
+ tree = ast.parse(source)
+ except Exception:
+ return None
+ node = next(
+ (n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))),
+ None,
+ )
+ if node is None:
+ return None
+ namespace = getattr(func, "__globals__", None) or {}
+ body = [
+ s for s in node.body if not (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant))
+ ]
+ if (
+ depth < 2
+ and len(body) == 1
+ and isinstance(body[0], ast.Return)
+ and isinstance(body[0].value, ast.Call)
+ and isinstance(body[0].value.func, ast.Name)
+ and body[0].value.args
+ and isinstance(body[0].value.args[0], ast.Name)
+ and body[0].value.args[0].id == "self"
+ and _call_forwards_count(node, body[0].value)
+ ):
+ impl = namespace.get(body[0].value.func.id)
+ if callable(impl):
+ resolved = _forward_function_node(impl, depth + 1)
+ if resolved is not None:
+ return resolved
+ return node, source, namespace
+
+
+_N_ITEMS_KEYWORDS = ("num_items_in_batch", "n_items")
+_FUSED_LOSS_CALLEES = (
+ "unsloth_fused_lm_head_loss",
+ "unsloth_fused_ce_loss",
+ "fused_linear_cross_entropy",
+ "fast_cross_entropy_loss",
+ "unsloth_count_aware_cross_entropy",
+)
+
+
+def _nested_scope_ids(node):
+ ids = set()
+ for sub in ast.walk(node):
+ if sub is not node and isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ ids.update(id(x) for x in ast.walk(sub))
+ return ids
+
+
+def _local_assignments(node, nested):
+ plain, out = {}, {}
+ for sub in ast.walk(node):
+ if id(sub) in nested:
+ continue
+ if (
+ isinstance(sub, ast.Assign)
+ and len(sub.targets) == 1
+ and isinstance(sub.targets[0], ast.Name)
+ ):
+ plain[id(sub.targets[0])] = sub.value
+ elif isinstance(sub, ast.AnnAssign) and isinstance(sub.target, ast.Name):
+ plain[id(sub.target)] = sub.value
+ for sub in ast.walk(node):
+ if id(sub) in nested:
+ continue
+ if isinstance(sub, ast.Name) and isinstance(sub.ctx, (ast.Store, ast.Del)):
+ out.setdefault(sub.id, []).append(plain.get(id(sub)))
+ return out
+
+
+def _is_count_get(value):
+ # Any receiver: the compile cache reads the count off `__kwargs`, a locals() alias of **kwargs.
+ if isinstance(value, ast.IfExp):
+ return _is_count_get(value.body) and _is_count_get(value.orelse)
+ return (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Attribute)
+ and value.func.attr == "get"
+ and bool(value.args)
+ and _is_const(value.args[0], _N_ITEMS_KEYWORDS)
+ )
+
+
+def _kwargs_carriers(node, assigned):
+ kwarg = node.args.kwarg.arg if node.args.kwarg is not None else None
+ candidates = {kwarg} if kwarg else set()
+
+ def carried(value, carriers):
+ if isinstance(value, ast.Name):
+ return value.id in carriers
+ if isinstance(value, ast.Dict):
+ return all(
+ k is None and isinstance(v, ast.Name) and v.id in carriers
+ for k, v in zip(value.keys, value.values)
+ ) and bool(value.keys)
+ if isinstance(value, ast.Call):
+ callee = _dotted_name(value.func) or ""
+ if callee == "dict" and len(value.args) == 1 and not value.keywords:
+ return carried(value.args[0], carriers)
+ if callee.endswith(".copy") and isinstance(value.func, ast.Attribute):
+ return carried(value.func.value, carriers)
+ return False
+
+ candidates |= set(assigned)
+ carriers = set(candidates)
+ changed = True
+ while changed:
+ changed = False
+ for name in list(carriers):
+ values = assigned.get(name, [])
+ if name == kwarg:
+ ok = all(v is not None and carried(v, carriers) for v in values)
+ else:
+ ok = bool(values) and all(v is not None and carried(v, carriers) for v in values)
+ if not ok:
+ carriers.discard(name)
+ changed = True
+ return carriers
+
+
+_CARRIER_MUTATORS = ("clear", "update", "popitem", "__delitem__", "__setitem__", "setdefault")
+
+
+def _known_loss_function(head):
+ # A user-assigned `loss_function` may accept the keyword and still return a mean.
+ try:
+ fn = getattr(head, "loss_function", None)
+ except Exception:
+ return None
+ if fn is None:
+ return True
+ fn = getattr(fn, "__func__", fn)
+ module = getattr(fn, "__module__", "") or ""
+ if module.startswith(("transformers.loss", "unsloth_zoo", "unsloth.")):
+ return True
+ try:
+ from transformers.loss.loss_utils import LOSS_MAPPING
+ if any(fn is f for f in LOSS_MAPPING.values()):
+ return True
+ except Exception:
+ pass
+ return False
+
+
+def _ce_reductions(node, namespace, subst):
+ """("mean" | "other") per PyTorch cross_entropy / nll_loss call in `node`, resolving a reduction
+ passed as a parameter through `subst` (the caller's keyword or the parameter default)."""
+ kinds = []
+ for call in ast.walk(node):
+ if not isinstance(call, ast.Call):
+ continue
+ name = _resolve_ce_callee(call.func, namespace)
+ params = _CE_PARAMS.get(name)
+ if params is None:
+ continue
+ if len(call.args) > len(params) or any(isinstance(x, ast.Starred) for x in call.args):
+ kinds.append("other")
+ continue
+ if any(kw.arg is None for kw in call.keywords):
+ kinds.append("other")
+ continue
+ bound = dict(zip(params, call.args))
+ bound.update((kw.arg, kw.value) for kw in call.keywords)
+
+ def value_of(v):
+ if isinstance(v, ast.Name) and v.id in subst:
+ return subst[v.id]
+ return v
+
+ kind = "mean"
+ if "reduction" in bound and not _is_const(value_of(bound["reduction"]), ("mean",)):
+ kind = "other"
+ for legacy in ("size_average", "reduce"):
+ if legacy in bound and not _is_const(value_of(bound[legacy]), (None, True)):
+ kind = "other"
+ kinds.append(kind)
+ return kinds
+
+
+def _resolve_callee(obj, call, namespace):
+ func = call.func
+ if (
+ isinstance(func, ast.Attribute)
+ and isinstance(func.value, ast.Name)
+ and func.value.id == "self"
+ ):
+ modules = getattr(obj, "__dict__", {}).get("_modules") or {}
+ child = modules.get(func.attr)
+ if child is not None:
+ return child, getattr(type(child), "forward", None), True
+ method = getattr(type(obj), func.attr, None)
+ if callable(method):
+ return obj, method, True
+ return None
+ if isinstance(func, ast.Name):
+ target = namespace.get(func.id)
+ if inspect.isfunction(target):
+ return obj, target, False
+ return None
+
+
+def _zoo_counts_fallback_branches():
+ try:
+ from unsloth_zoo.fused_losses import cross_entropy_loss as zoo_ce
+ except Exception:
+ return False
+ return hasattr(zoo_ce, "unsloth_loss_count_kwargs")
+
+
+def _old_zoo_fallbacks_only(head, fused_with_count, via_loss_function):
+ # An older unsloth_zoo trains only the fused branch with the count; keep the answer it relied on.
+ return (
+ fused_with_count
+ and not via_loss_function
+ and not _zoo_counts_fallback_branches()
+ and os.environ.get("UNSLOTH_RETURN_LOGITS", "0") != "1"
+ and _known_loss_function(head)
+ )
+
+
+def _forward_consumes_num_items_in_batch(head):
+ """Does the loss head's forward hand num_items_in_batch to its loss?
+
+ True: every loss call gets the count. False: a micro-batch mean. None: cannot tell, mixed, or
+ anything it cannot follow (never True by default).
+ """
+ if head is None:
+ return None
+ forward = getattr(head, "forward", None)
+ resolved = _forward_function_node(forward) if forward is not None else None
+ if resolved is None:
+ return None
+ verdict = _classify_loss_forward(head, *resolved, depth = 0, labels_name = "labels", subst = {})
+ return None if verdict == "no_loss" else verdict
+
+
+def _classify_loss_forward(head, node, source, namespace, depth, labels_name, subst):
+ nested = _nested_scope_ids(node)
+ assigned = _local_assignments(node, nested)
+ carriers = _kwargs_carriers(node, assigned)
+ params = {a.arg for a in node.args.args + node.args.kwonlyargs}
+
+ # A carrier emptied or rewritten in place no longer proves the count reaches the loss.
+ tampered = any(
+ id(sub) not in nested
+ and isinstance(sub, ast.Call)
+ and isinstance(sub.func, ast.Attribute)
+ and isinstance(sub.func.value, ast.Name)
+ and sub.func.value.id in carriers
+ and sub.func.attr in _CARRIER_MUTATORS
+ for sub in ast.walk(node)
+ )
+
+ count_names = set()
+ if "num_items_in_batch" in params and all(
+ v is not None and _is_count_get(v) for v in assigned.get("num_items_in_batch", [])
+ ):
+ count_names.add("num_items_in_batch")
+ for name, values in assigned.items():
+ if name in params:
+ continue
+ if any(v is not None and _is_count_get(v) for v in values) and all(
+ v is not None and (_is_count_get(v) or _is_const(v, (None,))) for v in values
+ ):
+ count_names.add(name)
+ star_carries_count = "num_items_in_batch" not in params
+
+ def is_count(value):
+ return (isinstance(value, ast.Name) and value.id in count_names) or _is_count_get(value)
+
+ # The count may only be read or re-keyed; a pop, del or comparison filters it out.
+ allowed = set()
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call) and _is_count_get(sub):
+ allowed.add(id(sub.args[0]))
+ elif isinstance(sub, ast.Dict):
+ for k, v in zip(sub.keys, sub.values):
+ if _is_const(k, ("num_items_in_batch",)) and is_count(v):
+ allowed.add(id(k))
+ tampered = tampered or any(
+ isinstance(sub, ast.Constant)
+ and sub.value == "num_items_in_batch"
+ and id(sub) not in allowed
+ for sub in ast.walk(node)
+ )
+
+ def counted_dict(value):
+ return any(
+ isinstance(d, ast.Dict)
+ and any(
+ _is_const(k, ("num_items_in_batch",)) and is_count(v)
+ for k, v in zip(d.keys, d.values)
+ )
+ for d in ast.walk(value)
+ )
+
+ def counted_helper(value):
+ if not isinstance(value, ast.Call):
+ return False
+ if (_dotted_name(value.func) or "").rsplit(".", 1)[-1] != "unsloth_loss_count_kwargs":
+ return False
+ count = value.args[1] if len(value.args) >= 2 else None
+ for kw in value.keywords:
+ if kw.arg == "n_items":
+ count = kw.value
+ return count is not None and is_count(count)
+
+ def passes_count(call):
+ starred = star_carries_count and any(
+ kw.arg is None and isinstance(kw.value, ast.Name) and kw.value.id in carriers
+ for kw in call.keywords
+ )
+ counted = any(
+ (kw.arg in _N_ITEMS_KEYWORDS and is_count(kw.value))
+ or (kw.arg is None and (counted_dict(kw.value) or counted_helper(kw.value)))
+ for kw in call.keywords
+ )
+ return starred or counted
+
+ consumes = False
+ via_loss_function = False
+ fused_with_count = False
+ fused_without_count = False
+ uncounted = False
+ loss_calls = set()
+ for call in ast.walk(node):
+ if not isinstance(call, ast.Call):
+ continue
+ leaf = (_dotted_name(call.func) or "").rsplit(".", 1)[-1]
+ if leaf != "loss_function" and leaf not in _FUSED_LOSS_CALLEES:
+ continue
+ loss_calls.add(id(call))
+ if id(call) in nested:
+ return None
+ if passes_count(call):
+ consumes = True
+ via_loss_function = via_loss_function or leaf == "loss_function"
+ fused_with_count = fused_with_count or leaf in _FUSED_LOSS_CALLEES
+ elif leaf in _FUSED_LOSS_CALLEES:
+ fused_without_count = True
+ else:
+ uncounted = True
+
+ ce_kinds = _ce_reductions(node, namespace, subst)
+ named_children = getattr(head, "named_children", None)
+ used = [
+ sub
+ for name, sub in (named_children() if callable(named_children) else ())
+ if isinstance(sub, (torch.nn.CrossEntropyLoss, torch.nn.NLLLoss))
+ and re.search(rf"\bself\.{re.escape(name)}\s*\(", source)
+ ]
+ own_mean = (ce_kinds and all(k == "mean" for k in ce_kinds)) or (
+ used and all(sub.reduction == "mean" for sub in used)
+ )
+ own_other = any(k != "mean" for k in ce_kinds) or any(sub.reduction != "mean" for sub in used)
+
+ if consumes:
+ if tampered:
+ return None
+ if fused_without_count or (
+ uncounted and not _old_zoo_fallbacks_only(head, fused_with_count, via_loss_function)
+ ):
+ return None
+ if ce_kinds or used:
+ return None
+ if via_loss_function and not _known_loss_function(head):
+ return None
+ elif fused_without_count:
+ return False
+ elif uncounted:
+ return False if _known_loss_function(head) else None
+
+ delegates = []
+ for call in ast.walk(node):
+ if not isinstance(call, ast.Call) or id(call) in nested or id(call) in loss_calls:
+ continue
+ if _resolve_ce_callee(call.func, namespace) is not None:
+ continue
+ func = call.func
+ if (
+ isinstance(func, ast.Attribute)
+ and isinstance(func.value, ast.Name)
+ and func.value.id == labels_name
+ ):
+ continue # labels.view(...), labels.to(...)
+
+ def mentions(value):
+ return any(isinstance(x, ast.Name) and x.id == labels_name for x in ast.walk(value))
+
+ position = next((i for i, a in enumerate(call.args) if mentions(a)), None)
+ keyword = next(
+ (kw.arg for kw in call.keywords if kw.arg is not None and mentions(kw.value)),
+ None,
+ )
+ if position is None and keyword is None:
+ continue
+ delegates.append((call, position, keyword))
+
+ verdicts = []
+ for call, position, keyword in delegates:
+ target = _resolve_callee(head, call, namespace)
+ if target is None:
+ verdicts.append(None)
+ continue
+ callee_obj, fn, bound = target
+ callee = _forward_function_node(fn) if fn is not None else None
+ if callee is None:
+ verdicts.append(None)
+ continue
+ c_node, c_source, c_namespace = callee
+ c_params = [a.arg for a in c_node.args.args]
+ if bound and c_params and c_params[0] == "self":
+ c_params = c_params[1:]
+ c_labels = (
+ keyword
+ if keyword is not None
+ else (c_params[position] if position is not None and position < len(c_params) else None)
+ )
+ if c_labels is None:
+ verdicts.append(None)
+ continue
+ c_subst = {}
+ defaults = c_node.args.defaults
+ for arg, default in zip(
+ c_node.args.args[len(c_node.args.args) - len(defaults) :], defaults
+ ):
+ if isinstance(default, ast.Constant):
+ c_subst[arg.arg] = default
+ for arg, default in zip(c_node.args.kwonlyargs, c_node.args.kw_defaults):
+ if isinstance(default, ast.Constant):
+ c_subst[arg.arg] = default
+ for arg, value in zip(c_params, call.args):
+ c_subst.pop(arg, None)
+ if isinstance(value, ast.Constant):
+ c_subst[arg] = value
+ for kw in call.keywords:
+ if kw.arg is not None:
+ c_subst.pop(kw.arg, None)
+ if isinstance(kw.value, ast.Constant):
+ c_subst[kw.arg] = kw.value
+ if depth >= 2:
+ verdicts.append(None)
+ continue
+ verdict = _classify_loss_forward(
+ callee_obj, c_node, c_source, c_namespace, depth + 1, c_labels, c_subst
+ )
+ if verdict == "no_loss":
+ continue
+ if verdict is True and not passes_count(call):
+ verdict = False
+ verdicts.append(verdict)
+
+ # A counted direct loss beside a delegated mean (an auxiliary loss computed elsewhere) is mixed.
+ if consumes:
+ return None if any(v is False for v in verdicts) else True
+ # A mean renormalised by a count it read is not provably a mean.
+ mean_verdict = None if count_names else False
+ if (
+ own_mean
+ and not own_other
+ and all(v is not False for v in verdicts)
+ and not any(v is True for v in verdicts)
+ ):
+ return mean_verdict
+ if verdicts:
+ if any(v is True for v in verdicts) and any(v is not True for v in verdicts):
+ return None
+ if any(v is False for v in verdicts):
+ return False
+ if all(v is True for v in verdicts) and not (ce_kinds or used) and not tampered:
+ return True
+ return None
+ if own_mean and not own_other:
+ return mean_verdict
+ if ce_kinds or used:
+ return None
+ return "no_loss"
+
+
+def _head_default_accepts_loss_kwargs(head):
+ # What HF Trainer falls back to when nothing declares the flag: a **kwargs forward signature.
+ try:
+ params = inspect.signature(head.forward).parameters.values()
+ except Exception:
+ return None
+ return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params)
+
+
+def apply_accepts_loss_kwargs_fix(model):
+ # Priority: instance value > head hands the count to its loss > fused loss without it > class attr > mean-loss guess > HF default.
+ declared = _instance_accepts_loss_kwargs(model)
+ # Re-decide every value written by an earlier call: the forward or the wrappers may have changed.
+ _clear_guessed_accepts_loss_kwargs(model)
+ if declared is not None:
+ _shadow_accepts_loss_kwargs(model, declared)
+ return f"{declared} (instance accepts_loss_kwargs)"
+
+ head = _loss_head(model)
value, reason = _find_concrete_accepts_loss_kwargs(model)
- if value is None:
- declared = _instance_accepts_loss_kwargs(model)
- if declared is not None:
- # Set by the model itself: keep it, and carry it onto any wrapper added since.
- _shadow_accepts_loss_kwargs(model, declared)
- return f"{declared} (instance accepts_loss_kwargs)"
- # Re-check an earlier guess: forward may have been replaced since.
- _clear_guessed_accepts_loss_kwargs(model)
- causal_lm = _forward_ignores_num_items_in_batch(model)
- if causal_lm is not None:
- _shadow_accepts_loss_kwargs(model, False, guessed = True)
- # transformers 5 reads the flag off get_base_model(), which the walk above can skip under PEFT.
- _shadow_accepts_loss_kwargs(causal_lm, False, guessed = True)
- return "False (forward takes **kwargs but computes its own mean loss)"
- return f"default (signature inspection, {reason})"
- _shadow_accepts_loss_kwargs(model, value)
- return f"{value} ({reason})"
+ consumes = _forward_consumes_num_items_in_batch(head)
+ if consumes is not None:
+ # Only where Trainer would read another answer off some level (Gemma 4's stale False, ProphetNet's **kwargs mean).
+ def trainer_reads(level):
+ if hasattr(level, "accepts_loss_kwargs"):
+ return getattr(level, "accepts_loss_kwargs")
+ return _head_default_accepts_loss_kwargs(level)
+
+ above_head = []
+ for level in _loss_kwargs_levels(model):
+ above_head.append(level)
+ if level is head:
+ break
+ if head is not None and all(head is not m for m in above_head):
+ above_head.append(head)
+ if any(bool(trainer_reads(level)) != consumes for level in above_head):
+ _shadow_accepts_loss_kwargs(model, consumes)
+ if consumes:
+ _record_num_items_labels(model, head)
+ return f"True ({type(head).__name__}.forward passes num_items_in_batch to its loss)"
+ return f"False ({type(head).__name__}.forward reduces its loss by a micro-batch mean)"
+ if value is not None:
+ _shadow_accepts_loss_kwargs(model, value)
+ return f"{value} ({reason})"
+ causal_lm = _forward_ignores_num_items_in_batch(model)
+ if causal_lm is not None:
+ _shadow_accepts_loss_kwargs(model, False)
+ _shadow_accepts_loss_kwargs(causal_lm, False)
+ return "False (forward takes **kwargs but computes its own mean loss)"
+ return f"default (signature inspection, {reason})"
# unsloth/gpt-oss-* generation_config predates upstream adding <|call|> (200012) to eos (#5162):
@@ -5478,56 +6137,52 @@ def patch_harmony_tool_call_eos_vllm(model, tokenizer):
return model
-def _loss_kwargs_chain(model):
- seen = set()
- m = model
- for _ in range(8):
- if m is None or id(m) in seen:
- return
- seen.add(id(m))
- yield m
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- m = nxt
-
-
def _is_guess(d):
- # Still the heuristic's value; an assignment made since (e.g. by the user) is a declaration.
+ # Still the value Unsloth wrote; an assignment made since (e.g. by the user) is a declaration.
return _GUESSED_LOSS_KWARGS in d and d.get("accepts_loss_kwargs") == d[_GUESSED_LOSS_KWARGS]
def _clear_guessed_accepts_loss_kwargs(model):
- chain = list(_loss_kwargs_chain(model))
- # Under PEFT the walk skips the causal head that get_base_model() returns (and transformers 5 reads).
- try:
- head = model.get_base_model() if hasattr(model, "get_base_model") else None
- except Exception:
- head = None
- if head is not None and all(head is not m for m in chain):
- chain.append(head)
- for m in chain:
- d = getattr(m, "__dict__", {})
+ for m in _loss_kwargs_levels(model):
+ d = getattr(m, "__dict__", None)
+ if d is None:
+ continue
if _is_guess(d):
d.pop("accepts_loss_kwargs", None)
d.pop(_GUESSED_LOSS_KWARGS, None)
+ d.pop(_NUM_ITEMS_LABELS, None)
+
+
+_NUM_ITEMS_LABELS = "_unsloth_num_items_labels"
+
+
+def _record_num_items_labels(model, head):
+ if getattr(head, "_unsloth_counts_unshifted_labels", False) is True:
+ value = "unshifted"
+ elif getattr(getattr(head, "config", None), "is_encoder_decoder", False):
+ return
+ else:
+ value = "shifted"
+ for m in _loss_kwargs_levels(model):
+ d = getattr(m, "__dict__", None)
+ if d is not None:
+ d[_NUM_ITEMS_LABELS] = value
+
+
+def _num_items_labels(model):
+ for m in _loss_kwargs_levels(model):
+ value = (getattr(m, "__dict__", None) or {}).get(_NUM_ITEMS_LABELS)
+ if value is not None:
+ return value
+ return None
def _instance_accepts_loss_kwargs(model):
- seen = set()
- m = model
- for _ in range(8):
- if m is None or id(m) in seen:
- return None
- seen.add(id(m))
- d = getattr(m, "__dict__", {})
+ for m in _loss_kwargs_chain(model):
+ d = getattr(m, "__dict__", None) or {}
value = None if _is_guess(d) else d.get("accepts_loss_kwargs", None)
if value is not None:
return value
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- m = nxt
return None
@@ -5550,6 +6205,16 @@ _CE_PARAMS = {
"reduction",
"label_smoothing",
),
+ "NLLLoss": ("weight", "size_average", "ignore_index", "reduce", "reduction"),
+ "nll_loss": (
+ "input",
+ "target",
+ "weight",
+ "size_average",
+ "ignore_index",
+ "reduce",
+ "reduction",
+ ),
}
@@ -5579,6 +6244,8 @@ def _ce_calls_all_mean(source, namespace = None):
_TORCH_CE = {
"CrossEntropyLoss": torch.nn.CrossEntropyLoss,
"cross_entropy": torch.nn.functional.cross_entropy,
+ "NLLLoss": torch.nn.NLLLoss,
+ "nll_loss": torch.nn.functional.nll_loss,
}
@@ -5639,26 +6306,8 @@ def _scan_ce_calls(source, namespace = None):
def _forward_ignores_num_items_in_batch(model):
# HF treats **kwargs as consuming num_items_in_batch and skips 1/GA; remote code (NemotronH) keeps **kwargs for generate yet returns a CrossEntropyLoss mean, so loss + grads come out GA x too large.
- m = model
- try:
- # PeftModelForCausalLM itself matches "CausalLM".
- if hasattr(m, "get_base_model"):
- m = m.get_base_model()
- except Exception:
- m = model
- seen = set()
- for _ in range(6):
- if m is None or id(m) in seen:
- return None
- seen.add(id(m))
- name = type(m).__name__
- if "CausalLM" in name or "ForConditionalGeneration" in name or "LMHeadModel" in name:
- break
- nxt = getattr(m, "base_model", None)
- if nxt is None or nxt is m:
- nxt = getattr(m, "model", None)
- m = nxt
- else:
+ m = _loss_head(model)
+ if m is None:
return None
# The instance forward is what Trainer inspects and calls (accelerate hooks and loaders replace it).
forward = getattr(m, "forward", None)
@@ -5668,11 +6317,14 @@ def _forward_ignores_num_items_in_batch(model):
return None
try:
params = inspect.signature(forward).parameters.values()
- source = inspect.getsource(forward)
except Exception:
return None
if not any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params):
return None
+ resolved = _forward_function_node(forward)
+ if resolved is None:
+ return None
+ _, source, namespace = resolved
if "num_items_in_batch" in source or "loss_function" in source:
return None
used = [
@@ -5683,7 +6335,6 @@ def _forward_ignores_num_items_in_batch(model):
]
if any(sub.reduction != "mean" for sub in used):
return None
- namespace = getattr(getattr(forward, "__func__", forward), "__globals__", None) or {}
all_mean, found = _scan_ce_calls(source, namespace)
if not all_mean or not (found or used):
return None