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): preserve row numbers and refuse empty splits in sequence mode (#1344) (#1502)

Nurkhan Esenbek840df00c75e1
diff --git a/changelog.d/0.75.1/1502.fixed.md b/changelog.d/0.75.1/1502.fixed.md
new file mode 100644
index 00000000..ea9a32c0
--- /dev/null
+++ b/changelog.d/0.75.1/1502.fixed.md
@@ -0,0 +1 @@
+- **`distill_mode: sequence` now numbers rows the way token mode does, and refuses a split with nothing left (#1344 in #1502).** In `distill_mode: sequence`, original source row indices are preserved when skipping rows with no prompt turn, user's 1-based source row positions are reported on causal-loss target failures (noting the assistant response was generated by the teacher), skipped row counts and positions are printed at setup, and splits left with 0 usable rows are refused before training starts (#1344 by @kok-o in #1502).
diff --git a/docs/training.md b/docs/training.md
index a6b74931..de15950d 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -664,10 +664,12 @@ Soup provides two controls to bound activation memory:
Set `distill_mode: sequence` (default `token`) to train on the teacher's **generated
-continuations** instead of per-token logit matching — a hard-label, cross-tokenizer-friendly
+continuations** instead of per-token logit matching - a hard-label, cross-tokenizer-friendly
KD that works when student and teacher do not share a vocabulary. `sequence` mode is mutually
exclusive with the cross-tokenizer `uld_strategy` logit path (they are different objectives over
-the same task; the trainer rejects the combination at setup). (v0.71.12)
+the same task; the trainer rejects the combination at setup). Rows with no prompt turn are
+skipped, the count and first positions are printed at setup, a split left with no usable row is
+refused before training, and a refusal names the row's position in your data. (v0.71.12)
## Sequence Classification
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index 6f84c72e..c47ded7d 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -384,6 +384,7 @@ def _map_distill_rows(
format_row: Any,
split: str,
max_length: int,
+ trust_source_index: bool = False,
) -> Any:
"""Tokenize distill rows and attach human-facing row number to causal-loss
target failures (#1242).
@@ -403,7 +404,18 @@ def _map_distill_rows(
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
+ source_idx = example.get("_source_index") if trust_source_index else None
+ if source_idx is not None:
+ row_num = int(source_idx) + 1
+ msg = str(exc)
+ if "(generated by the teacher)" not in msg:
+ msg = msg.replace(
+ "the assistant response is",
+ "the assistant response (generated by the teacher) is",
+ )
+ raise ValueError(f"{split} row {row_num}: {msg}") from exc
+ row_num = row_index + 1
+ raise ValueError(f"{split} row {row_num}: {exc}") from exc
raw_ds = Dataset.from_list(rows) if isinstance(rows, list) else rows
return raw_ds.map(
@@ -596,19 +608,68 @@ class DistillTrainerWrapper:
f"completions (max_new_tokens={seq_budget})"
)
dataset = dict(dataset)
+ raw_train = list(dataset["train"])
dataset["train"] = build_sequence_distill_rows(
- dataset["train"],
+ raw_train,
self.teacher,
teacher_tokenizer,
max_new_tokens=seq_budget,
)
+ kept_train = {
+ r["_source_index"]
+ for r in dataset["train"]
+ if isinstance(r, dict) and "_source_index" in r
+ }
+ skipped_train = [
+ i for i in range(len(raw_train)) if i not in kept_train
+ ]
+ if skipped_train:
+ pos_list = [str(i + 1) for i in skipped_train]
+ sample_pos = ", ".join(pos_list[:5])
+ if len(pos_list) > 5:
+ sample_pos += ", ..."
+ console.print(
+ f"[yellow]Skipped {len(skipped_train)} train row(s) with no prompt turn[/] "
+ f"(positions: {sample_pos})"
+ )
+ if len(dataset["train"]) == 0:
+ pos_desc = f" (positions: {sample_pos})" if skipped_train else ""
+ raise ValueError(
+ f"train split has 0 usable rows after skipping {len(skipped_train)} "
+ f"row(s) with no prompt turn{pos_desc}"
+ )
+
if dataset.get("val"):
+ raw_val = list(dataset["val"])
dataset["val"] = build_sequence_distill_rows(
- dataset["val"],
+ raw_val,
self.teacher,
teacher_tokenizer,
max_new_tokens=seq_budget,
)
+ kept_val = {
+ r["_source_index"]
+ for r in dataset["val"]
+ if isinstance(r, dict) and "_source_index" in r
+ }
+ skipped_val = [
+ i for i in range(len(raw_val)) if i not in kept_val
+ ]
+ if skipped_val:
+ pos_list_val = [str(i + 1) for i in skipped_val]
+ sample_pos_val = ", ".join(pos_list_val[:5])
+ if len(pos_list_val) > 5:
+ sample_pos_val += ", ..."
+ console.print(
+ f"[yellow]Skipped {len(skipped_val)} val row(s) with no prompt turn[/] "
+ f"(positions: {sample_pos_val})"
+ )
+ if len(dataset["val"]) == 0:
+ pos_desc_val = f" (positions: {sample_pos_val})" if skipped_val else ""
+ raise ValueError(
+ f"val split has 0 usable rows after skipping {len(skipped_val)} "
+ f"row(s) with no prompt turn{pos_desc_val}"
+ )
# Free the teacher — sequence-level KD does NOT need it in the
# student loss loop (keeps the 4 GB VRAM budget honest).
self.teacher = None
@@ -724,6 +785,7 @@ class DistillTrainerWrapper:
format_row=format_row,
split="train",
max_length=int(cfg.data.max_length),
+ trust_source_index=sequence_mode,
)
eval_ds = None
if "val" in dataset and dataset["val"]:
@@ -732,6 +794,7 @@ class DistillTrainerWrapper:
format_row=format_row,
split="val",
max_length=int(cfg.data.max_length),
+ trust_source_index=sequence_mode,
)
output_dir = Path(cfg.output)
diff --git a/src/soup_cli/utils/distill.py b/src/soup_cli/utils/distill.py
index 89d25c49..798cab8d 100644
--- a/src/soup_cli/utils/distill.py
+++ b/src/soup_cli/utils/distill.py
@@ -302,7 +302,7 @@ def build_sequence_distill_rows(
device: optional device override; defaults to the teacher's device.
Returns:
- A list of student ``{"messages": [...]}`` rows.
+ A list of student ``{"messages": [...], "_source_index": int}`` rows.
"""
import torch
@@ -316,7 +316,7 @@ def build_sequence_distill_rows(
pad_id = getattr(teacher_tokenizer, "eos_token_id", None)
out_rows: list = []
- for row in rows:
+ for idx, row in enumerate(rows):
if not isinstance(row, dict):
continue
messages = row.get("messages")
@@ -373,7 +373,8 @@ def build_sequence_distill_rows(
out_rows.append(
{
"messages": list(prompt_msgs)
- + [{"role": "assistant", "content": teacher_text}]
+ + [{"role": "assistant", "content": teacher_text}],
+ "_source_index": idx,
}
)
return out_rows
diff --git a/tests/test_issue1344_sequence_distill_dropped_row_numbering.py b/tests/test_issue1344_sequence_distill_dropped_row_numbering.py
new file mode 100644
index 00000000..20bd3cc0
--- /dev/null
+++ b/tests/test_issue1344_sequence_distill_dropped_row_numbering.py
@@ -0,0 +1,292 @@
+"""Regression tests for Issue #1344:
+`distill_mode: sequence` row numbering with dropped rows (assistant-only / no prompt turn).
+Ensures source position is carried through and reported accurately at setup,
+and splits with 0 usable rows are refused at setup rather than failing at train().
+"""
+
+from __future__ import annotations
+
+import pathlib
+from unittest import mock
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.trainer.distill import DistillTrainerWrapper
+from soup_cli.utils.distill import build_sequence_distill_rows
+from tests.test_issue1242_distill_causal_target_guard import (
+ LONG_ROW,
+ SHORT_ROW,
+ _make_cfg,
+ _tiny_llama_dir,
+)
+
+ASSISTANT_ONLY = {
+ "messages": [
+ {"role": "assistant", "content": "I have no preceding prompt."},
+ ]
+}
+
+ASSISTANT_ONLY_2 = {
+ "messages": [
+ {"role": "assistant", "content": "Another assistant-only turn."},
+ ]
+}
+
+
+class TestSequenceDistillRowNumbering:
+ def test_sequence_and_token_mode_both_refuse_train_row_3(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ """With [ASSISTANT_ONLY, SHORT_ROW, LONG_ROW], both token and sequence mode
+ must report 'train row 3' when LONG_ROW is truncated at max_length=64.
+ """
+ weights = _tiny_llama_dir(tmp_path)
+ dataset = {"train": [ASSISTANT_ONLY, SHORT_ROW, LONG_ROW]}
+
+ # 1. Token mode control
+ token_cfg = load_config_from_string(
+ _make_cfg(weights, tmp_path, max_length=64)
+ )
+ token_wrapper = DistillTrainerWrapper(token_cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"train row 3.*no causal-loss target.*data\.max_length=64",
+ ) as exc_token:
+ token_wrapper.setup(dataset)
+ assert "train row 3:" in str(exc_token.value)
+
+ # 2. Sequence mode: must also report train row 3 (not train row 2)
+ seq_cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ extra_training=" distill_mode: sequence\n",
+ )
+ )
+ seq_wrapper = DistillTrainerWrapper(seq_cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"train row 3.*no causal-loss target.*data\.max_length=64",
+ ) as exc_seq:
+ seq_wrapper.setup(dataset)
+ assert "train row 3:" in str(exc_seq.value)
+ assert "(generated by the teacher)" in str(exc_seq.value)
+
+ def test_sequence_and_token_mode_both_refuse_val_row_3(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ """The same 1-based source position is preserved on the val split."""
+ weights = _tiny_llama_dir(tmp_path)
+ dataset = {
+ "train": [SHORT_ROW],
+ "val": [ASSISTANT_ONLY, SHORT_ROW, LONG_ROW],
+ }
+
+ # 1. Token mode
+ token_cfg = load_config_from_string(
+ _make_cfg(weights, tmp_path, max_length=64)
+ )
+ token_wrapper = DistillTrainerWrapper(token_cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"val row 3.*no causal-loss target.*data\.max_length=64",
+ ) as exc_token:
+ token_wrapper.setup(dataset)
+ assert "val row 3:" in str(exc_token.value)
+
+ # 2. Sequence mode
+ seq_cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ extra_training=" distill_mode: sequence\n",
+ )
+ )
+ seq_wrapper = DistillTrainerWrapper(seq_cfg, device="cpu")
+ with pytest.raises(
+ ValueError,
+ match=r"val row 3.*no causal-loss target.*data\.max_length=64",
+ ) as exc_seq:
+ seq_wrapper.setup(dataset)
+ assert "val row 3:" in str(exc_seq.value)
+ assert "(generated by the teacher)" in str(exc_seq.value)
+
+ def test_sequence_mode_refuses_when_all_train_rows_skipped(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ """Sequence mode with only assistant-only rows is refused at setup with a message
+ about the dropped rows, not num_samples=0 at train().
+ """
+ weights = _tiny_llama_dir(tmp_path)
+ seq_cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ extra_training=" distill_mode: sequence\n",
+ )
+ )
+ seq_wrapper = DistillTrainerWrapper(seq_cfg, device="cpu")
+ pattern = (
+ r"train split has 0 usable rows after skipping 2 row\(s\) with "
+ r"no prompt turn \(positions: 1, 2\)"
+ )
+ with pytest.raises(ValueError, match=pattern):
+ seq_wrapper.setup({"train": [ASSISTANT_ONLY, ASSISTANT_ONLY_2]})
+
+ def test_sequence_mode_refuses_when_all_val_rows_skipped(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ """Sequence mode with an empty val split after skipping is refused at setup."""
+ weights = _tiny_llama_dir(tmp_path)
+ seq_cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ extra_training=" distill_mode: sequence\n",
+ )
+ )
+ seq_wrapper = DistillTrainerWrapper(seq_cfg, device="cpu")
+ pattern = (
+ r"val split has 0 usable rows after skipping 1 row\(s\) with "
+ r"no prompt turn \(positions: 1\)"
+ )
+ with pytest.raises(ValueError, match=pattern):
+ seq_wrapper.setup({"train": [SHORT_ROW], "val": [ASSISTANT_ONLY]})
+
+ def test_sequence_mode_reports_skipped_rows_to_console(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ """Setup output states how many rows had no prompt turn and were skipped."""
+ weights = _tiny_llama_dir(tmp_path)
+ seq_cfg = load_config_from_string(
+ _make_cfg(
+ weights,
+ tmp_path,
+ max_length=64,
+ extra_training=" distill_mode: sequence\n",
+ )
+ )
+ seq_wrapper = DistillTrainerWrapper(seq_cfg, device="cpu")
+
+ printed_messages: list[str] = []
+
+ def _record_print(msg: object, **kw: object) -> None:
+ printed_messages.append(str(msg))
+
+ with mock.patch("soup_cli.trainer.distill.console.print", side_effect=_record_print):
+ seq_wrapper.setup({
+ "train": [ASSISTANT_ONLY, SHORT_ROW],
+ "val": [ASSISTANT_ONLY, SHORT_ROW],
+ })
+
+ train_skip_msgs = [
+ m for m in printed_messages
+ if "Skipped 1 train row(s)" in m and "positions: 1" in m
+ ]
+ val_skip_msgs = [
+ m for m in printed_messages
+ if "Skipped 1 val row(s)" in m and "positions: 1" in m
+ ]
+ assert len(train_skip_msgs) == 1
+ assert len(val_skip_msgs) == 1
+
+ def test_build_sequence_distill_rows_unit_preserves_source_index(self) -> None:
+ """Unit test: build_sequence_distill_rows attaches _source_index to emitted rows."""
+ import torch
+
+ class _FakeTok:
+ eos_token = "</s>"
+
+ def apply_chat_template(self, messages, tokenize, **kw):
+ return torch.tensor([[1, 2, 3]])
+
+ def decode(self, ids, skip_special_tokens=True):
+ return "teacher-output"
+
+ class _FakeTeacher:
+ def generate(self, input_ids, max_new_tokens=None, **kw):
+ return torch.tensor([[1, 2, 3, 9, 10]])
+
+ def to(self, *a, **k):
+ return self
+
+ @property
+ def device(self):
+ return torch.device("cpu")
+
+ rows = [
+ ASSISTANT_ONLY, # idx 0 -> skipped
+ {"messages": [{"role": "user", "content": "hello"}]}, # idx 1 -> kept
+ ASSISTANT_ONLY, # idx 2 -> skipped
+ {"messages": [{"role": "user", "content": "world"}]}, # idx 3 -> kept
+ ]
+ out = build_sequence_distill_rows(
+ rows, _FakeTeacher(), _FakeTok(), max_new_tokens=4, device="cpu"
+ )
+ assert len(out) == 2
+ assert out[0]["_source_index"] == 1
+ assert out[1]["_source_index"] == 3
+ assert out[0]["messages"][-1]["content"] == "teacher-output"
+
+
+def _wrapper(tmp_path: pathlib.Path, *, sequence: bool) -> DistillTrainerWrapper:
+ weights = _tiny_llama_dir(tmp_path)
+ extra = " distill_mode: sequence\n" if sequence else ""
+ cfg = load_config_from_string(_make_cfg(weights, tmp_path, max_length=64, extra_training=extra))
+ return DistillTrainerWrapper(cfg, device="cpu")
+
+
+class TestARowCannotRenumberItself:
+ """`_source_index` is Soup's own bookkeeping; a column of that name in the data is data."""
+
+ def test_token_mode_ignores_a_source_index_column(self, tmp_path: pathlib.Path) -> None:
+ rows = [{**SHORT_ROW, "_source_index": "abc"}, {**LONG_ROW, "_source_index": "abc"}]
+ with pytest.raises(ValueError, match=r"^train row 2: no causal-loss target") as caught:
+ _wrapper(tmp_path, sequence=False).setup({"train": rows})
+ assert "generated by the teacher" not in str(caught.value)
+
+ def test_token_mode_ignores_a_source_index_column_in_the_val_split(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ val = [{**SHORT_ROW, "_source_index": "abc"}, {**LONG_ROW, "_source_index": "abc"}]
+ with pytest.raises(ValueError, match=r"^val row 2: no causal-loss target") as caught:
+ _wrapper(tmp_path, sequence=False).setup({"train": [SHORT_ROW], "val": val})
+ assert "generated by the teacher" not in str(caught.value)
+
+ def test_sequence_mode_numbers_rows_by_position_not_by_a_source_index_column(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ rows = [
+ ASSISTANT_ONLY,
+ {**SHORT_ROW, "_source_index": 100},
+ {**LONG_ROW, "_source_index": 7},
+ ]
+ printed: list[str] = []
+ with mock.patch(
+ "soup_cli.trainer.distill.console.print",
+ side_effect=lambda msg, **kw: printed.append(str(msg)),
+ ):
+ with pytest.raises(ValueError, match=r"^train row 3: no causal-loss target"):
+ _wrapper(tmp_path, sequence=True).setup({"train": rows})
+ assert any("Skipped 1 train row(s)" in m and "positions: 1)" in m for m in printed)
+
+
+class TestThePositionsAreCapped:
+ def test_only_the_first_five_skipped_positions_are_named(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ printed: list[str] = []
+ with mock.patch(
+ "soup_cli.trainer.distill.console.print",
+ side_effect=lambda msg, **kw: printed.append(str(msg)),
+ ):
+ _wrapper(tmp_path, sequence=True).setup({"train": [ASSISTANT_ONLY] * 7 + [SHORT_ROW]})
+ skipped = [m for m in printed if "Skipped 7 train row(s)" in m]
+ assert len(skipped) == 1
+ assert "(positions: 1, 2, 3, 4, 5, ...)" in skipped[0]
+