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): say why a pre_tokenized cache is refused after #1127 (#1281)
Jakub Krasuski7cd564e163af
diff --git a/changelog.d/0.75.1/1281.fixed.md b/changelog.d/0.75.1/1281.fixed.mdnew file mode 100644index 00000000..dc973f0b--- /dev/null+++ b/changelog.d/0.75.1/1281.fixed.md@@ -0,0 +1,6 @@+- **A refused `pre_tokenized` cache now says why (#1272 by @Blizzeq in #1281).**+ `soup data preprocess` records the key generation and the row-set inputs in+ `metadata.json`. When training refuses a cache, the message says it predates+ row-set keying (#1127), or names the `data.*` fields whose values differ, such as+ `data.val_split`, instead of showing two bare hashes. `docs/data.md` lists the+ fields a `pre_tokenized` config must keep as they were at preprocess time.diff --git a/docs/data.md b/docs/data.mdindex 059a78d4..aa7d1366 100644--- a/docs/data.md+++ b/docs/data.md@@ -1081,7 +1081,7 @@ dataset without `labels` trains on every token, because TRL's collator copies`input_ids` into `labels`. That is the pretraining objective, and a`soup data preprocess` cache built for `task: pretrain` records the same labels.-The full key, as `PREPROCESS_KEY_FIELDS` in `soup_cli/utils/data_pipeline.py`+The full key, as `PREPROCESS_KEY_FIELDS` in `src/soup_cli/utils/data_pipeline.py`declares it:| Key input | Config fields |@@ -1101,6 +1101,13 @@ loaders choose rows and their order. Every other `data` field is listed innew field must be added to one of the two tables. Caches written before this(tokenizer schema `v6` and earlier) are refused; re-run `soup data preprocess`.+The `pre_tokenized` training config must keep `data.val_split`, `data.replay`,+`data.replay_ratio`, `data.replay_seed`, `data.streaming`, `data.buffer_size`,+`data.image_dir` and `data.audio_dir` as they were when the cache was built, as it+must keep the chat template. A cache built under different values is refused, and+the message names the fields that changed. A cache written before this keying+says so instead of showing two bare hashes.+## Data Recipe DAG Runner (`soup data recipe --execute`)diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.pyindex f3dfcc8b..c8ed3963 100644--- a/src/soup_cli/commands/data.py+++ b/src/soup_cli/commands/data.py@@ -2716,6 +2716,7 @@ def preprocess_dataset(raisefrom soup_cli import __version__ as _soup_version+ from soup_cli.utils.data_pipeline import _PREPROCESS_TOKENIZE_SCHEMAmetadata = {"cache_key": cache_key,@@ -2726,6 +2727,10 @@ def preprocess_dataset("chat_template": cfg.data.chat_template,"mask_mode": mask_mode,"task": cfg.task,+ # #1272: what the gate needs to say why a cache is refused -- the key+ # generation, and the row-set inputs so it can name the fields that differ.+ "key_schema": _PREPROCESS_TOKENIZE_SCHEMA,+ "dataset_key": json.loads(dataset_path),"soup_version": _soup_version,}metadata_path = target / "metadata.json"diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex e6cede4c..a6ae2dce 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -458,7 +458,7 @@ def _make_vision_trainer(def _maybe_load_pretokenized(- dcfg, base: str, console_obj: Console, tcfg=None, task: str = "sft",+ dcfg, base: str, console_obj: Console, tcfg=None, *, task: str,) -> Optional[Tuple[object, object]]:"""v0.53.7 #86 — short-circuit tokenization when caller pre-tokenized via``soup data preprocess``.@@ -484,6 +484,7 @@ def _maybe_load_pretokenized(from soup_cli.utils.data_pipeline import (load_pretokenized_dataset,make_preprocess_cache_key,+ preprocess_dataset_key_diff,preprocess_dataset_key_input,preprocess_mask_mode,)@@ -508,8 +509,9 @@ def _maybe_load_pretokenized(source_format = metadata.get("format")if not isinstance(source_format, str) or not source_format:source_format = dcfg.format+ dataset_key = preprocess_dataset_key_input(dcfg)current_key = make_preprocess_cache_key(- dataset_path=preprocess_dataset_key_input(dcfg),+ dataset_path=dataset_key,tokenizer_name=base,max_length=dcfg.max_length,format_name=source_format,@@ -528,8 +530,19 @@ def _maybe_load_pretokenized(predates = "the cache predates chat_template keying (#1067); "elif "mask_mode" not in metadata:predates = "the cache predates loss-mask keying (#1054); "+ elif "key_schema" not in metadata:+ predates = "the cache predates row-set keying (#1127); "else:- predates = ""+ changed = preprocess_dataset_key_diff(+ metadata.get("dataset_key"), dataset_key+ )+ predates = (+ "the cache was built with a different "+ + ", ".join(f"data.{name}" for name in changed)+ + "; "+ if changed+ else ""+ )raise ValueError("pre_tokenized cache hash mismatch: was generated with "f"{stored_key!r}, current config implies {current_key!r}; "diff --git a/src/soup_cli/utils/data_pipeline.py b/src/soup_cli/utils/data_pipeline.pyindex bdd32601..c3943cf1 100644--- a/src/soup_cli/utils/data_pipeline.py+++ b/src/soup_cli/utils/data_pipeline.py@@ -255,13 +255,13 @@ NOT_PREPROCESS_KEY_FIELDS: Mapping[str, str] = types.MappingProxyType({"shards": "no runtime code reads it","raft_shuffle_seed": "RAFT rows carry no messages, so preprocess caches none","raft_epoch_shuffle": "RAFT rows carry no messages, so preprocess caches none",- "eval_on_each_dataset": "affects evaluation only; the cache holds the train split",+ "eval_on_each_dataset": "no runtime code reads it (staged, #808)","split_thinking": "no runtime code reads it",- "image_min_pixels": "image processing only; the cache holds text tokens",- "image_max_pixels": "image processing only; the cache holds text tokens",- "image_resize_algorithm": "image processing only; the cache holds text tokens",- "video_fps": "video processing only; the cache holds text tokens",- "video_maxlen": "video processing only; the cache holds text tokens",+ "image_min_pixels": "no runtime code reads it (staged, #808)",+ "image_max_pixels": "no runtime code reads it (staged, #808)",+ "image_resize_algorithm": "no runtime code reads it (staged, #808)",+ "video_fps": "no runtime code reads it (staged, #808)",+ "video_maxlen": "no runtime code reads it (staged, #808)","add_new_tokens": ("preprocess tokenizes with the base tokenizer and never adds these ""tokens (the live path does, in apply_vocab_expansion), so the cached ids "@@ -275,7 +275,10 @@ NOT_PREPROCESS_KEY_FIELDS: Mapping[str, str] = types.MappingProxyType({"resize_vocab": "no runtime code reads it","extend_conversation": "no runtime code reads it","skip_prepare_dataset": "no runtime code reads it",- "remove_unused_columns": "trainer argument, applied after the cache is loaded",+ "remove_unused_columns": (+ "no trainer reads it; the trainers that set remove_unused_columns pass "+ "False (#759)"+ ),"prompt_strategy": ("applied by the live SFT formatter only; preprocess renders messages ""directly and never calls it"@@ -310,6 +313,22 @@ def preprocess_dataset_key_input(data_cfg: Any) -> str:)+def preprocess_dataset_key_diff(stored: Any, current: str) -> List[str]:+ """The ``data.*`` fields whose values differ between two dataset key inputs (#1272).++ ``stored`` is the ``dataset_key`` a cache recorded in ``metadata.json`` (a+ dict); ``current`` is ``preprocess_dataset_key_input``'s JSON for the config+ being trained. Returns the differing field names in table order, so a refused+ cache can name what changed rather than leave two hashes to compare. A+ ``stored`` value that is not a dict (a hand-edited file) names no field+ rather than claim differences it cannot see.+ """+ now = json.loads(current)+ if not isinstance(stored, dict):+ return []+ return [name for name in _DATASET_KEY_FIELDS if stored.get(name) != now.get(name)]++def preprocess_mask_mode(data_cfg, training_cfg=None) -> str:"""The loss-mask mode both sides of the preprocess cache hash (#1054).diff --git a/tests/test_issue1038_preprocess_to_pretokenized.py b/tests/test_issue1038_preprocess_to_pretokenized.pyindex 7c7ba736..93567904 100644--- a/tests/test_issue1038_preprocess_to_pretokenized.py+++ b/tests/test_issue1038_preprocess_to_pretokenized.py@@ -103,7 +103,7 @@ def _gate(tmp_path, train, cache_dir, *, max_length=128, base=_BASE, interleave=f" max_length: {max_length}\n val_split: 0.0\n""output: ./out\n")- return _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock())+ return _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock(), task="sft")class TestTheRoundTrip:diff --git a/tests/test_issue1054_pretokenized_labels.py b/tests/test_issue1054_pretokenized_labels.pyindex a4fbeadb..2b34d038 100644--- a/tests/test_issue1054_pretokenized_labels.py+++ b/tests/test_issue1054_pretokenized_labels.py@@ -577,7 +577,7 @@ class TestCacheKeyCoversMaskMode:max_length=128,)with pytest.raises(ValueError, match="cache hash mismatch") as exc:- _maybe_load_pretokenized(dcfg, "x/y", Console())+ _maybe_load_pretokenized(dcfg, "x/y", Console(), task="sft")assert expected in str(exc.value)assert absent not in str(exc.value)@@ -681,7 +681,7 @@ class TestCacheKeyCoversMaskMode:train_on_messages_with_train_field=True,)with pytest.raises(ValueError, match="cache hash mismatch"):- _maybe_load_pretokenized(dcfg, "x/y", Console())+ _maybe_load_pretokenized(dcfg, "x/y", Console(), task="sft")def test_matching_mask_mode_still_loads(self, tmp_path, monkeypatch):"""Control: the gate must not reject a cache built under the SAME config@@ -701,7 +701,7 @@ class TestCacheKeyCoversMaskMode:tokenized_path=str(cache_dir.relative_to(tmp_path)),max_length=128,)- loaded = _maybe_load_pretokenized(dcfg, "x/y", Console())+ loaded = _maybe_load_pretokenized(dcfg, "x/y", Console(), task="sft")assert loaded is not Nonetrain_ds, _ = loadedassert len(train_ds) == 1diff --git a/tests/test_issue1067_chat_template_cache_key.py b/tests/test_issue1067_chat_template_cache_key.pyindex 62482e9d..cfaef609 100644--- a/tests/test_issue1067_chat_template_cache_key.py+++ b/tests/test_issue1067_chat_template_cache_key.py@@ -63,7 +63,7 @@ def _gate(tmp_path, cache_dir, chat_template=None):_config("pre_tokenized", chat_template, f" tokenized_path: {path}\n")+ "output: ./out\n")- return _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock())+ return _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock(), task="sft")def _first_row(cache_dir):diff --git a/tests/test_issue1127_preprocess_cache_key_fields.py b/tests/test_issue1127_preprocess_cache_key_fields.pyindex 73a7da67..8d55f526 100644--- a/tests/test_issue1127_preprocess_cache_key_fields.py+++ b/tests/test_issue1127_preprocess_cache_key_fields.py@@ -221,9 +221,9 @@ class TestGateRefusesACacheBuiltUnderAnotherSetting:class TestEveryGateCallerForwardsTheTask:def test_each_call_site_passes_task(self):- """The gate defaults to ``sft``, so a caller that drops ``task`` keys a- pretrain run as sft and refuses every cache ``soup data preprocess``- wrote for it."""+ """A caller has to name ``task`` (keyword-only, no default since #1272),+ and it has to be the run's own: keying a pretrain run as sft refuses every+ cache ``soup data preprocess`` wrote for it."""import astfrom pathlib import Pathdiff --git a/tests/test_issue1272_cache_refusal_reason.py b/tests/test_issue1272_cache_refusal_reason.pynew file mode 100644index 00000000..607fdb76--- /dev/null+++ b/tests/test_issue1272_cache_refusal_reason.py@@ -0,0 +1,184 @@+"""#1272: a refused ``pre_tokenized`` cache says why.++Since #1127 ten ``data`` fields fold into one hash, so a bare hash mismatch no+longer tells a user what changed. ``soup data preprocess`` now records the key+generation and the row-set inputs in ``metadata.json``, and the gate names either+the gap (a cache written before #1127) or the ``data`` fields that differ.+"""++from __future__ import annotations++import json++import pytest++from soup_cli.config.schema import DataConfig+from soup_cli.utils import data_pipeline as dp+from tests.test_issue1054_pretokenized_labels import _ROWS, _run_preprocess, _tokenizer+++def _cache(tmp_path, monkeypatch, data_extra=""):+ return _run_preprocess(+ tmp_path,+ monkeypatch,+ _tokenizer(),+ rows=[{"messages": _ROWS[0]}],+ data_extra=data_extra,+ )+++def _refusal(cache_dir, tmp_path, **data) -> str:+ from rich.console import Console++ from soup_cli.trainer.sft import _maybe_load_pretokenized++ dcfg = DataConfig(+ train="./d.jsonl",+ format="pre_tokenized",+ tokenized_path=str(cache_dir.relative_to(tmp_path)),+ max_length=128,+ **data,+ )+ with pytest.raises(ValueError, match="cache hash mismatch") as exc:+ _maybe_load_pretokenized(dcfg, "x/y", Console(), None, task="sft")+ return str(exc.value)+++class TestMetadataRecordsTheKey:+ def test_key_schema_and_dataset_key_are_written(self, tmp_path, monkeypatch):+ cache_dir = _cache(tmp_path, monkeypatch, data_extra=" val_split: 0.2\n")+ meta = json.loads((cache_dir / "metadata.json").read_text(encoding="utf-8"))++ assert meta["key_schema"] == dp._PREPROCESS_TOKENIZE_SCHEMA+ assert meta["dataset_key"]["val_split"] == 0.2+ assert set(meta["dataset_key"]) == set(dp._DATASET_KEY_FIELDS)+++class TestTheRefusalSaysWhy:+ def test_a_v6_cache_names_the_row_set_keying(self, tmp_path, monkeypatch):+ """A v6 cache has ``chat_template`` and ``mask_mode`` but no ``key_schema``."""+ cache_dir = _cache(tmp_path, monkeypatch)+ meta_path = cache_dir / "metadata.json"+ meta = json.loads(meta_path.read_text(encoding="utf-8"))+ meta.pop("key_schema")+ meta.pop("dataset_key")+ meta["cache_key"] = "0" * 16 # v6 hashed fewer inputs+ meta_path.write_text(json.dumps(meta), encoding="utf-8")++ message = _refusal(cache_dir, tmp_path)++ assert "predates row-set keying (#1127)" in message+ assert "data.val_split" not in message++ def test_a_different_val_split_is_named(self, tmp_path, monkeypatch):+ cache_dir = _cache(tmp_path, monkeypatch)++ message = _refusal(cache_dir, tmp_path, val_split=0.2)++ assert "the cache was built with a different data.val_split;" in message+ assert "predates" not in message++ def test_every_differing_field_is_named_in_table_order(self, tmp_path, monkeypatch):+ cache_dir = _cache(tmp_path, monkeypatch)++ message = _refusal(cache_dir, tmp_path, audio_dir="./audio", val_split=0.2)++ assert "a different data.val_split, data.audio_dir;" in message++ def test_a_mismatch_outside_the_row_set_names_no_field(self, tmp_path, monkeypatch):+ """``max_length`` is keyed but is not a row-set input, so the message adds+ nothing it cannot back up."""+ cache_dir = _cache(tmp_path, monkeypatch)+ from rich.console import Console++ from soup_cli.trainer.sft import _maybe_load_pretokenized++ dcfg = DataConfig(+ train="./d.jsonl",+ format="pre_tokenized",+ tokenized_path=str(cache_dir.relative_to(tmp_path)),+ max_length=256,+ )+ with pytest.raises(ValueError, match="cache hash mismatch") as exc:+ _maybe_load_pretokenized(dcfg, "x/y", Console(), None, task="sft")++ assert "predates" not in str(exc.value)+ assert "built with a different" not in str(exc.value)+++class TestDatasetKeyDiff:+ def test_same_inputs_differ_in_nothing(self):+ current = dp.preprocess_dataset_key_input(DataConfig(train="./d.jsonl"))+ assert dp.preprocess_dataset_key_diff(json.loads(current), current) == []++ @pytest.mark.parametrize("stored", ["edited", None])+ def test_a_stored_value_that_is_not_a_dict_names_nothing(self, stored):+ """A hand-edited ``dataset_key`` cannot say what changed, so no field is named."""+ current = dp.preprocess_dataset_key_input(DataConfig(train="./d.jsonl"))+ assert dp.preprocess_dataset_key_diff(stored, current) == []+++class TestTheGateNeedsATask:+ def test_task_has_no_default(self):+ """A forgotten caller is a TypeError, not a silently wrong key."""+ import inspect++ from soup_cli.trainer.sft import _maybe_load_pretokenized++ param = inspect.signature(_maybe_load_pretokenized).parameters["task"]+ assert param.kind is inspect.Parameter.KEYWORD_ONLY+ assert param.default is inspect.Parameter.empty+++class TestExclusionReasonsDescribeTheCode:+ @pytest.mark.parametrize(+ "field",+ [+ "eval_on_each_dataset",+ "image_min_pixels",+ "image_max_pixels",+ "image_resize_algorithm",+ "video_fps",+ "video_maxlen",+ ],+ )+ def test_staged_fields_say_nothing_reads_them(self, field):+ from soup_cli.config.staged_fields import STAGED_FIELDS++ assert ("data", field) in STAGED_FIELDS, field+ assert "no runtime code reads it" in dp.NOT_PREPROCESS_KEY_FIELDS[field]++ def test_remove_unused_columns_says_no_trainer_reads_it(self):+ assert "no trainer reads it" in dp.NOT_PREPROCESS_KEY_FIELDS["remove_unused_columns"]++ def test_remove_unused_columns_is_still_unconsumed(self):+ from tests.test_issue748_config_fields_reach_a_consumer import KNOWN_UNCONSUMED++ assert "data.remove_unused_columns" in KNOWN_UNCONSUMED+++class TestTheOldestGapStillWins:+ @pytest.mark.parametrize(+ ("dropped", "expected"),+ [+ (("mask_mode",), "predates loss-mask keying (#1054)"),+ (("mask_mode", "chat_template"), "predates chat_template keying (#1067)"),+ ],+ )+ def test_an_older_cache_names_its_own_gap(+ self, tmp_path, monkeypatch, dropped, expected+ ):+ """A real v5 or v4 cache has no ``key_schema`` or ``dataset_key`` either,+ so it predates #1127 too; the oldest gap is the one named."""+ cache_dir = _cache(tmp_path, monkeypatch)+ meta_path = cache_dir / "metadata.json"+ meta = json.loads(meta_path.read_text(encoding="utf-8"))+ for field in ("key_schema", "dataset_key", *dropped):+ meta.pop(field)+ meta["cache_key"] = "0" * 16+ meta_path.write_text(json.dumps(meta), encoding="utf-8")++ message = _refusal(cache_dir, tmp_path)++ assert expected in message+ assert "#1127" not in messagediff --git a/tests/test_v0537.py b/tests/test_v0537.pyindex 86ae1838..2e3be2eb 100644--- a/tests/test_v0537.py+++ b/tests/test_v0537.py@@ -2084,7 +2084,7 @@ class TestSftPretrainPreTokenizedShortCircuit:from soup_cli.trainer.sft import _maybe_load_pretokenizedcaptured = MagicMock()- result = _maybe_load_pretokenized(cfg.data, cfg.base, captured)+ result = _maybe_load_pretokenized(cfg.data, cfg.base, captured, task="sft")assert result is not Nonetrain_ds, eval_ds = resultassert len(train_ds) == 2@@ -2152,7 +2152,7 @@ class TestSftPretrainPreTokenizedShortCircuit:from soup_cli.trainer.sft import _maybe_load_pretokenizedwith pytest.raises(ValueError, match="cache hash mismatch"):- _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock())+ _maybe_load_pretokenized(cfg.data, cfg.base, MagicMock(), task="sft")def test_missing_metadata_proceeds_with_yellow_advisory(self, tmp_path, monkeypatch,@@ -2171,7 +2171,7 @@ class TestSftPretrainPreTokenizedShortCircuit:from soup_cli.trainer.sft import _maybe_load_pretokenizedcaptured = MagicMock()- result = _maybe_load_pretokenized(cfg.data, cfg.base, captured)+ result = _maybe_load_pretokenized(cfg.data, cfg.base, captured, task="sft")assert result is not Nonetrain_ds, _ = resultassert len(train_ds) == 2