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
test(config): name the refused and alias categories, and check every shipped config (#1948)
ndablizov3a83639fbec5
diff --git a/tests/test_issue748_config_fields_reach_a_consumer.py b/tests/test_issue748_config_fields_reach_a_consumer.pyindex a57a588d..af119322 100644--- a/tests/test_issue748_config_fields_reach_a_consumer.py+++ b/tests/test_issue748_config_fields_reach_a_consumer.py@@ -382,23 +382,15 @@ KNOWN_UNCONSUMED = {"HF argument pass False so a custom collator still sees ""the extra columns. The default is now False, and an ""explicit true loads with a warning and is ignored",- # -- declared and deliberately REFUSED, so having no consumer is correct.- # A distinct category from the two below: the user is told, loudly, at- # config load. Found by this guard rather than by hand.- "training.packing_cross_doc_attn_mask": "no issue needed: rejected at config load "- "(schema.py:3495) because it never "- "mapped to a valid TRL packing_strategy; "- "documented at docs/performance-and-"- "quantization.md:153",+ # training.packing_cross_doc_attn_mask moved to REFUSED_AT_LOAD (#1814).# -- staged for features that have not landed; grouped so they can be# retired together rather than one at a time."training.long_context_grpo": "#808 -- warns at load from v0.76, refused as of v0.77 ""(documented as wiring Tiled MLP; no Tiled MLP exists)","training.vision_grpo": "#808 -- warns at load from v0.76, refused as of v0.77 ""(no vision GRPO path)",- "training.load_in_16bit": "no issue needed: schema rewrites quantization at validation time",- "training.unsloth_bnb_4bit": "no issue needed: schema assertion alias",- "training.llm_int8": "no issue needed: schema assertion alias",+ # training.load_in_16bit / unsloth_bnb_4bit / llm_int8 moved to+ # VALIDATOR_ALIASES (#1814)."training.quantize_ref_model": "#808 -- warns at load from v0.76, refused as of v0.77 ""(reference-model quantisation staging)","training.convergence_window": "#808 -- warns at load from v0.76, refused as of v0.77 "@@ -450,6 +442,51 @@ KNOWN_UNCONSUMED = {}+# --------------------------------------------------------------------------+# #1814 -- fields whose only reader is a schema validator. They are not silently+# inert, so they do not belong in KNOWN_UNCONSUMED (whose pin should count only+# fields a user can set to no effect and no word). Each entry names the validator+# that consumes it, and TestTheNamedCategoriesAreTrue checks the behaviour, so an+# entry cannot outlive the validator that justifies it.+# --------------------------------------------------------------------------++#: Declared and refused at config load: setting the field stops the load with a+#: message naming it, which is the strongest kind of "the user is told".+REFUSED_AT_LOAD = {+ "training.packing_cross_doc_attn_mask": (+ "TrainingConfig._validate_cross_doc_attn_mask",+ "#1814 -- refused at config load: it never mapped to a valid TRL "+ "packing_strategy (documented in docs/performance-and-quantization.md)",+ ),+}++#: Aliases a validator consumes: it rewrites another field from them, or asserts+#: that the field they describe is set to match, and refuses the config if not.+VALIDATOR_ALIASES = {+ "training.load_in_16bit": (+ "TrainingConfig._validate_load_in_aliases",+ "#1814 -- rewrites training.quantization to 'none' (and refuses it beside "+ "load_in_8bit or a Quant Menu format)",+ ),+ "training.llm_int8": (+ "SoupConfig._validate_llm_int8_alias",+ "#1814 -- asserts training.quantization == '8bit' and refuses the config otherwise",+ ),+ "training.unsloth_bnb_4bit": (+ "SoupConfig._validate_unsloth_bnb_4bit_compat",+ "#1814 -- asserts backend 'unsloth' and quantization '4bit' and refuses the "+ "config otherwise",+ ),+}++#: Every field the orphan check lets through, with its reason.+GUARDED = {+ **KNOWN_UNCONSUMED,+ **{key: reason for key, (_, reason) in REFUSED_AT_LOAD.items()},+ **{key: reason for key, (_, reason) in VALIDATOR_ALIASES.items()},+}++def describe_tree_mismatch(imported: pathlib.Path, scanned: pathlib.Path):"""Return a message if these are different trees, else None.@@ -602,7 +639,7 @@ class TestEveryDeclaredFieldReachesAConsumer:keyfor key, attr in _declared().items()if not field_reaches_a_consumer(key, attr, consumed)- and key not in KNOWN_UNCONSUMED+ and key not in GUARDED)assert not orphans, ("These config fields are declared in schema.py and read by no "@@ -616,9 +653,10 @@ class TestEveryDeclaredFieldReachesAConsumer:"""A renamed or deleted field must not keep a stale entry alive --otherwise the allowlist silently stops guarding anything."""declared = _declared()- stale = sorted(k for k in KNOWN_UNCONSUMED if k not in declared)+ stale = sorted(k for k in GUARDED if k not in declared)assert not stale, (- "KNOWN_UNCONSUMED names fields that no longer exist; remove them:\n "+ "KNOWN_UNCONSUMED / REFUSED_AT_LOAD / VALIDATOR_ALIASES name fields that no "+ "longer exist; remove them:\n "+ "\n ".join(stale))@@ -628,16 +666,16 @@ class TestEveryDeclaredFieldReachesAConsumer:consumed = _consumed_in_src()declared = _declared()now_wired = sorted(- k for k in KNOWN_UNCONSUMED+ k for k in GUARDEDif k in declared and field_reaches_a_consumer(k, declared[k], consumed))assert not now_wired, (- "These fields now have a consumer, so their KNOWN_UNCONSUMED entry "+ "These fields now have a consumer, so their allowlist entry ""is obsolete and must be deleted:\n " + "\n ".join(now_wired))def test_every_allowlist_entry_carries_a_reason(self):- empty = sorted(k for k, v in KNOWN_UNCONSUMED.items() if not v or len(v) < 10)+ empty = sorted(k for k, v in GUARDED.items() if not v or len(v) < 10)assert not empty, f"allowlist entries need a reason: {empty}"def test_the_guard_can_actually_fail(self, tmp_path, monkeypatch):@@ -657,7 +695,7 @@ class TestEveryDeclaredFieldReachesAConsumer:orphans = [key for key, attr in _declared().items()if not field_reaches_a_consumer(key, attr, consumed)- and key not in KNOWN_UNCONSUMED+ and key not in GUARDED]assert "training.totally_unwired_probe" in orphans, (f"the guard did not flag an unwired field; it reported {orphans}. "@@ -674,7 +712,7 @@ class TestEveryDeclaredFieldReachesAConsumer:assert not [key for key, attr in _declared().items()if not field_reaches_a_consumer(key, attr, consumed_after)- and key not in KNOWN_UNCONSUMED+ and key not in GUARDED]def test_removing_a_fields_last_consumer_is_caught(self, tmp_path):@@ -711,14 +749,68 @@ def test_the_allowlist_size_is_pinned_exactly():half: it names WHICH entry went stale, where this one only says the countmoved."""- assert len(KNOWN_UNCONSUMED) == 36, (- f"KNOWN_UNCONSUMED is {len(KNOWN_UNCONSUMED)}, pinned at 36. Going UP "+ assert len(KNOWN_UNCONSUMED) == 32, (+ f"KNOWN_UNCONSUMED is {len(KNOWN_UNCONSUMED)}, pinned at 32. Going UP ""means a field was allowlisted rather than wired; going DOWN means an ""entry was retired, which is the good direction -- lower this number ""in the same commit.")+def test_the_named_categories_are_pinned_exactly():+ """The same two-way ratchet for the #1814 categories: an entry added to one of+ them is a reviewed decision, not a way around the KNOWN_UNCONSUMED pin."""+ assert (len(REFUSED_AT_LOAD), len(VALIDATOR_ALIASES)) == (1, 3), (+ f"REFUSED_AT_LOAD is {len(REFUSED_AT_LOAD)} and VALIDATOR_ALIASES is "+ f"{len(VALIDATOR_ALIASES)}, pinned at 1 and 3; change the pin in the same commit."+ )+ assert not (set(REFUSED_AT_LOAD) | set(VALIDATOR_ALIASES)) & set(KNOWN_UNCONSUMED)+ assert not set(REFUSED_AT_LOAD) & set(VALIDATOR_ALIASES)+++class TestTheNamedCategoriesAreTrue:+ """#1814 -- each category entry is checked, not trusted: the named validator+ exists, and setting the field has the effect the entry claims. Deleting the+ validator, or the check inside it, turns these red."""++ _BASE = "base: org/m\ntask: sft\ndata:\n train: d.jsonl\n"++ def _load(self, extra: str, backend: str = ""):+ from soup_cli.config.loader import load_config_from_string++ text = self._BASE + (f"backend: {backend}\n" if backend else "") + extra+ return load_config_from_string(text)++ @pytest.mark.parametrize("key", sorted({**REFUSED_AT_LOAD, **VALIDATOR_ALIASES}))+ def test_the_named_validator_exists(self, key):+ from soup_cli.config import schema++ qualname = {**REFUSED_AT_LOAD, **VALIDATOR_ALIASES}[key][0]+ cls_name, method = qualname.split(".")+ assert callable(getattr(getattr(schema, cls_name), method, None)), qualname++ def test_packing_cross_doc_attn_mask_is_refused_by_name(self):+ with pytest.raises(ValueError, match="packing_cross_doc_attn_mask"):+ self._load("training:\n packing_cross_doc_attn_mask: true\n")++ def test_load_in_16bit_rewrites_quantization(self):+ cfg = self._load("training:\n quantization: 4bit\n load_in_16bit: true\n")+ assert cfg.training.quantization == "none"++ def test_llm_int8_asserts_8bit(self):+ with pytest.raises(ValueError, match="llm_int8"):+ self._load("training:\n quantization: 4bit\n llm_int8: true\n")+ cfg = self._load("training:\n quantization: 8bit\n llm_int8: true\n")+ assert cfg.training.llm_int8 is True++ def test_unsloth_bnb_4bit_asserts_backend_and_4bit(self):+ with pytest.raises(ValueError, match="unsloth"):+ self._load("training:\n quantization: 4bit\n unsloth_bnb_4bit: true\n")+ cfg = self._load("training:\n quantization: 4bit\n unsloth_bnb_4bit: true\n",+ backend="unsloth")+ assert cfg.training.unsloth_bnb_4bit is True++def _reason_is_accountable(reason: str) -> bool:"""A reason must cite an issue or say in words that none exists.@@ -759,7 +851,7 @@ def test_every_allowlist_entry_states_an_issue_or_says_there_is_none():# entry through carrying a wrong story. An entry must cite an issue or say# in words that none exists.vague = sorted(- k for k, v in KNOWN_UNCONSUMED.items()+ k for k, v in GUARDED.items()if not _reason_is_accountable(v))assert not vague, (diff --git a/tests/test_shipped_configs_set_no_inert_field.py b/tests/test_shipped_configs_set_no_inert_field.pynew file mode 100644index 00000000..d1a27744--- /dev/null+++ b/tests/test_shipped_configs_set_no_inert_field.py@@ -0,0 +1,101 @@+"""#1814 — no shipped recipe or template sets a field that does nothing.++An ad hoc check on the v0.76.0 tree loaded every recipe and found none that sets+a field in ``KNOWN_UNCONSUMED`` (the fields read by nothing), a staged field+(warned at load, refused at its deadline) or a deprecated value. This makes that+check a test, so a recipe cannot start shipping a setting that a user copying it+would get no effect from, or a warning they did not write.+"""++from __future__ import annotations++import warnings++import pytest+import yaml++from soup_cli.config.deprecation import SoupConfigDeprecationWarning+from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import SoupConfig, remap_root_level_misplaced_keys+from soup_cli.config.staged_fields import find_staged_config_fields+from soup_cli.recipes.catalog import RECIPES+from soup_cli.templates import list_templates, load_template+from tests.test_issue748_config_fields_reach_a_consumer import KNOWN_UNCONSUMED+++def _shipped() -> list[tuple[str, str]]:+ configs = [(f"recipe:{name}", meta.yaml_str) for name, meta in RECIPES.items()]+ configs += [(f"template:{name}", load_template(name)) for name in list_templates()]+ return configs+++def inert_fields_set(text: str) -> list[str]:+ """Every field ``text`` sets that is unconsumed, staged, or a deprecated value."""+ loaded = yaml.safe_load(text) or {}+ raw = remap_root_level_misplaced_keys(loaded)+ found = []+ for section in ("training", "data"):+ for name in (raw.get(section) or {}):+ if f"{section}.{name}" in KNOWN_UNCONSUMED:+ found.append(f"{section}.{name} (read by nothing)")+ config = load_config_from_string(text) # the shipped text must load at all+ # The loader turns deprecation warnings into console lines (#759), so they are+ # recorded here from the same construction it performs.+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ SoupConfig(**loaded)+ found += [f"{item.path} (staged)" for item in find_staged_config_fields(raw, config=config)]+ found += [+ f"deprecated value: {w.message}"+ for w in caught if issubclass(w.category, SoupConfigDeprecationWarning)+ ]+ return sorted(set(found))+++def test_the_catalog_is_not_empty():+ # A loop over nothing passes; the issue counted 170 recipes at v0.76.0.+ assert len(RECIPES) >= 170+ assert len(list_templates()) >= 10+++def test_the_enumeration_covers_both_catalogs_exactly():+ # #1948 review: the checks above read the catalogs, while the parametrized+ # test gets its cases from _shipped(). Pin that the two are the same set, so an+ # empty enumeration or a lost branch (recipes or templates) fails here by name.+ # There are no intentional exclusions.+ enumerated = [name for name, _ in _shipped()]+ expected = {f"recipe:{name}" for name in RECIPES} | {+ f"template:{name}" for name in list_templates()+ }+ assert enumerated, "the shipped-config enumeration is empty"+ assert len(enumerated) == len(set(enumerated)), "an id is enumerated twice"+ missing = sorted(expected - set(enumerated))+ extra = sorted(set(enumerated) - expected)+ assert not missing, f"shipped configs the test never checks: {missing[:10]}"+ assert not extra, f"enumerated ids that are not shipped configs: {extra[:10]}"+ assert all(text for _, text in _shipped()), "a shipped config enumerated with no text"++[email protected]("name,text", _shipped(), ids=[n for n, _ in _shipped()])+def test_a_shipped_config_sets_no_inert_field(name, text):+ assert inert_fields_set(text) == [], name+++class TestTheCheckCanFail:+ """Each of the three detectors, shown to fire on a config that trips it."""++ _BASE = "base: org/m\ntask: sft\ndata:\n train: d.jsonl\n"++ def test_an_unconsumed_field_is_named(self):+ text = self._BASE + "training:\n warmup_auto: true\n"+ assert "training.warmup_auto (read by nothing)" in inert_fields_set(text)++ def test_a_staged_field_is_named(self):+ text = self._BASE + "training:\n forgetting_stop: true\n"+ assert "training.forgetting_stop (staged)" in inert_fields_set(text)++ def test_a_deprecated_value_is_named(self):+ text = self._BASE.replace(" train: d.jsonl\n",+ " train: d.jsonl\n remove_unused_columns: true\n")+ found = inert_fields_set(text)+ assert any(item.startswith("deprecated value:") for item in found), found