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
Fix #1251: soup data doctor --show-mask honors mask_history via --mask-history flag (#1259)
Kratosda1e3f126ef7
diff --git a/changelog.d/0.75.1/1259.fixed.md b/changelog.d/0.75.1/1259.fixed.mdnew file mode 100644index 00000000..a9b8b990--- /dev/null+++ b/changelog.d/0.75.1/1259.fixed.md@@ -0,0 +1 @@+- **`soup data doctor` gains `--mask-history/--no-mask-history` (default off), so the compat report and the `--show-mask` preview train only the last assistant turn, as a `data.mask_history: true` run does (#1251 by @wanjinhao1 in #1259).** `--mask-history` is refused together with `--no-train-on-responses-only` or `--train-on-messages-with-train-field`, the same combinations `soup.yaml` refuses.diff --git a/docs/data.md b/docs/data.mdindex 3d13af15..ec4d2651 100644--- a/docs/data.md+++ b/docs/data.md@@ -1166,6 +1166,11 @@ turn), `unknown_roles`, and `truncation_risk` (p95 rendered length vs`data.max_length`). `--train-on-responses-only` / `--train-on-messages-with-train-field`select the same masking strategy `soup train` would use, so the report and`--show-mask` preview can never disagree about what's actually trained.+`--mask-history` (default off, matching `data.mask_history`) narrows the+assistant-only mask to the **last** assistant turn, exactly like the+soup.yaml flag of the same name; it is refused with+`--no-train-on-responses-only` or `--train-on-messages-with-train-field`,+the same combinations `soup.yaml` refuses.## Preference-Data Linter (`soup data lint`)diff --git a/src/soup_cli/commands/data_doctor.py b/src/soup_cli/commands/data_doctor.pyindex c7150009..849cd7ea 100644--- a/src/soup_cli/commands/data_doctor.py+++ b/src/soup_cli/commands/data_doctor.py@@ -151,6 +151,10 @@ def doctor(False, "--train-on-messages-with-train-field",help="Per-message train:bool field masking (mirrors the same soup.yaml flag).",),+ mask_history: bool = typer.Option(+ False, "--mask-history/--no-mask-history",+ help="Train only the LAST assistant turn (mirrors data.mask_history).",+ ),train_on_eot: bool = typer.Option(False, "--train-on-eot",help="Extend the trained span through the trailing EOS/EOT token.",@@ -177,6 +181,30 @@ def doctor(console.print(f"[red]File not found: {file_path}[/]")raise typer.Exit(code=1)+ # Mirrors the soup.yaml schema rules (#1251): "data.mask_history+ # requires data.train_on_responses_only: true", and mask_history is+ # mutually exclusive with train_on_messages_with_train_field — refuse+ # the flag combos up front, before any tokenizer load or dataset work.+ if mask_history and (+ train_on_messages_with_train_field or not train_on_responses_only+ ):+ conflict = (+ "--train-on-messages-with-train-field"+ if train_on_messages_with_train_field+ else "--no-train-on-responses-only"+ )+ console.print(+ f"[red]Error:[/] [bold]--mask-history[/] narrows the assistant-only "+ f"loss mask to the last assistant turn, but [bold]{conflict}[/] "+ "takes a different path: with --no-train-on-responses-only every "+ "token trains (the legacy full-sequence path), and with "+ "--train-on-messages-with-train-field the per-message train:bool "+ "field decides. soup.yaml refuses both combinations. Re-run with "+ "--train-on-responses-only and without "+ "--train-on-messages-with-train-field, or drop --mask-history."+ )+ raise typer.Exit(code=EXIT_USAGE_ERROR)+data = load_raw_data(file_path)if not data:console.print("[red]Dataset is empty.[/]")@@ -208,6 +236,7 @@ def doctor(sample_size=sample, include_eot=train_on_eot,train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,+ mask_history=mask_history,)except ValueError as exc:console.print(f"[red]Error:[/] {escape(str(exc))}")@@ -230,6 +259,7 @@ def doctor(train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,include_eot=train_on_eot,+ mask_history=mask_history,)except ValueError as exc:console.print(f"[red]Error:[/] {escape(str(exc))}")diff --git a/src/soup_cli/utils/data_doctor.py b/src/soup_cli/utils/data_doctor.pyindex 77473129..a4ebc776 100644--- a/src/soup_cli/utils/data_doctor.py+++ b/src/soup_cli/utils/data_doctor.py@@ -250,6 +250,7 @@ def _build_row_labels(train_on_responses_only: bool,train_on_messages_with_train_field: bool,include_eot: bool,+ mask_history: bool = False,) -> dict:"""Build ``{input_ids, labels}`` via the SAME masking-strategy dispatch``data.sft_format.build_format_row`` uses at train time (per-message@@ -268,7 +269,8 @@ def _build_row_labels(return build_per_message_train_labels(messages, tokenizer, max_length=max_length)if train_on_responses_only:return build_assistant_only_labels(- messages, tokenizer, max_length=max_length, include_eot=include_eot+ messages, tokenizer, max_length=max_length, include_eot=include_eot,+ mask_history=mask_history,)# #788: legacy full-sequence path — call the SAME builder the trainer uses# (build_full_sequence_labels) so --show-mask reflects the one-BOS,@@ -389,6 +391,7 @@ def check_eos_in_labels(include_eot: bool = False,train_on_responses_only: bool = True,train_on_messages_with_train_field: bool = False,+ mask_history: bool = False,) -> DoctorCheck:"""The #1 'model never stops generating' bug. MAJOR when >=50% of rowshave at least one assistant turn whose trained span never trains an@@ -421,6 +424,7 @@ def check_eos_in_labels(train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,include_eot=include_eot,+ mask_history=mask_history,)except Exception: # noqa: BLE001 — a row the template can't render (e.g. an# unsupported system role — jinja2.TemplateError, not a ValueError/@@ -473,6 +477,7 @@ def check_bos_duplication(max_length: int,train_on_responses_only: bool = True,train_on_messages_with_train_field: bool = False,+ mask_history: bool = False,) -> DoctorCheck:"""MAJOR when >=50% of rows start with two consecutive BOS tokens (thetemplate AND the tokenizer both prepend one — a classic double-BOS@@ -506,6 +511,7 @@ def check_bos_duplication(train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,include_eot=False,+ mask_history=mask_history,)except Exception: # noqa: BLE001 — a row the template can't render is# reported by template_render/system_role; skip it here.@@ -664,6 +670,7 @@ def run_doctor(include_eot: bool = False,train_on_responses_only: bool = True,train_on_messages_with_train_field: bool = False,+ mask_history: bool = False,) -> DoctorReport:"""Run the full chat-template compat report over a sample of ``raw_rows``.@@ -690,6 +697,17 @@ def run_doctor(raise TypeError("train_on_responses_only must be bool")if not isinstance(train_on_messages_with_train_field, bool):raise TypeError("train_on_messages_with_train_field must be bool")+ if not isinstance(mask_history, bool):+ raise TypeError("mask_history must be bool")+ if mask_history and (+ train_on_messages_with_train_field or not train_on_responses_only+ ):+ raise ValueError(+ "mask_history requires train_on_responses_only and cannot combine "+ "with train_on_messages_with_train_field — data.mask_history "+ "narrows the assistant-only loss mask (soup.yaml schema rule: "+ "data.mask_history requires data.train_on_responses_only: true)"+ )from soup_cli.data.formats import format_to_messages@@ -717,11 +735,13 @@ def run_doctor(tokenizer, normalized, max_length=max_length, include_eot=include_eot,train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,+ mask_history=mask_history,),check_bos_duplication(tokenizer, normalized, max_length=max_length,train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,+ mask_history=mask_history,),check_system_role(tokenizer, normalized),check_unknown_roles(normalized),@@ -804,6 +824,7 @@ def _build_chat_preview_row(train_on_responses_only: bool,train_on_messages_with_train_field: bool,include_eot: bool,+ mask_history: bool = False,) -> Optional[Tuple[str, Tuple[MaskedToken, ...]]]:from soup_cli.data.formats import format_to_messages@@ -822,6 +843,7 @@ def _build_chat_preview_row(train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,include_eot=include_eot,+ mask_history=mask_history,)except Exception: # noqa: BLE001 — a row the template can't render (e.g. an# unsupported system role) is a per-row skip, not a crash — mirrors the@@ -867,6 +889,7 @@ def render_mask_preview(train_on_responses_only: bool = True,train_on_messages_with_train_field: bool = False,include_eot: bool = False,+ mask_history: bool = False,) -> List[MaskPreviewRow]:"""Render up to ``n`` rows with per-token trained/masked colouring.@@ -880,6 +903,17 @@ def render_mask_preview(raise ValueError("n must be a positive int")if n > _MAX_PREVIEW_ROWS:raise ValueError(f"n must be <= {_MAX_PREVIEW_ROWS}")+ if not isinstance(mask_history, bool):+ raise TypeError("mask_history must be bool")+ if mask_history and (+ train_on_messages_with_train_field or not train_on_responses_only+ ):+ raise ValueError(+ "mask_history requires train_on_responses_only and cannot combine "+ "with train_on_messages_with_train_field — it narrows the "+ "assistant-only loss mask (data.mask_history requires "+ "data.train_on_responses_only: true)"+ )previews: List[MaskPreviewRow] = []for row_index, row in enumerate(raw_rows[:_MAX_MASK_SCAN_ROWS]):@@ -896,6 +930,7 @@ def render_mask_preview(train_on_responses_only=train_on_responses_only,train_on_messages_with_train_field=train_on_messages_with_train_field,include_eot=include_eot,+ mask_history=mask_history,)if result is None:continuediff --git a/tests/test_issue1251_data_doctor_mask_history.py b/tests/test_issue1251_data_doctor_mask_history.pynew file mode 100644index 00000000..ed57728b--- /dev/null+++ b/tests/test_issue1251_data_doctor_mask_history.py@@ -0,0 +1,298 @@+"""#1251: ``soup data doctor`` ignored ``data.mask_history`` — the compat+report and the ``--show-mask`` preview trained every assistant turn while a+``mask_history: true`` run trains only the last.++The fix threads a ``mask_history`` flag through ``_build_row_labels`` and+every caller that already takes ``train_on_responses_only``, adds a+``--mask-history/--no-mask-history`` CLI flag (default off, matching+``DataConfig``), and refuses ``--mask-history`` together with+``--no-train-on-responses-only`` — mirroring the soup.yaml schema rule+``data.mask_history requires data.train_on_responses_only: true``.++Like #761's tests, these count **trained label positions**, never a flag: a+boolean assertion would not catch the flag being accepted and silently+ignored (the exact bug this issue reports).+"""++import json++import pytest++from soup_cli.data.loss_mask import IGNORE_INDEX++pytestmark = pytest.mark.unit++_SPECIALS = ["<unk>", "<s>", "</s>", "<|user|>", "<|assistant|>", "<|end|>"]+_WORDS = [+ "Hi", "Hello", "there", "What", "is", "two", "plus", "Four", "Three",+ "and", "one", "more", "Thanks", "Welcome", "you", "are",+]++# Plain template (no {% generation %}) and the generation-marker variant —+# build_assistant_only_labels reaches its labels by different code on the two.+_BODY = (+ "{% for m in messages %}<|{{ m['role'] }}|> "+ "{{ m['content'] }} <|end|> {% endfor %}"+)+_BODY_WITH_GENERATION = (+ "{% for m in messages %}<|{{ m['role'] }}|> "+ "{% if m['role'] == 'assistant' %}{% generation %}{{ m['content'] }}"+ "{% endgeneration %}{% else %}{{ m['content'] }}{% endif %}"+ " <|end|> {% endfor %}"+)+_TEMPLATES = ["generation_markers", "no_markers"]++_TWO_TURN = [+ {"role": "user", "content": "Hi there"},+ {"role": "assistant", "content": "Hello there"},+ {"role": "user", "content": "What is two plus two"},+ {"role": "assistant", "content": "Four"},+]+_THREE_TURN = _TWO_TURN + [+ {"role": "user", "content": "and one more"},+ {"role": "assistant", "content": "Thanks you are Welcome"},+]+++def _tokenizer(chat_template):+ transformers = pytest.importorskip("transformers")+ tokenizers = pytest.importorskip("tokenizers")+ from tokenizers import models, pre_tokenizers++ vocab = {token: index for index, token in enumerate(_SPECIALS + _WORDS)}+ backend = tokenizers.Tokenizer(models.WordLevel(vocab=vocab, unk_token="<unk>"))+ backend.pre_tokenizer = pre_tokenizers.Whitespace()+ backend.add_special_tokens(_SPECIALS)+ tok = transformers.PreTrainedTokenizerFast(+ tokenizer_object=backend, unk_token="<unk>", bos_token="<s>", eos_token="</s>"+ )+ tok.chat_template = chat_template+ return tok+++def _row(messages):+ return {"messages": [dict(m) for m in messages]}+++def _trained_positions(tok, messages, *, mask_history):+ """Count trained label positions via the --show-mask preview path."""+ from soup_cli.utils.data_doctor import render_mask_preview++ previews = render_mask_preview(+ [_row(messages)], tok, fmt="chatml", n=1, max_length=2048,+ train_on_responses_only=True, mask_history=mask_history,+ )+ assert len(previews) == 1+ return sum(1 for token in previews[0].tokens if token.trained)+++def _expected_trained_positions(messages, tok, *, mask_history):+ """Ground truth from the SAME builder the trainer uses."""+ from soup_cli.data.loss_mask import build_assistant_only_labels++ labels = build_assistant_only_labels(+ messages, tok, max_length=2048, mask_history=mask_history+ )["labels"]+ return sum(1 for label in labels if label != IGNORE_INDEX)+++class TestShowMaskPreviewHonorsMaskHistory:+ @pytest.mark.parametrize("template", _TEMPLATES)+ def test_two_turn_preview_trains_only_the_last_assistant_span(self, template):+ tok = _tokenizer(+ _BODY_WITH_GENERATION if template == "generation_markers" else _BODY+ )+ with_flag = _trained_positions(tok, _TWO_TURN, mask_history=True)+ without_flag = _trained_positions(tok, _TWO_TURN, mask_history=False)+ assert with_flag == _expected_trained_positions(+ _TWO_TURN, tok, mask_history=True+ )+ assert with_flag < without_flag++ @pytest.mark.parametrize("template", _TEMPLATES)+ def test_three_turn_preview_trains_only_the_last_assistant_span(self, template):+ tok = _tokenizer(+ _BODY_WITH_GENERATION if template == "generation_markers" else _BODY+ )+ with_flag = _trained_positions(tok, _THREE_TURN, mask_history=True)+ without_flag = _trained_positions(tok, _THREE_TURN, mask_history=False)+ assert with_flag == _expected_trained_positions(+ _THREE_TURN, tok, mask_history=True+ )+ assert with_flag < without_flag++ def test_default_off_trains_every_assistant_turn(self):+ """The flag's default is off (matches DataConfig): without it the+ preview must keep training every assistant turn. This is also the+ no-op detector — if mask_history were accepted and ignored, the+ two/three-turn assertions above would fail because with_flag would+ equal without_flag."""+ tok = _tokenizer(_BODY)+ without_flag = _trained_positions(tok, _TWO_TURN, mask_history=False)+ assert without_flag == _expected_trained_positions(+ _TWO_TURN, tok, mask_history=False+ )+ assert without_flag > _trained_positions(tok, _TWO_TURN, mask_history=True)++ def test_trained_spans_match_build_assistant_only_labels_bit_for_bit(self):+ """The preview and the trainer's label builder must agree exactly."""+ tok = _tokenizer(_BODY_WITH_GENERATION)+ assert _trained_positions(tok, _THREE_TURN, mask_history=True) == (+ _expected_trained_positions(_THREE_TURN, tok, mask_history=True)+ )+++class TestEngineRefusesMaskHistoryWithoutResponsesOnly:+ def test_render_mask_preview_refuses_the_combination(self):+ from soup_cli.utils.data_doctor import render_mask_preview++ tok = _tokenizer(_BODY)+ with pytest.raises(ValueError) as exc_info:+ render_mask_preview(+ [_row(_TWO_TURN)], tok, fmt="chatml", n=1,+ train_on_responses_only=False, mask_history=True,+ )+ message = str(exc_info.value)+ assert "mask_history" in message+ assert "train_on_responses_only" in message++ def test_run_doctor_refuses_the_combination(self):+ from soup_cli.utils.data_doctor import run_doctor++ tok = _tokenizer(_BODY)+ with pytest.raises(ValueError) as exc_info:+ run_doctor(+ [_row(_TWO_TURN)], tok, fmt="chatml",+ train_on_responses_only=False, mask_history=True,+ )+ message = str(exc_info.value)+ assert "mask_history" in message+ assert "train_on_responses_only" in message+++class TestCliRefusesMaskHistoryWithoutResponsesOnly:+ def test_combo_is_refused_and_names_both_flags(self, tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ monkeypatch.chdir(tmp_path)+ path = tmp_path / "d.jsonl"+ path.write_text(+ json.dumps({"messages": _TWO_TURN}) + "\n", encoding="utf-8"+ )+ result = CliRunner().invoke(+ app,+ [+ "data", "doctor", str(path), "--model", "fake/model",+ "--mask-history", "--no-train-on-responses-only",+ ],+ )+ assert result.exit_code == 3+ text = " ".join(strip_ansi(result.output).split())+ assert "--mask-history" in text+ assert "--train-on-responses-only" in text+++# ---------------------------------------------------------------------------+# CLI end-to-end: the flag a user types must reach the engine (#1251,+# acceptance item 2 — a no-op flag must fail a test).+# ---------------------------------------------------------------------------++_EOS_LAST_ONLY = (+ "{% for m in messages %}<|{{ m['role'] }}|> {{ m['content'] }} <|end|> "+ "{% if loop.last %}</s>{% endif %}{% endfor %}"+)+++def _invoke_doctor(monkeypatch, tmp_path, template, *extra):+ from typer.testing import CliRunner++ import soup_cli.utils.data_doctor as engine+ from soup_cli.cli import app++ tok = _tokenizer(template)+ monkeypatch.setattr(+ engine, "resolve_tokenizer", lambda model, *, trust_remote_code=False: tok+ )+ trained = []+ real = engine.render_mask_preview++ def spy(*args, **kwargs):+ rows = real(*args, **kwargs)+ trained.extend(sum(t.trained for t in row.tokens) for row in rows)+ return rows++ monkeypatch.setattr(engine, "render_mask_preview", spy)+ monkeypatch.chdir(tmp_path)+ path = tmp_path / "d.jsonl"+ path.write_text(json.dumps({"messages": _THREE_TURN}) + "\n", encoding="utf-8")+ result = CliRunner().invoke(+ app, ["data", "doctor", str(path), "--model", "fake/model", *extra]+ )+ return result, trained++[email protected](("extra", "expected"), [((), 13), (("--mask-history",), 6)])+def test_cli_show_mask_honours_the_flag(monkeypatch, tmp_path, extra, expected):+ _, trained = _invoke_doctor(monkeypatch, tmp_path, _BODY, "--show-mask", "1", *extra)+ assert trained == [expected]++[email protected](("extra", "exit_code"), [((), 2), (("--mask-history",), 0)])+def test_cli_report_honours_the_flag(monkeypatch, tmp_path, extra, exit_code):+ # EOS closes only the last turn: training every turn leaves earlier turns+ # without one (eos_in_labels MAJOR, exit 2); training only the last is OK.+ result, _ = _invoke_doctor(monkeypatch, tmp_path, _EOS_LAST_ONLY, *extra)+ assert result.exit_code == exit_code, result.output+++# ---------------------------------------------------------------------------+# --mask-history --train-on-messages-with-train-field must be refused too+# (soup.yaml refuses the pair in every spelling; the doctor must match).+# ---------------------------------------------------------------------------+++def test_cli_refuses_mask_history_with_the_train_field(tmp_path, monkeypatch):+ from typer.testing import CliRunner++ import soup_cli.utils.data_doctor as engine+ from soup_cli.cli import app+ from tests.conftest import strip_ansi++ # A local tokenizer, so a regression shows up as a wrong exit code+ # rather than as an attempt to download "fake/model".+ tok = _tokenizer(_BODY)+ monkeypatch.setattr(+ engine, "resolve_tokenizer", lambda model, *, trust_remote_code=False: tok+ )+ monkeypatch.chdir(tmp_path)+ path = tmp_path / "d.jsonl"+ path.write_text(json.dumps({"messages": _TWO_TURN}) + "\n", encoding="utf-8")+ result = CliRunner().invoke(+ app,+ [+ "data", "doctor", str(path), "--model", "fake/model",+ "--mask-history", "--train-on-messages-with-train-field",+ ],+ )+ assert result.exit_code == 3, (result.output, repr(result.exception))+ plain = " ".join(strip_ansi(result.output).split())+ assert "--mask-history" in plain+ assert "--train-on-messages-with-train-field" in plain++[email protected]("entry", ["run_doctor", "render_mask_preview"])+def test_engine_refuses_mask_history_with_the_train_field(entry):+ from soup_cli.utils import data_doctor as engine++ kwargs = {+ "fmt": "chatml",+ "mask_history": True,+ "train_on_messages_with_train_field": True,+ }+ if entry == "render_mask_preview":+ kwargs["n"] = 1+ with pytest.raises(ValueError, match="train_on_messages_with_train_field"):+ getattr(engine, entry)([_row(_TWO_TURN)], _tokenizer(_BODY), **kwargs)