Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(distill): refuse rows with no causal-loss target at setup (#1242) (#1298)

Nurkhan Esenbekd85d5d698180
diff --git a/changelog.d/0.75.1/1298.fixed.md b/changelog.d/0.75.1/1298.fixed.md
new file mode 100644
index 00000000..4e5d2bd5
--- /dev/null
+++ b/changelog.d/0.75.1/1298.fixed.md
@@ -0,0 +1 @@
+- Refuse rows with no causal-loss target at setup in `task: distill` with human-facing row number and `data.max_length`, matching SFT behavior, and return finite 0.0 CE loss in `compute_loss` if a microbatch contains zero targets (#1242 by @kok-o in #1298).
diff --git a/docs/training.md b/docs/training.md
index 953b5cb0..ce6a96a3 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -506,7 +506,7 @@ soup train
## Knowledge Distillation
-Train a small student model to match a larger teacher's output distribution.
+Train a small student model to match a larger teacher's output distribution. Every train/val row must keep at least one causal-loss target after truncation at `data.max_length`, and a row without one is refused at setup by split and row number, as SFT does.
```yaml
base: HuggingFaceTB/SmolLM2-135M
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index fc1b77a9..c1e52c74 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -377,6 +377,41 @@ class DistillNonfiniteTracker:
pass
+def _map_distill_rows(
+ rows: Any,
+ *,
+ format_row: Any,
+ split: str,
+ max_length: int,
+) -> Any:
+ """Tokenize distill rows and attach human-facing row number to causal-loss
+ target failures (#1242).
+ """
+ from datasets import Dataset
+
+ from soup_cli.data.loss_mask import (
+ NoCausalLossTargetError,
+ ensure_causal_loss_target,
+ )
+
+ def checked_format_row(example: dict, row_index: int) -> dict:
+ try:
+ formatted = format_row(example)
+ labels = formatted.get("labels")
+ if labels is not None:
+ ensure_causal_loss_target(labels, max_length=max_length)
+ return formatted
+ except NoCausalLossTargetError as exc:
+ raise ValueError(f"{split} row {row_index + 1}: {exc}") from exc
+
+ raw_ds = Dataset.from_list(rows) if isinstance(rows, list) else rows
+ return raw_ds.map(
+ checked_format_row,
+ with_indices=True,
+ remove_columns=raw_ds.column_names,
+ )
+
+
class DistillTrainerWrapper:
"""High-level wrapper for student/teacher distillation.
@@ -427,7 +462,6 @@ class DistillTrainerWrapper:
def setup(self, dataset: dict) -> None:
"""Load student + teacher, build distillation Trainer."""
- from datasets import Dataset
from peft import TaskType, get_peft_model
from transformers import (
AutoModelForCausalLM,
@@ -683,15 +717,20 @@ class DistillTrainerWrapper:
console=console,
training_cfg=tcfg,
)
- raw_train = Dataset.from_list(dataset["train"])
- train_ds = raw_train.map(
- format_row, remove_columns=raw_train.column_names
+ raw_train = dataset["train"]
+ train_ds = _map_distill_rows(
+ raw_train,
+ format_row=format_row,
+ split="train",
+ max_length=int(cfg.data.max_length),
)
eval_ds = None
if "val" in dataset and dataset["val"]:
- raw_val = Dataset.from_list(dataset["val"])
- eval_ds = raw_val.map(
- format_row, remove_columns=raw_val.column_names
+ eval_ds = _map_distill_rows(
+ dataset["val"],
+ format_row=format_row,
+ split="val",
+ max_length=int(cfg.data.max_length),
)
output_dir = Path(cfg.output)
@@ -814,11 +853,16 @@ class DistillTrainerWrapper:
if labels is not None:
shift_logits = student_logits[:, :-1, :].contiguous()
shift_labels = labels[:, 1:].contiguous()
- ce_loss = torch.nn.functional.cross_entropy(
- shift_logits.view(-1, shift_logits.size(-1)),
- shift_labels.view(-1),
- ignore_index=-100,
- )
+ if shift_labels.ne(-100).any():
+ ce_loss = torch.nn.functional.cross_entropy(
+ shift_logits.view(-1, shift_logits.size(-1)),
+ shift_labels.view(-1),
+ ignore_index=-100,
+ )
+ else:
+ ce_loss = (student_logits.sum() * 0.0).to(
+ dtype=student_logits.dtype
+ )
# v0.71.12 #145 — sequence-level KD trains the student with
# plain CE on teacher-generated text. The teacher has already
diff --git a/tests/test_issue1242_distill_causal_target_guard.py b/tests/test_issue1242_distill_causal_target_guard.py
new file mode 100644
index 00000000..2d580417
--- /dev/null
+++ b/tests/test_issue1242_distill_causal_target_guard.py
@@ -0,0 +1,240 @@
+"""Regression tests for Issue #1242:
+`task: distill` refuses rows with no loss target at setup with human-facing row number,
+matching SFT behavior, and compute_loss returns finite zero when a microbatch has no targets.
+"""
+
+from __future__ import annotations
+
+import pathlib
+
+import pytest
+import torch
+from safetensors.torch import save_file
+from tokenizers import Tokenizer, models, pre_tokenizers
+from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.trainer.distill import DistillTrainerWrapper
+
+
+def _tiny_llama_dir(tmp_path: pathlib.Path) -> pathlib.Path:
+ config = LlamaConfig(
+ vocab_size=16,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=1,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ tie_word_embeddings=True,
+ max_position_embeddings=256,
+ )
+ model = LlamaForCausalLM(config).to(torch.float32).eval()
+ weights = tmp_path / "model"
+ weights.mkdir(parents=True, exist_ok=True)
+ state = {name: value.contiguous() for name, value in model.state_dict().items()}
+ state.pop("lm_head.weight", None)
+ save_file(state, str(weights / "model.safetensors"))
+ config.save_pretrained(str(weights))
+
+ vocab = {
+ "<unk>": 0,
+ "<s>": 1,
+ "</s>": 2,
+ "<pad>": 3,
+ "user": 4,
+ "assistant": 5,
+ "hi": 6,
+ "good": 7,
+ }
+ tokenizer = Tokenizer(models.WordLevel(vocab=vocab, unk_token="<unk>"))
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
+ fast = PreTrainedTokenizerFast(
+ tokenizer_object=tokenizer,
+ unk_token="<unk>",
+ bos_token="<s>",
+ eos_token="</s>",
+ pad_token="<pad>",
+ chat_template=(
+ "{% for message in messages %}"
+ "{{ message['role'] }} {{ message['content'] }} "
+ "{% endfor %}"
+ ),
+ )
+ fast.save_pretrained(str(weights))
+ return weights
+
+
+def _make_cfg(
+ weights: pathlib.Path,
+ tmp_path: pathlib.Path,
+ *,
+ divergence: str = "forward_kl",
+ max_length: int = 64,
+ gradient_accumulation_steps: int = 1,
+ train_on_messages_with_train_field: bool = False,
+ extra_training: str = "",
+) -> str:
+ train_field_opt = (
+ " train_on_responses_only: false\n train_on_messages_with_train_field: true\n"
+ if train_on_messages_with_train_field
+ else ""
+ )
+ return f"""
+base: {weights.as_posix()}
+task: distill
+backend: transformers
+data:
+ train: train.jsonl
+ max_length: {max_length}
+{train_field_opt}training:
+ teacher_model: {weights.as_posix()}
+ distill_divergence: {divergence}
+ batch_size: 1
+ epochs: 1
+ gradient_accumulation_steps: {gradient_accumulation_steps}
+{extra_training} lora:
+ r: 4
+ alpha: 8
+ target_modules: ['q_proj', 'v_proj']
+output: {tmp_path.as_posix()}/out
+"""
+
+
+SHORT_ROW = {
+ "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "good"},
+ ]
+}
+
+# 96 tokens when tokenized by whitespace;
+# prompt truncation at max_length=64 drops the assistant response
+LONG_ROW = {
+ "messages": [
+ {"role": "user", "content": " ".join(["hi"] * 96)},
+ {"role": "assistant", "content": "good"},
+ ]
+}
+
+
+class TestDistillCausalTargetGuard:
+ def test_distill_setup_refuses_train_row_with_no_loss_target(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, max_length=64))
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+
+ with pytest.raises(
+ ValueError,
+ match=r"train row 2.*no causal-loss target.*data\.max_length=64",
+ ):
+ wrapper.setup({"train": [SHORT_ROW, LONG_ROW]})
+
+ def test_distill_setup_refuses_val_row_with_no_loss_target(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, max_length=64))
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+
+ with pytest.raises(
+ ValueError,
+ match=r"val row 2.*no causal-loss target.*data\.max_length=64",
+ ):
+ wrapper.setup({"train": [SHORT_ROW], "val": [SHORT_ROW, LONG_ROW]})
+
+ def test_control_surviving_target_is_accepted(self, tmp_path: pathlib.Path) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, max_length=64))
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": [SHORT_ROW]})
+ assert wrapper.trainer is not None
+
+ @pytest.mark.parametrize("divergence", ["forward_kl", "reverse_kl", "js"])
+ @pytest.mark.parametrize("ga", [1, 4])
+ def test_divergences_and_gradient_accumulation(
+ self, tmp_path: pathlib.Path, divergence: str, ga: int
+ ) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ divergence=divergence,
+ max_length=64,
+ gradient_accumulation_steps=ga,
+ )
+ )
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"train row 2.*no causal-loss target.*data\.max_length=64",
+ ):
+ wrapper.setup({"train": [SHORT_ROW, LONG_ROW]})
+
+ def test_train_on_messages_with_train_field_all_false(self, tmp_path: pathlib.Path) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ train_on_messages_with_train_field=True,
+ )
+ )
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+ row_all_false = {
+ "messages": [
+ {"role": "user", "content": "hi", "train": False},
+ {"role": "assistant", "content": "good", "train": False},
+ ]
+ }
+ with pytest.raises(
+ ValueError,
+ match=r"train row 1.*no causal-loss target",
+ ):
+ wrapper.setup({"train": [row_all_false]})
+
+ @pytest.mark.parametrize(
+ "extra",
+ [
+ " uld_strategy: wasserstein\n",
+ " minillm_enabled: true\n minillm_teacher_mix_ratio: 0.5\n",
+ " minillm_enabled: true\n minillm_on_policy: true\n",
+ " distill_mode: sequence\n",
+ ],
+ ids=["uld", "minillm", "minillm_on_policy", "sequence"],
+ )
+ def test_distill_variants_refuse_row_with_no_loss_target(
+ self, tmp_path: pathlib.Path, extra: str
+ ) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, extra_training=extra))
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"train row 2.*no causal-loss target.*data\.max_length=64",
+ ):
+ wrapper.setup({"train": [SHORT_ROW, LONG_ROW]})
+
+
+class TestComputeLossDefenseInDepth:
+ """Defense in depth: compute_loss evaluates to finite 0.0 even if a microbatch has 0 targets."""
+
+ def test_all_masked_labels_return_finite_loss(self, tmp_path: pathlib.Path) -> None:
+ weights = _tiny_llama_dir(tmp_path)
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, max_length=64))
+ wrapper = DistillTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": [SHORT_ROW]})
+
+ # Manually invoke compute_loss with all -100 labels
+ inputs = {
+ "input_ids": torch.tensor([[4, 6, 5, 7]], dtype=torch.long),
+ "attention_mask": torch.tensor([[1, 1, 1, 1]], dtype=torch.long),
+ "labels": torch.tensor([[-100, -100, -100, -100]], dtype=torch.long),
+ }
+ inputs = wrapper.trainer._prepare_inputs(inputs)
+ loss = wrapper.trainer.compute_loss(wrapper.model, inputs)
+ assert torch.isfinite(loss), f"Loss should be finite, got {loss}"
+ assert loss.item() == 0.0