Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
"""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]