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 CPU pipeline evaluation loss normalization (#17291)
0xAlkin8941acb30ed5
diff --git a/tests/test_parallel_cp_compose_gloo.py b/tests/test_parallel_cp_compose_gloo.pyindex f101adf018c..eff50f2df82 100644--- a/tests/test_parallel_cp_compose_gloo.py+++ b/tests/test_parallel_cp_compose_gloo.py@@ -374,6 +374,7 @@ def _case_train(probe_refusal = False,gc = "none",packed = None,+ eval_only = False,):error = _import_checkout_unsloth()if error is not None:@@ -467,6 +468,10 @@ def _case_train(load = tp_env.tensor_parallel_env_load(load)peft = tp_env.tensor_parallel_env_peft(peft)model = load(ckpt, load_in_4bit = False)+ cpu_chunked_ce = False+ if eval_only:+ from unsloth_zoo.cpu.ops import patch_chunked_causal_lm_loss+ cpu_chunked_ce = patch_chunked_causal_lm_loss(model)gdn_calls = []if arch == "qwen3_5":# The torch Gated DeltaNet kernels (fla / Triton need CUDA), and a counter on Unsloth's GDN exchange.@@ -520,6 +525,8 @@ def _case_train(batch["labels"][batch["labels"] % 5 == 0] = -100 # uneven token counts per row and per shard+ if eval_only:+ batch["attention_mask"] = torch.ones_like(input_ids)if packed:batch.update(_packed_row(batch, packed, int(rows[0]["row"])))return batch@@ -569,6 +576,8 @@ def _case_train(dataset_kwargs = {"skip_prepare_dataset": True},gradient_checkpointing = False,)+ if eval_only:+ args.loss_type = "nll"if packed:# What the registry reads for a packed run (query_from): SFTConfig.padding_free; the rows come from the# collator above, so TRL's own padding-free collator is not involved.@@ -648,6 +657,17 @@ def _case_train(processing_class = tokenizer,callbacks = [Grabber()],)+ if eval_only:+ trainer.args.per_device_eval_batch_size = bs+ metrics = trainer.evaluate(eval_dataset = data)+ stage = pp_native.pipeline_stage_of(trainer.model)+ return {+ "eval_loss": metrics["eval_loss"],+ "rows_read": rows_read,+ "stage": None if stage is None else int(stage.stage_index),+ "cpu_compute_loss": bool(getattr(type(trainer).compute_loss, "_unsloth_cpu", False)),+ "cpu_chunked_ce": cpu_chunked_ce,+ }if device != "cpu":assert trainer.accelerator.mixed_precision == "no", trainer.accelerator.mixed_precisionmanager = getattr(trainer, "_context_parallel_manager", None)@@ -1302,6 +1322,40 @@ def test_pp_moe_router_aux_loss_with_accumulation_matches_one_process(_close(res, ref, rel = 5e-4, state_atol = 1e-5, what = (ga, aux, rank))+ "arch,aux",+ [("llama", False), ("qwen3_moe", False), ("qwen3_moe", True)],+ ids = ["dense", "moe_aux_off", "moe_aux_on"],+)+def test_cpu_pipeline_eval_matches_one_process(monkeypatch, arch, aux):+ monkeypatch.setenv("UNSLOTH_FORCE_CPU", "1")+ kw = dict(+ bs = 2,+ ga = 1,+ steps = 3,+ arch = arch,+ eval_only = True,+ router_aux = aux,+ aux_coef = 0.5 if aux else None,+ )+ (ref,) = _spawn("train", 1, **kw)+ assert "error" not in ref, ref+ results = _spawn(+ "train",+ 2,+ {"UNSLOTH_PP_SIZE": "2", "UNSLOTH_PP_MICROBATCHES": "1", "UNSLOTH_PP_SCHEDULE": "gpipe"},+ **kw,+ )+ _skip_if_one_microbatch_refused(results)+ assert sorted(res.get("stage", -1) for res in results) == [0, 1], results+ for res in [ref, *results]:+ assert "error" not in res, res+ assert res["cpu_compute_loss"]+ assert res["cpu_chunked_ce"] is (arch == "llama")+ assert res["rows_read"] == ref["rows_read"]+ assert res["eval_loss"] == pytest.approx(ref["eval_loss"], rel = 1e-5)++_PP_AUX_SPLIT = "load-balancing loss per micro-batch"diff --git a/tests/test_pp_env_eval.py b/tests/test_pp_env_eval.pynew file mode 100644index 00000000000..4d18e3fc14d--- /dev/null+++ b/tests/test_pp_env_eval.py@@ -0,0 +1,54 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import types++import pytest+import torch+import trl++from unsloth.models import pp_env+++class _Trainer:+ def __init__(self, average_tokens_across_devices = True):+ self.args = types.SimpleNamespace(+ device = torch.device("cpu"),+ average_tokens_across_devices = average_tokens_across_devices,+ )++ def compute_loss(self, *args, **kwargs):+ raise AssertionError("pipeline evaluation does not call compute_loss")++ def _get_num_items_in_batch(self, batches, device):+ assert not self.args.average_tokens_across_devices+ return sum((batch["labels"] != -100).sum() for batch in batches).to(device)+++class _CpuTrainer(_Trainer):+ def compute_loss(self, *args, **kwargs):+ return super().compute_loss(*args, **kwargs)++ compute_loss._unsloth_cpu = True+++ "labels,expected",+ [([[1, 2, -100], [3, 4, 5]], 3), ([[1, -100, -100]], 0)],+)+def test_cpu_eval_counts_only_shifted_targets(monkeypatch, labels, expected):+ monkeypatch.setattr(trl, "__version__", "1.15.0")+ labels = torch.tensor(labels)+ trainer = _CpuTrainer()+ assert pp_env._eval_items(trainer, {"labels": labels}, labels) == expected+ assert trainer.args.average_tokens_across_devices is True++[email protected]("average", [False, True])[email protected]("trainer_cls,version", [(_Trainer, "1.15.0"), (_CpuTrainer, "1.14.0")])+def test_other_trainers_keep_their_eval_token_count(monkeypatch, trainer_cls, version, average):+ monkeypatch.setattr(trl, "__version__", version)+ labels = torch.tensor([[1, 2, -100], [3, 4, 5]])+ trainer = trainer_cls(average_tokens_across_devices = average)+ assert pp_env._eval_items(trainer, {"labels": labels}, labels) == 5+ assert trainer.args.average_tokens_across_devices is averagediff --git a/unsloth/models/pp_env.py b/unsloth/models/pp_env.pyindex 4da9513a880..c07f88dbeb6 100644--- a/unsloth/models/pp_env.py+++ b/unsloth/models/pp_env.py@@ -933,9 +933,14 @@ def _pp_training_step(def _eval_items(trainer, inputs, labels):- """The loss normaliser of one eval batch, counted as this Trainer counts it on one GPU (Unsloth's- prediction step passes _get_num_items_in_batch: unshifted labels on transformers 4.x), for this dp- replica's batch only; else the shifted label count (the model's own mean)."""+ """This trainer's one-process evaluation token count, local to the data parallel replica."""+ if getattr(getattr(type(trainer), "compute_loss", None), "_unsloth_cpu", False):+ import trl+ from packaging.version import Version++ # TRL 1.15 evaluates its fused head without num_items_in_batch, even with CPU chunked CE installed.+ if Version(trl.__version__) >= Version("1.15.0"):+ return int((labels[:, 1:] != -100).sum())getter = getattr(trainer, "_get_num_items_in_batch", None)if callable(getter):args = trainer.args