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(data): spread canaries through the file so the val split cannot hold them (#1331) (#1386)
Mohammad Hijjawi18187cfee8da
diff --git a/changelog.d/0.75.1/1386.fixed.md b/changelog.d/0.75.1/1386.fixed.mdnew file mode 100644index 00000000..26d737ac--- /dev/null+++ b/changelog.d/0.75.1/1386.fixed.md@@ -0,0 +1,6 @@+- `soup data canary insert` spreads the canaries through the file instead of appending+ them, and records each canary's row in the manifest. The loader holds out the file's+ tail as validation (`data.val_split`, 0.1 by default), so from 135 rows on every appended+ canary was held out, no model trained on it, and `soup data canary check` could only+ report OK. `insert` now prints how many canaries the default split trains on+ (#1331 by @MohammadHijjawi97 in #1386).diff --git a/docs/data.md b/docs/data.mdindex ca8a27fe..a495d9f2 100644--- a/docs/data.md+++ b/docs/data.md@@ -164,6 +164,17 @@ than the chat turn `check` scores, tool-calling puts a tool-schema system turnbefore the prompt, which `check` does not render, and the multimodal formats need areal image or audio file per row. `-o` takes `.jsonl`, or `.json` for a JSON array.+`insert` spreads the canaries through the file rather than appending them: the file is+cut into one equal stretch per canary, and each canary goes to a random row of its own+stretch (`--seed` fixes the rows). The dataset's own rows keep their order. The+loader holds out the file's last rows as validation (`data.val_split`, 0.1 by default),+and a canary there is never trained on, so appending put every canary out of reach+from 135 rows on. Spread, a held-out tail of+`data.val_split` holds about that share of them: `insert` prints how many of them the+default split trains on, and the manifest records each canary's row in the written file+(`"row"`, counted from 0) and the file's row count (`"rows"`). Set `data.val_split: 0`+for a run where every canary must be trained on.+`check` measures the model's loss on each inserted secret and ranks it againstnever-inserted **controls** drawn from the same secret space and sharing the samecarrier prompt — so a low loss means the *secret* is unusually likely, not thediff --git a/src/soup_cli/commands/data_canary.py b/src/soup_cli/commands/data_canary.pyindex b36e794c..ba5d9f32 100644--- a/src/soup_cli/commands/data_canary.py+++ b/src/soup_cli/commands/data_canary.py@@ -20,8 +20,9 @@ from rich.console import Consolefrom rich.markup import escapefrom rich.table import Table+from soup_cli.config.schema import DataConfigfrom soup_cli.data.formats import detect_format-from soup_cli.data.loader import load_raw_data+from soup_cli.data.loader import _split_val, load_raw_datafrom soup_cli.utils.canary import (CANARY_FORMATS,_harden_permissions,@@ -30,6 +31,7 @@ from soup_cli.utils.canary import (canary_rows,generate_canaries,generate_controls,+ interleave_canary_rows,load_manifest,write_manifest,)@@ -152,7 +154,7 @@ def insert(help="Where to write the canary manifest (CONTAINS THE SECRETS)",),count: int = typer.Option(16, "--count", "-k", help="Number of canaries"),- seed: int = typer.Option(0, "--seed", help="Canary generation seed"),+ seed: int = typer.Option(0, "--seed", help="Seed for the canaries and the rows they go to"),data_format: str = typer.Option("auto", "--format",help="Dataset format to write the canaries in: auto (detect), "@@ -181,14 +183,21 @@ def insert(console.print(f"[red]{escape(str(exc))}[/]")raise typer.Exit(1)- mixed = list(rows) + canary_rows(canaries, fmt)+ # Spread through the file, not appended: the loader holds out the file's+ # tail as validation, which would have held every canary (#1331).+ mixed, positions = interleave_canary_rows(+ rows, canary_rows(canaries, fmt), seed=seed+ )# Manifest FIRST. If the dataset were written first and the manifest# then failed (disk full, permissions), a canary-poisoned dataset would# survive on disk with nothing left to identify the secrets in it — a# user who missed the error and trained on it could never audit what# was inserted. Failing before the data is written leaves no artifact.try:- write_manifest(canaries, manifest, fmt)+ write_manifest(+ canaries, manifest, fmt,+ positions=positions, total_rows=len(mixed),+ )except (ValueError, OSError) as exc:console.print(f"[red]{escape(str(exc))}[/]")raise typer.Exit(1)@@ -216,6 +225,15 @@ def insert(f"Output: [bold]{escape(output)}[/]\n"f"Manifest: [bold]{escape(manifest)}[/]")+ # The loader's own split, so the count is what `soup train` holds out.+ val_split = DataConfig.model_fields["val_split"].default+ train_part, _ = _split_val(list(range(len(mixed))), val_split)+ trained = sum(1 for position in positions if position < len(train_part))+ console.print(+ f"At the default data.val_split ({val_split}), {trained} of "+ f"{len(canaries)} canaries are in the training split; the rest are "+ "in the held-out tail."+ )console.print("[yellow]The manifest contains the secret canaries. Do NOT commit it ""alongside the dataset it protects — anyone holding it can reproduce "diff --git a/src/soup_cli/utils/canary.py b/src/soup_cli/utils/canary.pyindex b6385faa..1c5403b3 100644--- a/src/soup_cli/utils/canary.py+++ b/src/soup_cli/utils/canary.py@@ -169,8 +169,42 @@ def canary_rows(canaries: Sequence[Canary], fmt: str = "chatml") -> list[dict]:return [_canary_row(canary, fmt) for canary in canaries]+def interleave_canary_rows(+ rows: Sequence[Any], inserted: Sequence[dict], *, seed: int+) -> tuple[list, tuple[int, ...]]:+ """Spread ``inserted`` through ``rows``; return the mix and their positions.++ ``positions[i]`` is the 0-based row of ``inserted[i]`` in the mix. The mix+ is cut into ``len(inserted)`` equal stretches and each canary goes to a+ seeded random row of its own stretch, so the canaries cannot sit together+ at either end (#1331). Appending them put every one in the tail that+ ``data.val_split`` holds out for validation, where no model trains on+ them and ``check`` can only report OK. Spread evenly, a tail of fraction+ ``v`` holds about ``v`` of them, whatever the seed.+ """+ count = len(inserted)+ total = len(rows) + count+ rng = random.Random(seed)+ positions = tuple(+ rng.randrange(i * total // count, (i + 1) * total // count)+ for i in range(count)+ )+ slots = dict(zip(positions, inserted))+ source = iter(rows)+ mixed = [+ slots[index] if index in slots else next(source)+ for index in range(total)+ ]+ return mixed, positions++def write_manifest(- canaries: Sequence[Canary], path: str, fmt: str = "chatml"+ canaries: Sequence[Canary],+ path: str,+ fmt: str = "chatml",+ *,+ positions: Sequence[int] | None = None,+ total_rows: int | None = None,) -> str:"""Persist the secrets. THIS FILE IS THE SENSITIVE ARTIFACT.@@ -179,19 +213,29 @@ def write_manifest(POSIX: under the usual 022 umask a generic write lands 0644, lettingany local user on a shared box read every canary without ever running``check``. Mirrors registry/store.py, adapter_sign.py, audit_log.py.++ ``positions`` (from :func:`interleave_canary_rows`) and ``total_rows``+ record where each canary sits in the written dataset, so which canaries a+ given ``data.val_split`` trains on can be worked out later (#1331)."""_require_canary_format(fmt)safe = enforce_under_cwd_and_no_symlink(str(path), "manifest")+ entries = [+ {"carrier": canary.carrier, "secret": canary.secret}+ for canary in canaries+ ]+ if positions is not None:+ for entry, position in zip(entries, positions):+ entry["row"] = positionpayload = {"version": 1,"carrier_template": CARRIER_TEMPLATE,"slug": _SLUG,"format": fmt,- "canaries": [- {"carrier": canary.carrier, "secret": canary.secret}- for canary in canaries- ],+ "canaries": entries,}+ if total_rows is not None:+ payload["rows"] = total_rowsatomic_write_text(json.dumps(payload, indent=2), safe)_harden_permissions(safe)return safediff --git a/tests/test_issue1331_canary_placement.py b/tests/test_issue1331_canary_placement.pynew file mode 100644index 00000000..1e07693e--- /dev/null+++ b/tests/test_issue1331_canary_placement.py@@ -0,0 +1,238 @@+"""#1331: `soup data canary insert` spreads the canaries through the file.++`insert` used to append the canaries, and the loader holds out the file's tail+as validation (`_split_val`, default `data.val_split: 0.1`). From 135 rows on,+all 16 canaries were in validation, no model trained on them, and+`soup data canary check` could only report OK.++The canaries are now spread evenly: the file is cut into K equal stretches and+canary i goes to a seeded random row of stretch i, so a held-out tail of+fraction v holds about v of them for every seed. The manifest records each+canary's row and the file's row count, so which canaries a split trains on can+be worked out from it.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.schema import DataConfig+from soup_cli.data.loader import load_dataset+from soup_cli.utils.canary import canary_rows, generate_canaries, load_manifest+from tests.conftest import strip_ansi++REPO_ROOT = Path(__file__).resolve().parents[1]+++def _plain(text: str) -> str:+ return re.sub(r"\s+", " ", strip_ansi(text)).strip()+++def _write_alpaca(path: Path, count: int) -> None:+ path.write_text(+ "".join(+ json.dumps({"instruction": f"question {i}", "output": f"answer {i}"}) + "\n"+ for i in range(count)+ ),+ encoding="utf-8",+ )+++def _insert(*extra: str):+ return CliRunner().invoke(+ app,+ ["data", "canary", "insert", "train.jsonl", "-o", "canaried.jsonl",+ "--manifest", "m.json", *extra],+ )+++def _secrets_in(rows) -> set[str]:+ blob = json.dumps(list(rows))+ return {c.secret.strip() for c in load_manifest("m.json") if c.secret.strip() in blob}+++# --------------------------------------------------------------------------+# end to end: insert with its defaults, load at the default val_split+# --------------------------------------------------------------------------++[email protected]("rows", [100, 135, 200, 1000])+def test_the_default_split_trains_on_the_canaries(rows, tmp_path, monkeypatch):+ """The issue's table: tail placement put 12, 15, 16 and 16 of 16 in val."""+ monkeypatch.chdir(tmp_path)+ _write_alpaca(Path("train.jsonl"), rows)+ result = _insert()+ assert result.exit_code == 0, (result.output, repr(result.exception))++ manifest = json.loads(Path("m.json").read_text(encoding="utf-8"))+ assert len(manifest["canaries"]) == 16+ assert manifest["rows"] == rows + 16++ config = DataConfig(train="canaried.jsonl", format="auto")+ assert config.val_split == 0.1+ data = load_dataset(config)+ assert len(data["train"]) + len(data["val"]) == rows + 16+ in_train = _secrets_in(data["train"])+ in_val = _secrets_in(data["val"])+ assert len(in_train) + len(in_val) == 16++ # The manifest says which canaries the default split trains on.+ split_idx = len(data["train"])+ trainable = {+ entry["secret"].strip()+ for entry in manifest["canaries"]+ if entry["row"] < split_idx+ }+ assert in_train == trainable+ assert len(in_val) <= 3, sorted(in_val)+ # And `insert` said so.+ assert (+ f"At the default data.val_split (0.1), {len(in_train)} of 16 canaries are "+ "in the training split" in _plain(result.output)+ ), result.output+++# --------------------------------------------------------------------------+# the manifest describes the file+# --------------------------------------------------------------------------++[email protected]("seed", ["0", "7"])[email protected]("suffix", [".jsonl", ".json"])+def test_each_recorded_row_holds_its_canary(suffix, seed, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_alpaca(Path("train.jsonl"), 40)+ result = CliRunner().invoke(+ app,+ ["data", "canary", "insert", "train.jsonl", "-o", f"canaried{suffix}",+ "--manifest", "m.json", "--count", "5", "--seed", seed],+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))++ text = Path(f"canaried{suffix}").read_text(encoding="utf-8")+ written = (+ json.loads(text) if suffix == ".json"+ else [json.loads(line) for line in text.splitlines() if line]+ )+ manifest = json.loads(Path("m.json").read_text(encoding="utf-8"))+ assert manifest["rows"] == len(written) == 45+ rows = [entry["row"] for entry in manifest["canaries"]]+ assert rows == sorted(set(rows))+ for entry in manifest["canaries"]:+ assert written[entry["row"]] == {+ "instruction": entry["carrier"], "output": entry["secret"].strip(),+ }+ # Every other row is the dataset's, in its original order.+ others = [row for i, row in enumerate(written) if i not in set(rows)]+ assert others == [+ {"instruction": f"question {i}", "output": f"answer {i}"} for i in range(40)+ ]+ # `check` still reads the manifest.+ assert len(load_manifest("m.json")) == 5+++def test_the_printed_count_follows_the_loaders_split(tmp_path, monkeypatch):+ """20 rows at val_split 0.1 train on rows 0-17: a canary on row 17 is trained+ on and one on row 18, the first held-out row, is not."""+ from soup_cli.commands import data_canary as cmd++ monkeypatch.chdir(tmp_path)+ _write_alpaca(Path("train.jsonl"), 18)++ def _at_the_boundary(rows, inserted, *, seed):+ mixed = list(rows[:17]) + [inserted[0], inserted[1]] + list(rows[17:])+ return mixed, (17, 18)++ monkeypatch.setattr(cmd, "interleave_canary_rows", _at_the_boundary)+ result = _insert("--count", "2")+ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert (+ "At the default data.val_split (0.1), 1 of 2 canaries are in the training "+ "split" in _plain(result.output)+ ), result.output++ data = load_dataset(DataConfig(train="canaried.jsonl", format="auto"))+ assert len(data["train"]) == 18+ assert len(_secrets_in(data["train"])) == 1+++def test_insertion_is_deterministic_in_the_seed(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_alpaca(Path("train.jsonl"), 300)++ def _run(seed: str) -> tuple[str, str]:+ result = _insert("--seed", seed)+ assert result.exit_code == 0, (result.output, repr(result.exception))+ return (+ Path("canaried.jsonl").read_text(encoding="utf-8"),+ Path("m.json").read_text(encoding="utf-8"),+ )++ first = _run("3")+ assert _run("3") == first++ def _rows(manifest_text: str) -> list[int]:+ return [entry["row"] for entry in json.loads(manifest_text)["canaries"]]++ assert _rows(_run("4")[1]) != _rows(first[1])+++# --------------------------------------------------------------------------+# the placement itself+# --------------------------------------------------------------------------++[email protected]("seed", range(10))[email protected]("rows, count", [(0, 16), (1, 16), (100, 16), (135, 16),+ (1000, 16), (7, 3), (50, 1)])+def test_each_canary_lands_in_its_own_stretch_of_the_file(rows, count, seed):+ """Canary i sits in the i-th of `count` equal stretches of the mix, so no+ end of the file (the val tail included) can collect them."""+ from soup_cli.utils.canary import interleave_canary_rows++ data = [{"instruction": f"q{i}", "output": f"a{i}"} for i in range(rows)]+ inserted = canary_rows(generate_canaries(count=count, seed=seed), "alpaca")++ mixed, positions = interleave_canary_rows(data, inserted, seed=seed)++ total = rows + count+ assert len(mixed) == total+ assert [mixed[p] for p in positions] == inserted+ assert [row for i, row in enumerate(mixed) if i not in positions] == data+ for i, position in enumerate(positions):+ assert i * total // count <= position < (i + 1) * total // count, (i, position)++[email protected]("seed", range(10))[email protected]("val_split", [0.05, 0.1, 0.2, 0.5])+def test_a_held_out_tail_holds_about_its_share_for_every_seed(val_split, seed):+ from soup_cli.utils.canary import interleave_canary_rows++ rows, count = 500, 16+ data = [{"instruction": f"q{i}", "output": f"a{i}"} for i in range(rows)]+ inserted = canary_rows(generate_canaries(count=count, seed=0), "alpaca")+ _, positions = interleave_canary_rows(data, inserted, seed=seed)++ split_idx = int((rows + count) * (1 - val_split))+ held_out = sum(1 for p in positions if p >= split_idx)+ assert abs(held_out - val_split * count) <= 1, (held_out, positions)+++# --------------------------------------------------------------------------+# docs+# --------------------------------------------------------------------------+++def test_the_canary_docs_say_how_canaries_meet_val_split():+ text = (REPO_ROOT / "docs" / "data.md").read_text(encoding="utf-8")+ section = text.split("## Canaries (`soup data canary insert|check`)", 1)[1]+ section = " ".join(section.split("\n## ", 1)[0].split())+ assert "data.val_split" in section, section+ assert "spread" in section, section+ assert '"row"' in section, section