Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(provenance): record run base revisions and artifact identities (#1972)

Nurkhan Esenbekbb11917c29fe
diff --git a/changelog.d/0.76.0/1972.added.md b/changelog.d/0.76.0/1972.added.md
new file mode 100644
index 00000000..7a5258ae
--- /dev/null
+++ b/changelog.d/0.76.0/1972.added.md
@@ -0,0 +1 @@
+- Record nullable run base revisions and portable final-artifact provenance, bind supported resident Transformers base loads to one Hub commit, preserve unknown/offline/legacy flows, and transfer historical identities into registry entries without re-reading training files; keep cache-path hints explicitly unverified and training-hash capture separate (#1902 by @kok-o in #1972).
diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.md
index 5dbd084d..a2cfb80d 100644
--- a/docs/adapters-and-governance.md
+++ b/docs/adapters-and-governance.md
@@ -306,7 +306,14 @@ soup registry promote llama31-chat-v1 --tag prod
soup registry delete llama31-chat-v1 --yes
```
-**Training data:** `push --data <file>` stores the file's SHA-256 as the entry's `data_hash`, shown by `soup registry show`. It records the file registered as the training input, not proof of what the run trained on. The file must be under the current directory; without `--data` the entry has no `data_hash`.
+**Training data:** `push --data <file>` stores the file's SHA-256 as the entry's `data_hash`, shown by `soup registry show`. It records the file registered as the training input, not proof of what the run trained on. The file must be under the current directory. Without `--data`, `register_from_run` copies a stored historical `training_data_sha256` without reopening today's path; legacy runs remain unknown. When both are present, the explicit file takes precedence for `data_hash`, while the separate historical `training_data_sha256` is retained. `entry_hash` binds the chosen data digest and any recorded base revision/source. Training-time hash capture itself remains #1764 part 2; reserving nullable storage does not claim the transformed examples consumed by training.
+
+**Base identity:** Registration copies the run's nullable base revision and its source;
+`soup registry show` exposes both. `hub_commit` identifies the commit passed to supported
+base loaders, while `cache_path` only describes the local directory name and does not
+verify local contents. The original human-readable base ID and config hash retain their
+existing meaning. Registrations with no known revision/hash retain their legacy entry
+fingerprint. Retries also compare the recorded revision/source and historical data hash.
**Retries:** `push --idempotency-key <key>` (or `RegistryStore.push(idempotency_key=...)`) makes a registration safe to repeat after a crash or a timeout. A later push with the same key writes nothing and returns the existing entry, provided it repeats that entry's name, base model, task, run, config and data hash and its tag is one of the entry's tags; anything else under the same key is refused with an error naming the entry. Notes are not compared. Two writers pushing the same key at once end up with one entry. A key is 1 to 128 characters from letters, digits, `.`, `_`, `:` and `-`; pushes without one behave as before. `RegistryStore.get_by_idempotency_key(key)` finds the entry. Deleting the entry frees its key.
diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.md
index 6d66768d..911129a1 100644
--- a/docs/backends-and-ops.md
+++ b/docs/backends-and-ops.md
@@ -681,6 +681,48 @@ A file over a limit is refused with a message naming the file and the limit (`so
Every `soup train` run is automatically tracked in a local SQLite database (`~/.soup/experiments.db`).
+### Recorded base identity
+
+For single-process resident Hugging Face loads on the Transformers backend, `soup train` resolves
+the base's commit once, immediately before its first model/tokenizer/processor/config
+load, and passes that commit to the run's subsequent base loads. The original `base`
+name stays in the config and experiments row; unrelated teacher, reward and scorer
+repositories do not receive its revision. `soup runs show` displays the revision and
+its source.
+
+The new nullable `runs.base_revision`, `runs.base_revision_source` and
+`runs.training_data_sha256` columns upgrade existing databases in place. Historical
+rows stay unknown; Soup never fills them from today's Hub state or dataset bytes.
+Training-data hash capture remains separate work (#1764 part 2); this change reserves
+its storage/transfer contract without hashing training inputs.
+
+An unavailable/offline Hub metadata lookup preserves the existing load flow and
+records an unknown revision. A local `snapshots/<40-hex>` directory records
+`base_revision_source: cache_path`: this is a hint derived from the directory name,
+**not proof that its local bytes match the Hub commit**. Other local directories
+also have unknown content identity. There is no new config field or new default
+offline, legacy-export or `--base` refusal.
+
+The saving rank writes `soup_run.json` beside the final training artifact, containing
+the schema version, run ID, original base ID, nullable revision/source and nullable
+training-data hash. Keep that file when copying an adapter. Shared live-eval loading
+and GGUF's adapter-merge path can then reuse a matching recorded Hub commit without
+access to the original experiments database. An explicit different base or missing,
+malformed or future-version metadata keeps the existing flow, without guessing a
+historical commit. This metadata is provenance, not a signed integrity attestation.
+Loading a local adapter folder directly also reuses that commit when its
+`adapter_config.json` names the same base and has no conflicting explicit revision;
+the tokenizer still comes from the adapter folder.
+
+**First-stage boundaries:** Non-HF hubs, Unsloth, MLX, layer-streaming and distributed loads remain unbound and
+are recorded as such; a cache-path hint on any backend is still unverified. Standalone
+wrapper/sweep invocations do not automatically establish a run scope. Metadata is
+written for the final artifact, not each intermediate checkpoint. Other exporters
+(including ONNX/TensorRT and native AWQ/GPTQ/torchao loaders), remote adapter sidecars
+and independent teacher/reward/scorer repositories do not gain a binding guarantee.
+Evaluation engines that bypass the shared live-eval loader (including lm-eval's
+adapter benchmark path and vLLM) also remain unbound in this stage.
+
```bash
# List all training runs
soup runs
diff --git a/src/soup_cli/commands/export.py b/src/soup_cli/commands/export.py
index a33b6387..5d5a967c 100644
--- a/src/soup_cli/commands/export.py
+++ b/src/soup_cli/commands/export.py
@@ -535,11 +535,19 @@ def _merge_adapter(
)
console.print(f"[dim]Loading base model: {for_terminal(base_model)}...[/]")
+ from soup_cli.utils.run_provenance import recorded_base_kwargs
+
+ revision_kwargs = recorded_base_kwargs(adapter_path, base_model)
+ if revision_kwargs:
+ console.print(f"[dim]Base revision: {revision_kwargs['revision']} (recorded run)[/]")
+ else:
+ console.print("[dim]Base revision: unknown (legacy, local source or base override)[/]")
model = AutoModelForCausalLM.from_pretrained(
base_model,
torch_dtype=torch.float16,
trust_remote_code=trc,
device_map="cpu",
+ **revision_kwargs,
)
console.print(f"[dim]Loading LoRA adapter: {adapter_path}...[/]")
diff --git a/src/soup_cli/commands/registry.py b/src/soup_cli/commands/registry.py
index 8f224449..ecc45f09 100644
--- a/src/soup_cli/commands/registry.py
+++ b/src/soup_cli/commands/registry.py
@@ -189,6 +189,9 @@ def show_cmd(
("name", entry["name"]),
("tags", ", ".join(entry.get("tags", []))),
("base_model", entry["base_model"]),
+ ("base_revision", entry.get("base_revision") or "unknown"),
+ ("base_revision_source", entry.get("base_revision_source") or "unknown"),
+ ("training_data_sha256", entry.get("training_data_sha256") or "unknown"),
("task", entry["task"]),
("run_id", entry.get("run_id") or "-"),
("entry_hash", entry.get("entry_hash", "")[:16] + "..."),
diff --git a/src/soup_cli/commands/runs.py b/src/soup_cli/commands/runs.py
index 4a040819..a800720e 100644
--- a/src/soup_cli/commands/runs.py
+++ b/src/soup_cli/commands/runs.py
@@ -200,6 +200,8 @@ def show(
info_lines.extend([
"",
f"Model: [bold]{_esc(str(run.get('base_model') or '-'))}[/]",
+ f"Revision: {for_terminal(run.get('base_revision') or 'unknown')}",
+ f"Identity: {for_terminal(run.get('base_revision_source') or 'unknown')}",
f"Task: {_esc(str(run.get('task') or '-'))}",
f"Device: {_esc(str(run.get('device_name') or '-'))} "
f"({_esc(str(run.get('device') or '-'))})",
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 1f58396f..ec535c28 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1777,6 +1777,7 @@ def train(
from soup_cli.experiment.tracker import ExperimentTracker
tracker = ExperimentTracker()
+ run_base = cfg.base
experiment_name = cfg.experiment_name or name
run_id = tracker.start_run(
config_dict=cfg.model_dump(),
@@ -1878,9 +1879,26 @@ def train(
# to keep separate chains and sweep's copy fell ten tasks and the MLX
# route behind. See soup_cli/trainer/dispatch.py.
from soup_cli.trainer.dispatch import build_trainer
+ from soup_cli.utils.launcher import is_in_distributed
+ from soup_cli.utils.run_provenance import BaseRevision, base_revision_scope
- trainer_wrapper = build_trainer(cfg, **trainer_kwargs)
- trainer_wrapper.setup(dataset)
+ base_identity = BaseRevision(
+ run_base,
+ binding_supported=(cfg.backend == "transformers" and hub_name == "hf"
+ and not cfg.training.stream_layers and not is_in_distributed()),
+ )
+ with base_revision_scope(base_identity):
+ trainer_wrapper = build_trainer(cfg, **trainer_kwargs)
+ trainer_wrapper.setup(dataset)
+ tracker.record_base_revision(
+ run_id, revision=base_identity.revision, source=base_identity.source,
+ )
+ if base_identity.source == "hub_commit":
+ console.print(f"[dim]Base revision: {base_identity.revision} (bound Hub commit)[/]")
+ elif base_identity.source == "cache_path":
+ console.print("[dim]Base revision: cache-path metadata; local bytes are unverified[/]")
+ else:
+ console.print("[dim]Base revision: unknown (existing loading behavior preserved)[/]")
# #350 — PEFT promotes newly-created adapters to fp32. FSDP cannot flatten
# those beside bf16/float16 BNB storage, so align every trainable floating
@@ -1963,7 +1981,7 @@ def train(
raise
try:
- with profiler_ctx as profiler, energy_ctx:
+ with profiler_ctx as profiler, energy_ctx, base_revision_scope(base_identity):
if profile_run and profiler is not None:
from soup_cli.utils.profiling import attach_profile_callback
@@ -1977,6 +1995,19 @@ def train(
resume_from_checkpoint=resume_from,
)
+ from soup_cli.utils.run_provenance import write_run_provenance
+
+ tracker.record_base_revision(
+ run_id, revision=base_identity.revision, source=base_identity.source,
+ )
+ # Only the saving rank writes portable metadata beside the final artifact.
+ if _should_run_diagnose_gate_on_rank():
+ metadata = base_identity.metadata(run_id)
+ recorded_run = tracker.get_run(run_id)
+ if isinstance(recorded_run, dict):
+ metadata["training_data_sha256"] = recorded_run.get("training_data_sha256")
+ write_run_provenance(result["output_dir"], metadata)
+
# Save completion to tracker
tracker.finish_run(
run_id=run_id,
diff --git a/src/soup_cli/experiment/tracker.py b/src/soup_cli/experiment/tracker.py
index 359c20f4..dbade4c0 100644
--- a/src/soup_cli/experiment/tracker.py
+++ b/src/soup_cli/experiment/tracker.py
@@ -61,6 +61,9 @@ CREATE TABLE IF NOT EXISTS runs (
duration_secs REAL,
output_dir TEXT,
base_model TEXT,
+ base_revision TEXT,
+ base_revision_source TEXT,
+ training_data_sha256 TEXT,
task TEXT,
cost_usd REAL,
cost_gpu_label TEXT,
@@ -165,7 +168,7 @@ class ExperimentTracker:
def _ensure_schema(self) -> None:
"""Create tables if they don't exist.
- Lazy migration adds the v0.34.0 cost columns and the ``val_loss``
+ Lazy migration adds nullable run provenance, the v0.34.0 cost columns and ``val_loss``
metrics column to legacy DBs -- ``~/.soup/experiments.db`` exists on
every machine that has ever run ``soup train``, so the schema is
upgraded in place rather than assumed. Each column is gated on its own
@@ -178,6 +181,11 @@ class ExperimentTracker:
conn = self._get_conn()
conn.executescript(_SCHEMA_SQL)
for table, column, ddl in (
+ ("runs", "base_revision", "ALTER TABLE runs ADD COLUMN base_revision TEXT"),
+ ("runs", "base_revision_source",
+ "ALTER TABLE runs ADD COLUMN base_revision_source TEXT"),
+ ("runs", "training_data_sha256",
+ "ALTER TABLE runs ADD COLUMN training_data_sha256 TEXT"),
("runs", "cost_usd", "ALTER TABLE runs ADD COLUMN cost_usd REAL"),
("runs", "cost_gpu_label", "ALTER TABLE runs ADD COLUMN cost_gpu_label TEXT"),
("runs", "run_kind",
@@ -238,7 +246,8 @@ class ExperimentTracker:
if existing is not None:
conn.execute(
"""UPDATE runs SET status = 'running', config_json = ?, device = ?,
- device_name = ?, gpu_memory = ?, experiment_name = ?, base_model = ?, task = ?
+ device_name = ?, gpu_memory = ?, experiment_name = ?, base_model = ?, task = ?,
+ base_revision = NULL, base_revision_source = NULL, training_data_sha256 = NULL
WHERE run_id = ?""",
(
config_json, device, device_name, gpu_memory, experiment_name, base_model, task,
@@ -260,6 +269,20 @@ class ExperimentTracker:
conn.commit()
return run_id
+ def record_base_revision(
+ self, run_id: str, *, revision: Optional[str], source: str,
+ ) -> None:
+ """Store the current execution's identity, never backfill historical rows."""
+ from soup_cli.utils.run_provenance import validate_identity
+
+ validate_identity(revision, source)
+ conn = self._get_conn()
+ conn.execute(
+ "UPDATE runs SET base_revision=?, base_revision_source=? WHERE run_id=?",
+ (revision, source, run_id),
+ )
+ conn.commit()
+
def launch_run(
self,
*,
diff --git a/src/soup_cli/registry/hashing.py b/src/soup_cli/registry/hashing.py
index 1cd1e92a..bc98317d 100644
--- a/src/soup_cli/registry/hashing.py
+++ b/src/soup_cli/registry/hashing.py
@@ -48,18 +48,33 @@ def hash_entry(
config: dict,
data_path: Optional[str],
base_model: str,
+ data_sha256: Optional[str] = None,
+ base_revision: Optional[str] = None,
+ base_revision_source: Optional[str] = None,
) -> str:
"""SHA-256 combining config, data file, and base model name.
The data file is hashed by content (not path) so moving files doesn't
- invalidate hashes. If ``data_path`` is ``None`` the field is omitted
- from the hash input. An empty string is NOT treated as ``None`` — it
+ invalidate hashes. If neither a path nor a historical digest is given,
+ the data field is omitted. An empty string is NOT treated as ``None`` — it
is passed through to :func:`hash_file`, which will raise.
+ ``data_sha256`` transfers a historical digest without re-reading its path;
+ an explicit ``data_path`` takes precedence. A known revision and its source
+ are included, while unknown identities preserve the legacy fingerprint.
"""
+ from soup_cli.utils.run_provenance import validate_identity, validate_training_hash
+
+ validate_training_hash(data_sha256)
+ validate_identity(base_revision, base_revision_source)
parts: dict[str, Any] = {
"config": _canonical_json(config),
"base_model": base_model,
}
if data_path is not None:
parts["data_sha256"] = hash_file(data_path)
+ elif data_sha256 is not None:
+ parts["data_sha256"] = data_sha256
+ if base_revision is not None:
+ parts["base_revision"] = base_revision
+ parts["base_revision_source"] = base_revision_source
return hash_config(parts)
diff --git a/src/soup_cli/registry/store.py b/src/soup_cli/registry/store.py
index c2003bbe..e09fa932 100644
--- a/src/soup_cli/registry/store.py
+++ b/src/soup_cli/registry/store.py
@@ -77,7 +77,10 @@ _IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
# What a retry under the same idempotency key has to repeat. ``notes`` is free-form and
# not compared; the tag only has to be one of the entry's tags.
-_IDEMPOTENT_FIELDS = ("name", "base_model", "task", "run_id", "config_hash", "data_hash")
+_IDEMPOTENT_FIELDS = (
+ "name", "base_model", "task", "run_id", "config_hash", "data_hash",
+ "base_revision", "base_revision_source", "training_data_sha256",
+)
_SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS registry_entries (
@@ -89,6 +92,9 @@ CREATE TABLE IF NOT EXISTS registry_entries (
config_json TEXT NOT NULL,
config_hash TEXT NOT NULL,
data_hash TEXT,
+ base_revision TEXT,
+ base_revision_source TEXT,
+ training_data_sha256 TEXT,
entry_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
notes TEXT,
@@ -262,9 +268,13 @@ class RegistryStore:
columns = {
row[1] for row in conn.execute("PRAGMA table_info(registry_entries)").fetchall()
}
- if "idempotency_key" not in columns:
+ for column in (
+ "idempotency_key", "base_revision", "base_revision_source", "training_data_sha256",
+ ):
+ if column in columns:
+ continue
try:
- conn.execute("ALTER TABLE registry_entries ADD COLUMN idempotency_key TEXT")
+ conn.execute(f"ALTER TABLE registry_entries ADD COLUMN {column} TEXT")
except sqlite3.OperationalError as exc:
if "duplicate column" not in str(exc).lower():
raise
@@ -309,6 +319,9 @@ class RegistryStore:
data_path: Optional[str] = None,
notes: Optional[str] = None,
idempotency_key: Optional[str] = None,
+ base_revision: Optional[str] = None,
+ base_revision_source: Optional[str] = None,
+ training_data_sha256: Optional[str] = None,
) -> str:
"""Create a new registry entry. Returns the new entry's id.
@@ -326,17 +339,24 @@ class RegistryStore:
if idempotency_key is not None:
validate_idempotency_key(idempotency_key)
+ from soup_cli.utils.run_provenance import validate_identity, validate_training_hash
+
+ validate_identity(base_revision, base_revision_source)
+ validate_training_hash(training_data_sha256)
entry_id = _generate_entry_id()
now = datetime.now().isoformat()
config_hash = hash_config(config)
- data_hash = hash_file(data_path) if data_path is not None else None
+ data_hash = hash_file(data_path) if data_path is not None else training_data_sha256
entry_hash = hash_entry(
- config=config, data_path=data_path, base_model=base_model,
+ config=config, data_path=None, base_model=base_model, data_sha256=data_hash,
+ base_revision=base_revision, base_revision_source=base_revision_source,
)
request = {
"name": name, "base_model": base_model, "task": task, "run_id": run_id,
"config_hash": config_hash, "data_hash": data_hash,
+ "base_revision": base_revision, "base_revision_source": base_revision_source,
+ "training_data_sha256": training_data_sha256,
}
if idempotency_key is not None:
@@ -350,13 +370,14 @@ class RegistryStore:
"""INSERT INTO registry_entries
(id, name, base_model, task, run_id, config_json,
config_hash, data_hash, entry_hash, created_at, notes,
- idempotency_key)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ idempotency_key, base_revision, base_revision_source, training_data_sha256)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
entry_id, name, base_model, task, run_id,
json.dumps(config, default=str, sort_keys=True),
config_hash, data_hash, entry_hash, now, notes,
idempotency_key,
+ base_revision, base_revision_source, training_data_sha256,
),
)
conn.execute(
@@ -786,7 +807,10 @@ class RegistryStore:
``data_path`` names the file to record as the run's training input; its
SHA-256 becomes ``data_hash``. It is what the caller says was trained on,
- not proof of it. Without it, ``data_hash`` stays ``None``.
+ not proof of it. Without it, a historical ``training_data_sha256`` is
+ copied without reopening today's data file (legacy runs remain unknown).
+ With it, the explicit file takes precedence for ``data_hash`` while the
+ separate historical field is retained. ``entry_hash`` binds that choice.
``idempotency_key`` is passed to :meth:`push`.
"""
run = tracker.get_run(run_id)
@@ -813,6 +837,9 @@ class RegistryStore:
data_path=data_path,
notes=notes,
idempotency_key=idempotency_key,
+ base_revision=run.get("base_revision"),
+ base_revision_source=run.get("base_revision_source"),
+ training_data_sha256=run.get("training_data_sha256"),
)
def get_eval_results(self, entry_id: str) -> list[dict]:
diff --git a/src/soup_cli/trainer/asr.py b/src/soup_cli/trainer/asr.py
index e64e206b..c809295b 100644
--- a/src/soup_cli/trainer/asr.py
+++ b/src/soup_cli/trainer/asr.py
@@ -33,6 +33,7 @@ from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -123,7 +124,10 @@ def _load_autoconfig(base: str, trust_remote_code: bool) -> Any:
"""Load ``AutoConfig`` for ``base`` (isolated for test monkeypatching)."""
from transformers import AutoConfig
- return AutoConfig.from_pretrained(base, trust_remote_code=trust_remote_code)
+ return AutoConfig.from_pretrained(
+ base, trust_remote_code=trust_remote_code,
+ **base_revision_kwargs(base),
+ )
def _require_whisper_base(base: str, trust_remote_code: bool) -> Any:
@@ -203,7 +207,8 @@ class AsrTrainerWrapper:
console.print(f"[dim]Loading Whisper processor: {cfg.base}[/]")
self.processor = WhisperProcessor.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
# For fine-tuning, the decoder prefix (language / task) is baked into
# the tokenized labels; forced_decoder_ids must be cleared so training
@@ -220,7 +225,8 @@ class AsrTrainerWrapper:
console.print(f"[dim]Loading Whisper model: {cfg.base}[/]")
self.model = WhisperForConditionalGeneration.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
self.model.config.forced_decoder_ids = None
self.model.config.suppress_tokens = []
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index 9262fdda..2b6198cf 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -33,6 +33,7 @@ if TYPE_CHECKING:
from soup_cli.config.schema import TrainingConfig # noqa: F401
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
console = Console()
@@ -274,7 +275,8 @@ class BCOTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -295,7 +297,10 @@ class BCOTrainerWrapper:
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/classifier.py b/src/soup_cli/trainer/classifier.py
index c6277070..4b021975 100644
--- a/src/soup_cli/trainer/classifier.py
+++ b/src/soup_cli/trainer/classifier.py
@@ -35,6 +35,7 @@ from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils.eval_schedule import training_eval_kwargs
from soup_cli.utils.gpu import bf16_fp16_flags
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -293,7 +294,8 @@ class ClassifierTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None and self.tokenizer.eos_token is not None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -304,6 +306,7 @@ class ClassifierTrainerWrapper:
num_labels=num_labels,
problem_type=problem_type,
trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
label_names = (
list(tcfg.label_names) if tcfg.label_names is not None else None
diff --git a/src/soup_cli/trainer/csm.py b/src/soup_cli/trainer/csm.py
index e6a4e0b2..4f978a71 100644
--- a/src/soup_cli/trainer/csm.py
+++ b/src/soup_cli/trainer/csm.py
@@ -8,6 +8,7 @@ from typing import Any
from soup_cli.trainer.sft import SFTTrainerWrapper, console
from soup_cli.utils.csm import validate_csm_config, validate_csm_dataset, validate_csm_row
from soup_cli.utils.eval_schedule import training_eval_kwargs
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -149,6 +150,7 @@ class CSMTrainerWrapper(SFTTrainerWrapper):
apply_training_seed(tcfg)
self.processor = CsmProcessor.from_pretrained(
cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
# Saving the processor, rather than just its tokenizer, preserves the
# feature extractor + native chat template for reload/inference.
@@ -157,6 +159,7 @@ class CSMTrainerWrapper(SFTTrainerWrapper):
cfg.base,
torch_dtype=resolve_base_load_dtype(self.device, full_finetune=tcfg.lora.r == 0),
trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if (self.model.config.num_codebooks != 32
or self.model.codec_model.config.num_quantizers != 32
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index a2fcd846..d24437af 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -40,6 +40,7 @@ if TYPE_CHECKING:
import torch as _torch_typ
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
logger = logging.getLogger(__name__)
console = Console()
@@ -513,7 +514,8 @@ class DistillTrainerWrapper:
console.print(f"[dim]Loading tokenizer (student/teacher shared): {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -524,6 +526,7 @@ class DistillTrainerWrapper:
cfg.base,
trust_remote_code=self._trust_remote_code,
device_map=dev_map,
+ **base_revision_kwargs(cfg.base),
)
# LoRA on the student — bracket with v0.40.6 #67 surgical PEFT patches.
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index ac367875..3d37448b 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -23,6 +23,7 @@ from soup_cli.utils.mixed_precision import (
keep_trainable_dtype_on_resume,
reload_root_adapter_on_resume,
)
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -305,7 +306,8 @@ class DPOTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading vision processor: {cfg.base}[/]")
self.processor = AutoProcessor.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
_ensure_vision_processor_pad_token(self.processor)
self.tokenizer = self.processor
@@ -314,7 +316,8 @@ class DPOTrainerWrapper(StreamingSetupMixin):
else:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -338,7 +341,10 @@ class DPOTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = loader.from_pretrained(cfg.base, **model_kwargs)
+ self.model = loader.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index 792b686c..c3e0dda6 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -17,6 +17,7 @@ from soup_cli.utils.gpu import (
resolve_device_map,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -268,7 +269,8 @@ class EmbeddingTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -294,7 +296,10 @@ class EmbeddingTrainerWrapper:
model_kwargs["quantization_config"] = quant_config_obj
# Use AutoModel (not AutoModelForCausalLM) for embedding models
- self.model = AutoModel.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModel.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index 85198508..f9c25be5 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -27,6 +27,7 @@ from soup_cli.utils.mixed_precision import (
keep_trainable_dtype_on_resume,
reload_root_adapter_on_resume,
)
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -646,7 +647,8 @@ class GRPOTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -671,7 +673,10 @@ class GRPOTrainerWrapper:
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 6038455b..52aa8f3e 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -22,6 +22,7 @@ from soup_cli.utils.mixed_precision import (
keep_trainable_dtype_on_resume,
reload_root_adapter_on_resume,
)
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -224,7 +225,8 @@ class IPOTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -245,7 +247,10 @@ class IPOTrainerWrapper:
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index 3768106c..0be0919f 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -19,6 +19,7 @@ from soup_cli.utils.gpu import (
resolve_frozen_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -253,7 +254,8 @@ class KTOTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -275,7 +277,10 @@ class KTOTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/mole_routing.py b/src/soup_cli/trainer/mole_routing.py
index 33e4be51..7ebaf371 100644
--- a/src/soup_cli/trainer/mole_routing.py
+++ b/src/soup_cli/trainer/mole_routing.py
@@ -34,6 +34,7 @@ from soup_cli.utils.gpu import (
model_size_from_name,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
logger = logging.getLogger(__name__)
@@ -303,7 +304,8 @@ class MoleRoutingTrainerWrapper:
)
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -312,6 +314,7 @@ class MoleRoutingTrainerWrapper:
cfg.base,
trust_remote_code=self._trust_remote_code,
torch_dtype=torch.bfloat16 if self.device == "cuda" else torch.float32,
+ **base_revision_kwargs(cfg.base),
)
hidden_size = base_model.config.hidden_size
@@ -319,7 +322,7 @@ class MoleRoutingTrainerWrapper:
# rest — PEFT multi-adapter pattern (matches v0.71.8 interference_live).
adapter_names = [f"task_{i}" for i in range(len(adapters))]
model = PeftModel.from_pretrained(
- base_model, adapters[0], adapter_name=adapter_names[0]
+ base_model, adapters[0], adapter_name=adapter_names[0],
)
for name, path in zip(adapter_names[1:], adapters[1:]):
model.load_adapter(path, adapter_name=name)
diff --git a/src/soup_cli/trainer/online_dpo.py b/src/soup_cli/trainer/online_dpo.py
index c1e70e93..890d7502 100644
--- a/src/soup_cli/trainer/online_dpo.py
+++ b/src/soup_cli/trainer/online_dpo.py
@@ -57,6 +57,7 @@ from soup_cli.utils.gpu import (
resolve_frozen_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -381,7 +382,8 @@ class OnlineDPOTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -409,7 +411,10 @@ class OnlineDPOTrainerWrapper:
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index 52d9d035..9604580c 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -19,6 +19,7 @@ from soup_cli.utils.gpu import (
resolve_frozen_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -273,7 +274,8 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -294,7 +296,10 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.py
index 3c8f3281..a6a42c24 100644
--- a/src/soup_cli/trainer/ppo.py
+++ b/src/soup_cli/trainer/ppo.py
@@ -27,6 +27,7 @@ from soup_cli.utils.gpu import (
resolve_frozen_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -617,6 +618,7 @@ class PPOTrainerWrapper:
trust_remote_code=self._trust_remote_code,
num_labels=1,
device_map=resolve_device_map(self.device) if self.device != "cpu" else None,
+ **base_revision_kwargs(cfg.base),
)
reward_model.eval()
return reward_model
@@ -659,6 +661,7 @@ class PPOTrainerWrapper:
trust_remote_code=self._trust_remote_code,
num_labels=1,
device_map=resolve_device_map(self.device) if self.device != "cpu" else None,
+ **base_revision_kwargs(cfg.base),
)
return value_model
@@ -696,7 +699,8 @@ class PPOTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -718,7 +722,10 @@ class PPOTrainerWrapper:
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
if tcfg.quantization in ("4bit", "8bit"):
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index 0b09cccd..4d42db4b 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -17,6 +17,7 @@ from soup_cli.utils.gpu import (
resolve_device_map,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -315,7 +316,8 @@ class PretrainTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -346,7 +348,8 @@ class PretrainTrainerWrapper:
from soup_cli.utils.long_context import apply_long_context_config
model_config = AutoConfig.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
rope_config = apply_long_context_config(
model_config,
@@ -361,7 +364,10 @@ class PretrainTrainerWrapper:
if rope_config:
model_kwargs["config"] = model_config
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
if rope_config:
console.print(
f"[green]Long-context enabled:[/] RoPE {tcfg.rope_scaling_type} "
diff --git a/src/soup_cli/trainer/prm.py b/src/soup_cli/trainer/prm.py
index 18790ea5..131e26b6 100644
--- a/src/soup_cli/trainer/prm.py
+++ b/src/soup_cli/trainer/prm.py
@@ -36,6 +36,7 @@ from soup_cli.utils.gpu import (
resolve_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
logger = logging.getLogger(__name__)
@@ -275,7 +276,8 @@ class PRMTrainerWrapper:
apply_training_seed(cfg.training)
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -292,6 +294,7 @@ class PRMTrainerWrapper:
# GradScaler on pre-Ampere cards, and makes the Metal optimizer abort
# on MPS (#564).
torch_dtype=resolve_base_load_dtype(self.device, full_finetune=True),
+ **base_revision_kwargs(cfg.base),
)
hidden_size = base_model.config.hidden_size
# The head trains too, so it is an fp32 master weight like the base.
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index b36f06b3..ba740830 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -28,6 +28,7 @@ from soup_cli.utils.mixed_precision import (
align_trainable_dtype_for_fp16,
keep_trainable_dtype_on_resume,
)
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -220,7 +221,8 @@ class RewardModelTrainerWrapper:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -252,6 +254,7 @@ class RewardModelTrainerWrapper:
self.model = AutoModelForSequenceClassification.from_pretrained(
cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
)
if tcfg.quantize_reward_model and tcfg.quantization in ("4bit", "8bit"):
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index 086ae2b2..dd9a0af9 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -25,6 +25,7 @@ from soup_cli.utils.mixed_precision import (
align_trainable_dtype_for_fp16,
keep_trainable_dtype_on_resume,
)
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
from soup_cli.utils.terminal import for_terminal
@@ -1643,7 +1644,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -1684,7 +1686,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):
from soup_cli.utils.long_context import apply_long_context_config
model_config = AutoConfig.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
rope_config = apply_long_context_config(
model_config,
@@ -1699,7 +1702,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
if rope_config:
model_kwargs["config"] = model_config
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
@@ -1950,7 +1956,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading vision processor: {cfg.base}[/]")
self.processor = AutoProcessor.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
# Idefics3/SmolVLM (and other) processors keep the text tokenizer nested
# and don't forward pad_token/eos_token — mirror them onto the processor
@@ -1989,7 +1996,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForImageTextToText.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForImageTextToText.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
@@ -2121,7 +2131,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):
)
console.print(f"[dim]Loading audio processor: {cfg.base}[/]")
self.processor = AutoProcessor.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
self.tokenizer = self.processor # SFTTrainer uses processing_class
@@ -2153,7 +2164,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
# Use AutoModel for audio models — AutoModelForCausalLM doesn't handle
# audio-language architectures (Qwen2-Audio, Whisper, etc.)
- self.model = AutoModel.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModel.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index e49756dd..93d0c51d 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -19,6 +19,7 @@ from soup_cli.utils.gpu import (
resolve_frozen_base_load_dtype,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
console = Console()
@@ -268,7 +269,8 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -289,7 +291,10 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
if quant_config_obj is not None:
model_kwargs["quantization_config"] = quant_config_obj
- self.model = AutoModelForCausalLM.from_pretrained(cfg.base, **model_kwargs)
+ self.model = AutoModelForCausalLM.from_pretrained(
+ cfg.base, **model_kwargs,
+ **base_revision_kwargs(cfg.base),
+ )
from soup_cli.utils.data_pipeline import apply_vocab_expansion
apply_vocab_expansion(
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 09edf27f..8713b9fb 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -31,6 +31,7 @@ from rich.panel import Panel
from soup_cli.utils.config_bounds import DEFAULT_STREAM_READ_AHEAD, MAX_STREAM_READ_AHEAD
from soup_cli.utils.paths import quote_path
+from soup_cli.utils.run_provenance import base_revision_kwargs
from soup_cli.utils.stripe_roots import ReadAheadDecision, effective_read_ahead
console = Console()
@@ -781,7 +782,8 @@ class StreamingSetupMixin:
console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code
+ cfg.base, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
@@ -789,7 +791,8 @@ class StreamingSetupMixin:
# The streamed decoder is always transformers' own class (see
# _STREAM_NATIVE_MODEL_CODE); trust_remote_code reaches the tokenizer only.
model_config = AutoConfig.from_pretrained(
- cfg.base, trust_remote_code=self._STREAM_NATIVE_MODEL_CODE
+ cfg.base, trust_remote_code=self._STREAM_NATIVE_MODEL_CODE,
+ **base_revision_kwargs(cfg.base),
)
# Allowlist, not a heuristic — a half-supported architecture streams
# weights into the wrong module and mis-trains silently.
diff --git a/src/soup_cli/utils/cut_ce.py b/src/soup_cli/utils/cut_ce.py
index 9b84e90e..007804e8 100644
--- a/src/soup_cli/utils/cut_ce.py
+++ b/src/soup_cli/utils/cut_ce.py
@@ -17,6 +17,8 @@ Incompatibilities:
from __future__ import annotations
+from soup_cli.utils.run_provenance import base_revision_kwargs
+
# Single source of truth for the advisory both trainer/sft.py and
# utils/v028_features.py print when apply_cut_ce() returns False.
NO_MATCHING_ARCHITECTURE_MESSAGE = "no matching architecture or cut_cross_entropy not installed"
@@ -52,7 +54,10 @@ def _detect_model_type(model_name: str) -> str:
try:
from transformers import AutoConfig
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=False)
+ config = AutoConfig.from_pretrained(
+ model_name, trust_remote_code=False,
+ **base_revision_kwargs(model_name),
+ )
except Exception: # noqa: BLE001 (detection is best-effort by design)
return ""
return str(getattr(config, "model_type", "") or "")
diff --git a/src/soup_cli/utils/liger.py b/src/soup_cli/utils/liger.py
index 08a3ca91..e8a7d3f2 100644
--- a/src/soup_cli/utils/liger.py
+++ b/src/soup_cli/utils/liger.py
@@ -13,6 +13,8 @@ Requires: liger-kernel >= 0.3.0
from __future__ import annotations
+from soup_cli.utils.run_provenance import base_revision_kwargs
+
def check_liger_available() -> bool:
"""Check if liger-kernel is installed."""
@@ -116,7 +118,10 @@ def _detect_model_type(model_name: str) -> str:
try:
from transformers import AutoConfig
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=False)
+ config = AutoConfig.from_pretrained(
+ model_name, trust_remote_code=False,
+ **base_revision_kwargs(model_name),
+ )
except Exception: # noqa: BLE001 — detection is best-effort by design
return ""
return str(getattr(config, "model_type", "") or "")
diff --git a/src/soup_cli/utils/live_eval.py b/src/soup_cli/utils/live_eval.py
index c5205c1c..1cff339f 100644
--- a/src/soup_cli/utils/live_eval.py
+++ b/src/soup_cli/utils/live_eval.py
@@ -240,10 +240,25 @@ def load_model_and_tokenizer(
from transformers import AutoModelForCausalLM, AutoTokenizer
dev = resolve_device(device)
- tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=trust_remote_code)
+ from soup_cli.utils.run_provenance import (
+ base_revision_kwargs,
+ recorded_adapter_base,
+ recorded_base_kwargs,
+ )
+
+ tokenizer_id = model_id
+ if adapter is None:
+ saved_base = recorded_adapter_base(model_id)
+ if saved_base is not None:
+ adapter, model_id = model_id, saved_base
+ revision_kwargs = base_revision_kwargs(model_id) or recorded_base_kwargs(adapter, model_id)
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_id, trust_remote_code=trust_remote_code,
+ **(revision_kwargs if tokenizer_id == model_id else {}),
+ )
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
- model_kwargs = {"trust_remote_code": trust_remote_code}
+ model_kwargs = {"trust_remote_code": trust_remote_code, **revision_kwargs}
if dtype is not None:
model_kwargs["torch_dtype"] = dtype
quant_config = _build_quantization_config(quantization)
diff --git a/src/soup_cli/utils/run_provenance.py b/src/soup_cli/utils/run_provenance.py
new file mode 100644
index 00000000..7fd9679d
--- /dev/null
+++ b/src/soup_cli/utils/run_provenance.py
@@ -0,0 +1,202 @@
+"""Run-scoped base revisions and portable, explicitly nullable artifact metadata.
+
+No library monkeypatches or new config fields. HF loaders opt in through
+``base_revision_kwargs``; unsupported backends retain their existing behavior.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Iterator
+
+from soup_cli.utils.hf import get_hf_api
+
+PROVENANCE_FILENAME = "soup_run.json"
+_MAX_METADATA_BYTES = 64 * 1024
+_REVISION = re.compile(r"[0-9a-f]{40}")
+_SHA256 = re.compile(r"[0-9a-f]{64}")
+_SOURCES = {
+ "hub_commit", "cache_path", "local", "unknown", "unsupported_backend", "offline",
+ "resolution_failed",
+}
+
+
+def validate_identity(revision: str | None, source: str | None) -> None:
+ """Reject malformed metadata without inventing a commit for unknown runs."""
+ if source is not None and (not isinstance(source, str) or source not in _SOURCES):
+ raise ValueError("invalid base revision source")
+ if revision is not None:
+ if not isinstance(revision, str) or not _REVISION.fullmatch(revision):
+ raise ValueError("base revision must be a lowercase 40-hex commit or None")
+ if source not in {"hub_commit", "cache_path"}:
+ raise ValueError("a recorded revision needs its identity source")
+
+
+def validate_training_hash(value: str | None) -> None:
+ if value is not None and (not isinstance(value, str) or not _SHA256.fullmatch(value)):
+ raise ValueError("training data hash must be a lowercase SHA-256 or None")
+
+
+@dataclass
+class BaseRevision:
+ """Resolve at most once, immediately before the first supported base load.
+
+ A cache directory's name is metadata, not an integrity check on local bytes.
+ Offline/probe failure preserves the prior loader flow and records unknown.
+ """
+
+ base: str
+ binding_supported: bool = True
+ revision: str | None = field(default=None, init=False)
+ source: str = field(default="unknown", init=False)
+ _pending: bool = field(default=True, init=False, repr=False)
+
+ def __post_init__(self) -> None:
+ if os.path.isdir(self.base):
+ path = Path(os.path.abspath(self.base))
+ self.source = "local"
+ if path.parent.name == "snapshots" and _REVISION.fullmatch(path.name):
+ self.revision, self.source = path.name, "cache_path"
+ self._pending = False
+ elif not self.binding_supported:
+ self.source, self._pending = "unsupported_backend", False
+
+ def load_kwargs(self, model_id: str) -> dict[str, str]:
+ if not isinstance(model_id, str) or model_id != self.base:
+ return {}
+ if self._pending:
+ self._pending = False
+ if any(os.environ.get(name, "").upper() in {"1", "TRUE", "YES", "ON"}
+ for name in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE")):
+ self.source = "offline"
+ else:
+ try:
+ # Bound the optional metadata request, not model downloads.
+ revision = get_hf_api().model_info(self.base, timeout=5).sha
+ if isinstance(revision, str) and _REVISION.fullmatch(revision):
+ self.revision, self.source = revision, "hub_commit"
+ else:
+ self.source = "resolution_failed"
+ except Exception:
+ # Do not echo provider exceptions: they can contain tokens/paths.
+ self.source = "resolution_failed"
+ if self.source == "hub_commit" and self.revision is not None:
+ return {"revision": self.revision}
+ return {}
+
+ def metadata(self, run_id: str) -> dict[str, Any]:
+ return {
+ "schema_version": 1, "run_id": run_id, "base_model": self.base,
+ "base_revision": self.revision, "base_revision_source": self.source,
+ # Reserved shared storage contract; hash capture is #1764 part 2.
+ "training_data_sha256": None,
+ }
+
+
+_ACTIVE_BASE: ContextVar[BaseRevision | None] = ContextVar("soup_base_revision", default=None)
+
+
+@contextmanager
+def base_revision_scope(identity: BaseRevision) -> Iterator[None]:
+ """Keep one execution identity across setup/training; restore nested callers."""
+ token = _ACTIVE_BASE.set(identity)
+ try:
+ yield
+ finally:
+ _ACTIVE_BASE.reset(token)
+
+
+def base_revision_kwargs(model_id: str) -> dict[str, str]:
+ """Pin only this run's base, never unrelated teachers/rewards/scorers."""
+ identity = _ACTIVE_BASE.get()
+ return identity.load_kwargs(model_id) if identity is not None else {}
+
+
+def _validate_metadata(data: Any) -> dict[str, Any]:
+ if (not isinstance(data, dict) or type(data.get("schema_version")) is not int
+ or data["schema_version"] != 1):
+ raise ValueError("unsupported run metadata")
+ if not isinstance(data.get("run_id"), str) or not data["run_id"]:
+ raise ValueError("run metadata needs a run ID")
+ if not isinstance(data.get("base_model"), str) or not data["base_model"]:
+ raise ValueError("run metadata needs the original base ID")
+ validate_identity(data.get("base_revision"), data.get("base_revision_source"))
+ validate_training_hash(data.get("training_data_sha256"))
+ return data
+
+
+def write_run_provenance(output: str | Path, metadata: dict[str, Any]) -> None:
+ """Atomically save the final artifact's run identity without a DB dependency."""
+ _validate_metadata(metadata)
+ directory = Path(output)
+ directory.mkdir(parents=True, exist_ok=True)
+ payload = json.dumps(metadata, sort_keys=True, ensure_ascii=False).encode("utf-8")
+ if len(payload) > _MAX_METADATA_BYTES:
+ raise ValueError("run metadata is too large")
+ fd, temporary = tempfile.mkstemp(prefix=".soup_run_", dir=directory)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(payload)
+ os.replace(temporary, directory / PROVENANCE_FILENAME)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+
+
+def read_run_provenance(artifact: str | Path) -> dict[str, Any]:
+ """Unknown/malformed/legacy metadata must not introduce new load refusals."""
+ try:
+ with (Path(artifact) / PROVENANCE_FILENAME).open("rb") as handle:
+ payload = handle.read(_MAX_METADATA_BYTES + 1)
+ if len(payload) > _MAX_METADATA_BYTES:
+ return {}
+ return _validate_metadata(json.loads(payload))
+ except (OSError, ValueError, TypeError, RecursionError):
+ return {}
+
+
+def recorded_base_kwargs(artifact: str | None, base: str) -> dict[str, str]:
+ """Reuse a copied artifact's Hub commit only for its matching base ID.
+
+ An explicit base override, a local source, or a cache-path hint is not a
+ bound Hub identity. Leave those existing flows alone instead of guessing.
+ """
+ if artifact is None or os.path.isdir(base):
+ return {}
+ data = read_run_provenance(artifact)
+ if (data.get("base_model") == base and data.get("base_revision_source") == "hub_commit"
+ and data.get("base_revision") is not None):
+ return {"revision": data["base_revision"]}
+ return {}
+
+
+def recorded_adapter_base(artifact: str) -> str | None:
+ """Recognize a local adapter whose saved base agrees with its run metadata.
+
+ Transformers otherwise auto-loads the base from adapter_config.json, which
+ can resolve a moving Hub HEAD. Preserve legacy/explicit-revision behavior
+ when the two local records disagree instead of rewriting an override.
+ """
+ data = read_run_provenance(artifact)
+ base = data.get("base_model")
+ if not isinstance(base, str) or not recorded_base_kwargs(artifact, base):
+ return None
+ try:
+ with (Path(artifact) / "adapter_config.json").open("rb") as handle:
+ payload = handle.read(_MAX_METADATA_BYTES + 1)
+ if len(payload) > _MAX_METADATA_BYTES:
+ return None
+ config = json.loads(payload)
+ if (isinstance(config, dict) and config.get("base_model_name_or_path") == base
+ and config.get("revision") in (None, data["base_revision"])):
+ return base
+ except (OSError, ValueError, TypeError, RecursionError):
+ pass
+ return None
diff --git a/tests/test_base_loader_contracts.py b/tests/test_base_loader_contracts.py
new file mode 100644
index 00000000..17f75738
--- /dev/null
+++ b/tests/test_base_loader_contracts.py
@@ -0,0 +1,128 @@
+"""Execute each resident trainer's actual HF call expression with strict receivers.
+
+This inventories the load boundary rather than trusting one representative
+trainer: removing the revision argument at any base call must fail independently.
+Model computation is covered separately using locally constructed HF models.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.utils import run_provenance as provenance
+
+BASE = "owner/base"
+REVISION = "a" * 40
+ROOT = Path(__file__).resolve().parents[1]
+_BASE_ARGUMENTS = {
+ "cfg.base", "config.base", "self.config.base", "base", "base_model", "model_id", "model_name",
+}
+
+
+def _load_calls():
+ paths = sorted((ROOT / "src/soup_cli/trainer").glob("*.py"))
+ paths += [ROOT / f"src/soup_cli/utils/{name}.py" for name in ("cut_ce", "liger")]
+ cases = []
+ for path in paths:
+ text = path.read_text(encoding="utf-8")
+ for call in ast.walk(ast.parse(text)):
+ if (not isinstance(call, ast.Call) or not isinstance(call.func, ast.Attribute)
+ or call.func.attr != "from_pretrained" or not call.args):
+ continue
+ receiver = ast.get_source_segment(text, call.func.value)
+ if receiver == "PeftModel":
+ continue # Its first argument is a loaded model, not a Hub repository.
+ if ast.get_source_segment(text, call.args[0]) in _BASE_ARGUMENTS:
+ cases.append(pytest.param(call, receiver, id=f"{path.stem}:{call.lineno}"))
+ assert len(cases) >= 40, "the inventory must cover the whole resident base-loader surface"
+ return cases
+
+
+class _Values:
+ def __getattr__(self, name):
+ if name == "base":
+ return BASE
+ return self
+
+ def __call__(self, *args, **kwargs):
+ return None
+
+
+class _Environment(dict):
+ def __missing__(self, name):
+ if name.endswith("kwargs"):
+ return {}
+ return _Values()
+
+
[email protected]("call,receiver", _load_calls())
+def test_every_actual_base_loader_call_receives_the_bound_commit(call, receiver, monkeypatch):
+ seen = []
+
+ def load(model_id, *args, revision, **kwargs):
+ assert model_id == BASE
+ assert revision == REVISION
+ seen.append((model_id, revision))
+
+ env = _Environment(
+ base=BASE, base_model=BASE, model_id=BASE, model_name=BASE,
+ cfg=_Values(), config=_Values(), self=_Values(),
+ base_revision_kwargs=provenance.base_revision_kwargs,
+ )
+ env[receiver] = SimpleNamespace(from_pretrained=load)
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(
+ model_info=lambda *args, **kwargs: SimpleNamespace(sha=REVISION),
+ ))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+ expression = compile(ast.Expression(body=call), "<actual base load>", "eval")
+ with provenance.base_revision_scope(provenance.BaseRevision(BASE)):
+ eval(expression, env)
+ assert seen == [(BASE, REVISION)]
+
+
[email protected]("receiver,remote_code", [("AutoConfig", False), ("AutoTokenizer", True)])
+def test_streamed_loads_preserve_native_model_policy_and_bound_revision(
+ receiver, remote_code, monkeypatch,
+):
+ """Execute the merged calls: tokenizer trust must not enable remote model code."""
+ path = ROOT / "src/soup_cli/trainer/stream_setup.py"
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ model_code = next(
+ ast.literal_eval(node.value) for node in ast.walk(tree)
+ if isinstance(node, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == "_STREAM_NATIVE_MODEL_CODE"
+ for target in node.targets
+ )
+ )
+ assert model_code is False
+ calls = [node for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == receiver
+ and node.func.attr == "from_pretrained"]
+ assert len(calls) == 1
+ seen = []
+
+ def load(model_id, *, trust_remote_code, revision):
+ assert model_id == BASE and revision == REVISION
+ assert trust_remote_code is remote_code
+ seen.append(model_id)
+
+ env = {
+ "cfg": SimpleNamespace(base=BASE),
+ "self": SimpleNamespace(_trust_remote_code=True, _STREAM_NATIVE_MODEL_CODE=model_code),
+ receiver: SimpleNamespace(from_pretrained=load),
+ "base_revision_kwargs": provenance.base_revision_kwargs,
+ }
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(
+ model_info=lambda *args, **kwargs: SimpleNamespace(sha=REVISION),
+ ))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+ with provenance.base_revision_scope(provenance.BaseRevision(BASE)):
+ eval(compile(ast.Expression(body=calls[0]), "<streamed base load>", "eval"), env)
+ assert seen == [BASE]
diff --git a/tests/test_base_revision_loading.py b/tests/test_base_revision_loading.py
new file mode 100644
index 00000000..dd0e9f8c
--- /dev/null
+++ b/tests/test_base_revision_loading.py
@@ -0,0 +1,230 @@
+"""Exercise real loader/CLI boundaries without Hub downloads or a GPU."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from soup_cli.utils import run_provenance as provenance
+
+BASE = "owner/base"
+REVISION = "a" * 40
+
+
+def moving_hub(monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+ probe = Mock(side_effect=[SimpleNamespace(sha=REVISION), SimpleNamespace(sha="b" * 40)])
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(model_info=probe))
+ return probe
+
+
+def test_actual_sft_loads_pin_tokenizer_model_and_config(tmp_path, monkeypatch, moving_hub):
+ pytest.importorskip("torch")
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
+
+ from soup_cli.config.schema import SoupConfig
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+ from tests._tiny_hf_models import tiny_model_dir
+
+ local = tiny_model_dir("llama")
+ original_config = AutoConfig.from_pretrained
+ original_model = AutoModelForCausalLM.from_pretrained
+ original_tokenizer = AutoTokenizer.from_pretrained
+ calls = []
+
+ def tokenizer(model_id, *, trust_remote_code, revision):
+ assert model_id == BASE
+ assert revision == REVISION
+ calls.append("tokenizer")
+ return original_tokenizer(local, trust_remote_code=trust_remote_code)
+
+ def config(model_id, **kwargs):
+ if model_id == BASE:
+ assert kwargs.pop("revision") == REVISION
+ calls.append("config")
+ model_id = local
+ # AutoTokenizer also reads the redirected local model's config internally.
+ return original_config(model_id, **kwargs)
+
+ def model(model_id, *, trust_remote_code, device_map, torch_dtype, config, revision):
+ assert model_id == BASE
+ assert revision == REVISION
+ calls.append("model")
+ return original_model(
+ local, trust_remote_code=trust_remote_code, device_map=device_map,
+ torch_dtype=torch_dtype, config=config,
+ )
+
+ monkeypatch.setattr(AutoTokenizer, "from_pretrained", tokenizer)
+ monkeypatch.setattr(AutoConfig, "from_pretrained", config)
+ monkeypatch.setattr(AutoModelForCausalLM, "from_pretrained", model)
+ cfg = SoupConfig(
+ base=BASE, data={"train": "unused.jsonl", "max_length": 256},
+ training={"quantization": "none", "rope_scaling_type": "linear",
+ "lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]}},
+ output=str(tmp_path / "out"),
+ )
+ identity = provenance.BaseRevision(BASE)
+ wrapper = SFTTrainerWrapper(cfg, device="cpu")
+ with provenance.base_revision_scope(identity):
+ wrapper._setup_transformers(cfg, cfg.training)
+ assert calls == ["tokenizer", "config", "model"]
+ assert moving_hub.call_count == 1
+ assert cfg.base == BASE
+ assert wrapper.model is not None
+
+
[email protected]("mode", ["recorded", "implicit", "override", "legacy"])
+def test_copied_adapter_pins_live_eval_and_export_loaders(tmp_path, monkeypatch, mode):
+ pytest.importorskip("torch")
+ from peft import LoraConfig, get_peft_model
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ from soup_cli.commands.export import _merge_adapter
+ from soup_cli.utils.live_eval import load_model_and_tokenizer
+ from tests._tiny_hf_models import tiny_model_dir
+
+ local = tiny_model_dir("llama")
+ original_model = AutoModelForCausalLM.from_pretrained
+ original_tokenizer = AutoTokenizer.from_pretrained
+ base = original_model(local)
+ adapter = get_peft_model(base, LoraConfig(r=4, target_modules=["q_proj", "v_proj"]))
+ adapter.peft_config["default"].base_model_name_or_path = BASE
+ source = tmp_path / "original-adapter"
+ adapter.save_pretrained(source)
+ original_tokenizer(local).save_pretrained(source)
+ identity = provenance.BaseRevision(BASE)
+ identity.revision, identity.source = REVISION, "hub_commit"
+ if mode != "legacy":
+ provenance.write_run_provenance(source, identity.metadata("deleted-original-run"))
+ copied = tmp_path / "copied-adapter"
+ shutil.copytree(source, copied)
+ shutil.rmtree(source)
+ selected_base = "different/base" if mode == "override" else BASE
+ expected_revision = REVISION if mode in {"recorded", "implicit"} else None
+ calls = []
+
+ def model(model_id, *, revision=None, **kwargs):
+ assert model_id == selected_base
+ assert revision == expected_revision
+ calls.append(("model", revision))
+ return original_model(local, **kwargs)
+
+ def tokenizer(model_id, **kwargs):
+ if model_id == selected_base:
+ assert kwargs.pop("revision", None) == expected_revision
+ calls.append(("tokenizer", expected_revision))
+ model_id = local
+ else:
+ assert "revision" not in kwargs
+ return original_tokenizer(model_id, **kwargs)
+
+ monkeypatch.setattr(AutoModelForCausalLM, "from_pretrained", model)
+ monkeypatch.setattr(AutoTokenizer, "from_pretrained", tokenizer)
+ monkeypatch.setattr(provenance, "get_hf_api", Mock(side_effect=AssertionError("no lookup")))
+ if mode == "implicit":
+ loaded, _, device = load_model_and_tokenizer(str(copied), device="cpu")
+ else:
+ loaded, _, device = load_model_and_tokenizer(
+ selected_base, adapter=str(copied), device="cpu",
+ )
+ assert loaded is not None and str(device) == "cpu"
+ merged = tmp_path / "merged"
+ _merge_adapter(str(copied), selected_base, str(merged))
+ assert (merged / "config.json").is_file()
+ expected_calls = [] if mode == "implicit" else [("tokenizer", expected_revision)]
+ assert calls == expected_calls + [("model", expected_revision), ("model", expected_revision)]
+
+
[email protected]("mode", ["bound", "offline", "distributed", "non-hf"])
[email protected]("stored_hash", [None, "c" * 64], ids=["unknown-data", "stored-data"])
+def test_train_cli_records_identity_and_writes_final_artifact(
+ tmp_path, monkeypatch, moving_hub, mode, stored_hash,
+):
+ pytest.importorskip("torch")
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+ from soup_cli.experiment.tracker import ExperimentTracker
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SOUP_DB_PATH", str(tmp_path / "runs.db"))
+ if mode == "offline":
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setattr("soup_cli.utils.launcher.is_in_distributed", lambda: mode == "distributed")
+ monkeypatch.setattr("soup_cli.utils.gpu.detect_device", lambda: ("cpu", "CPU"))
+ monkeypatch.setattr("soup_cli.utils.gpu.get_gpu_info", lambda: {})
+ alternate_snapshot = None
+
+ def alternate_hub(hub, model_id, *, local_dir):
+ nonlocal alternate_snapshot
+ assert hub == "modelscope" and model_id == BASE
+ alternate_snapshot = local_dir
+ directory = Path(local_dir)
+ directory.mkdir(parents=True)
+ (directory / "config.json").write_text("{}", encoding="utf-8")
+ return local_dir
+
+ if mode == "non-hf":
+ monkeypatch.setattr("soup_cli.utils.hubs.download_repo", alternate_hub)
+ output = tmp_path / "final"
+ (tmp_path / "data.jsonl").write_text(
+ '{"instruction":"hi", "output":"hello"}\n', encoding="utf-8",
+ )
+ (tmp_path / "soup.yaml").write_text(
+ f"base: {BASE}\ndata: {{train: data.jsonl, format: alpaca, val_split: 0}}\n"
+ "training: {epochs: 1, quantization: none, batch_size: 1, "
+ f"hub: {'modelscope' if mode == 'non-hf' else 'hf'}}}\noutput: final\n",
+ encoding="utf-8",
+ )
+ expected = {"revision": REVISION} if mode == "bound" else {}
+
+ class Trainer:
+ def setup(self, dataset):
+ assert dataset["train"]
+ assert provenance.base_revision_kwargs(BASE) == expected
+
+ def train(self, **kwargs):
+ assert provenance.base_revision_kwargs(BASE) == expected
+ # Emulate a separate producer of the reserved historical hash field.
+ conn = kwargs["tracker"]._get_conn()
+ conn.execute(
+ "UPDATE runs SET training_data_sha256=? WHERE run_id=?",
+ (stored_hash, kwargs["run_id"]),
+ )
+ conn.commit()
+ output.mkdir()
+ return {"output_dir": str(output), "initial_loss": 1.0, "final_loss": 0.5,
+ "total_steps": 1, "duration_secs": 1.0}
+
+ def build(cfg, **kwargs):
+ assert cfg.base == (alternate_snapshot if mode == "non-hf" else BASE)
+ return Trainer()
+
+ monkeypatch.setattr("soup_cli.trainer.dispatch.build_trainer", build)
+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])
+ assert result.exit_code == 0, (result.output, result.exception)
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ row = tracker.list_runs()[0]
+ assert row["status"] == "completed"
+ assert row["base_model"] == BASE
+ assert json.loads(row["config_json"])["base"] == BASE
+ assert row["base_revision"] == (REVISION if mode == "bound" else None)
+ assert row["base_revision_source"] == {
+ "bound": "hub_commit", "offline": "offline", "distributed": "unsupported_backend",
+ "non-hf": "unsupported_backend",
+ }[mode]
+ metadata = provenance.read_run_provenance(output)
+ assert metadata["run_id"] == row["run_id"]
+ assert metadata["base_revision"] == row["base_revision"]
+ assert metadata["training_data_sha256"] == stored_hash
+ assert moving_hub.call_count == (1 if mode == "bound" else 0)
+ assert provenance.base_revision_kwargs(BASE) == {}
+ tracker.close()
diff --git a/tests/test_registry_idempotency.py b/tests/test_registry_idempotency.py
index 4f832ee3..4f19d5fe 100644
--- a/tests/test_registry_idempotency.py
+++ b/tests/test_registry_idempotency.py
@@ -271,8 +271,9 @@ def test_a_legacy_database_is_upgraded_in_place(tmp_path):
"SELECT * FROM registry_entries WHERE id LIKE 'reg_old_%' ORDER BY id"
).fetchall()
conn.close()
- assert [row[:-1] for row in after] == before # old rows only gain a NULL key
- assert [row[-1] for row in after] == [None, None]
+ width = len(before[0])
+ assert [row[:width] for row in after] == before # every legacy value is unchanged
+ assert [row[width:] for row in after] == [(None, None, None, None)] * 2
assert _counts(db) == (3, 3)
diff --git a/tests/test_run_provenance.py b/tests/test_run_provenance.py
new file mode 100644
index 00000000..a376c9ec
--- /dev/null
+++ b/tests/test_run_provenance.py
@@ -0,0 +1,424 @@
+"""Recorded base identities survive database upgrades and copied adapters."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import shutil
+import sqlite3
+from concurrent.futures import ThreadPoolExecutor
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from soup_cli.experiment.tracker import ExperimentTracker
+from soup_cli.registry import RegistryStore, hash_entry, hash_file
+
+REVISION = "a" * 40
+OTHER_REVISION = "b" * 40
+TRAINING_HASH = "c" * 64
+BASE = "owner/base"
+
+
[email protected](autouse=True)
+def explicit_offline_state(monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+
+
+def _run(tracker, *, base=BASE):
+ return tracker.start_run({"base": base, "task": "sft"}, "cpu", "CPU", {})
+
+
+def test_legacy_run_upgrade_is_nullable_and_idempotent(tmp_path):
+ from soup_cli.experiment.tracker import _SCHEMA_SQL
+
+ db = tmp_path / "legacy.db"
+ # Strip only the new columns to reproduce a database from before this feature.
+ legacy = "\n".join(
+ line for line in _SCHEMA_SQL.splitlines()
+ if not any(name in line for name in
+ ("base_revision", "training_data_sha256"))
+ )
+ with sqlite3.connect(db) as conn:
+ conn.executescript(legacy)
+ conn.execute(
+ "INSERT INTO runs(run_id, created_at, config_json) VALUES (?, ?, ?)",
+ ("legacy", "2020-01-01", json.dumps({"base": BASE})),
+ )
+ for _ in range(2):
+ tracker = ExperimentTracker(db)
+ row = tracker.get_run("legacy")
+ assert row["base_revision"] is None
+ assert row["base_revision_source"] is None
+ assert row["training_data_sha256"] is None
+ tracker.close()
+
+
+def test_concurrent_database_initialization_preserves_recorded_identity(tmp_path):
+ db = tmp_path / "concurrent.db"
+ tracker = ExperimentTracker(db)
+ run_id = _run(tracker)
+ tracker.record_base_revision(run_id, revision=REVISION, source="hub_commit")
+ tracker.close()
+
+ def reopen(_):
+ tracker = ExperimentTracker(db)
+ try:
+ return tracker.get_run(run_id)["base_revision"]
+ finally:
+ tracker.close()
+
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ assert list(pool.map(reopen, range(8))) == [REVISION] * 8
+
+
+def test_concurrent_upgrade_of_legacy_database_leaves_old_identity_unknown(tmp_path):
+ from soup_cli.experiment.tracker import _SCHEMA_SQL
+
+ db = tmp_path / "legacy-concurrent.db"
+ legacy = "\n".join(
+ line for line in _SCHEMA_SQL.splitlines()
+ if not any(name in line for name in ("base_revision", "training_data_sha256"))
+ )
+ with sqlite3.connect(db) as conn:
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.executescript(legacy)
+ conn.execute(
+ "INSERT INTO runs(run_id, created_at, config_json) VALUES ('old', '2020', '{}')",
+ )
+
+ def upgrade(_):
+ tracker = ExperimentTracker(db)
+ try:
+ row = tracker.get_run("old")
+ return row["base_revision"], row["base_revision_source"], row["training_data_sha256"]
+ finally:
+ tracker.close()
+
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ assert list(pool.map(upgrade, range(8))) == [(None, None, None)] * 8
+
+
+def test_restarted_run_does_not_reuse_the_previous_identity(tmp_path):
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ run_id = _run(tracker)
+ tracker.record_base_revision(run_id, revision=REVISION, source="hub_commit")
+ tracker.start_run({"base": "other/base"}, "cpu", "CPU", {}, run_id=run_id)
+ row = tracker.get_run(run_id)
+ assert row["base_model"] == "other/base"
+ assert row["base_revision"] is None
+ assert row["base_revision_source"] is None
+ assert row["training_data_sha256"] is None
+ tracker.close()
+
+
+def test_moving_hub_resolves_once_for_all_base_loads(monkeypatch):
+ from soup_cli.utils import run_provenance as provenance
+
+ probe = Mock(side_effect=[SimpleNamespace(sha=REVISION), SimpleNamespace(sha=OTHER_REVISION)])
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(model_info=probe))
+ identity = provenance.BaseRevision(BASE)
+ with provenance.base_revision_scope(identity):
+ # Model, tokenizer, processor and config all use exactly the same execution identity.
+ for _ in range(4):
+ assert provenance.base_revision_kwargs(BASE) == {"revision": REVISION}
+ assert provenance.base_revision_kwargs("different/teacher") == {}
+ assert provenance.base_revision_kwargs("different/reward") == {}
+ assert provenance.base_revision_kwargs(BASE) == {}
+ assert probe.call_count == 1
+ assert identity.revision == REVISION
+ assert identity.source == "hub_commit"
+
+
[email protected]("mode", ["offline", "failed", "invalid-sha", "unsupported"])
+def test_unknown_identity_preserves_existing_loader_flow(monkeypatch, mode):
+ from soup_cli.utils import run_provenance as provenance
+
+ probe = Mock(return_value=SimpleNamespace(sha="main"))
+ if mode == "failed":
+ probe.side_effect = OSError("offline, with a sensitive diagnostic")
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(model_info=probe))
+ if mode == "offline":
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ identity = provenance.BaseRevision(BASE, binding_supported=mode != "unsupported")
+ with provenance.base_revision_scope(identity):
+ assert provenance.base_revision_kwargs(BASE) == {}
+ assert provenance.base_revision_kwargs(BASE) == {}
+ assert identity.revision is None
+ assert identity.source != "hub_commit"
+ assert probe.call_count == (0 if mode in {"offline", "unsupported"} else 1)
+
+
+def test_scopes_restore_identity_after_nested_run_and_exception(monkeypatch):
+ from soup_cli.utils import run_provenance as provenance
+
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(
+ model_info=lambda repo, **kwargs: SimpleNamespace(
+ sha=REVISION if repo == BASE else OTHER_REVISION,
+ ),
+ ))
+ with provenance.base_revision_scope(provenance.BaseRevision(BASE)):
+ with pytest.raises(RuntimeError), provenance.base_revision_scope(
+ provenance.BaseRevision("other/base"),
+ ):
+ assert provenance.base_revision_kwargs("other/base") == {"revision": OTHER_REVISION}
+ raise RuntimeError("aborted inner run")
+ assert provenance.base_revision_kwargs(BASE) == {"revision": REVISION}
+ assert provenance.base_revision_kwargs(BASE) == {}
+
+
+def test_cache_path_identity_is_metadata_and_does_not_pin_local_bytes(tmp_path, monkeypatch):
+ from soup_cli.utils import run_provenance as provenance
+
+ snapshot = tmp_path / "models--owner--base" / "snapshots" / REVISION
+ snapshot.mkdir(parents=True)
+ monkeypatch.setattr(provenance, "get_hf_api", Mock(side_effect=AssertionError("no network")))
+ identity = provenance.BaseRevision(str(snapshot))
+ with provenance.base_revision_scope(identity):
+ assert provenance.base_revision_kwargs(str(snapshot)) == {}
+ assert identity.revision == REVISION
+ assert identity.source == "cache_path"
+ provenance.write_run_provenance(snapshot, identity.metadata("run-cache"))
+ assert provenance.recorded_base_kwargs(str(snapshot), str(snapshot)) == {}
+ assert provenance.BaseRevision(str(tmp_path)).revision is None
+
+
+def test_copied_adapter_recovers_revision_without_original_database(tmp_path, monkeypatch):
+ from soup_cli.utils import run_provenance as provenance
+
+ source = tmp_path / "original"
+ source.mkdir()
+ identity = provenance.BaseRevision(BASE)
+ identity.revision, identity.source = REVISION, "hub_commit"
+ provenance.write_run_provenance(source, identity.metadata("run-original"))
+ copied = tmp_path / "copied"
+ shutil.copytree(source, copied)
+ shutil.rmtree(source)
+ monkeypatch.setattr(provenance, "get_hf_api", Mock(side_effect=AssertionError("no lookup")))
+ assert provenance.recorded_base_kwargs(str(copied), BASE) == {"revision": REVISION}
+ assert provenance.read_run_provenance(copied)["run_id"] == "run-original"
+ # Legacy adapters and explicit --base overrides preserve their supported behavior.
+ assert provenance.recorded_base_kwargs(str(copied), "other/base") == {}
+ assert provenance.recorded_base_kwargs(str(tmp_path / "legacy"), BASE) == {}
+
+
+ "payload", ["not JSON", "[]", "{}", '{"schema_version":999}', "x" * 70000],
+ ids=["syntax", "list", "missing", "future-version", "oversized"],
+)
+def test_unreadable_or_invalid_sidecar_stays_unknown(tmp_path, payload):
+ from soup_cli.utils import run_provenance as provenance
+
+ (tmp_path / provenance.PROVENANCE_FILENAME).write_text(payload, encoding="utf-8")
+ assert provenance.recorded_base_kwargs(str(tmp_path), BASE) == {}
+
+
+def test_oversized_sidecar_with_a_valid_json_prefix_is_not_accepted(tmp_path):
+ from soup_cli.utils import run_provenance as provenance
+
+ identity = provenance.BaseRevision(BASE)
+ identity.revision, identity.source = REVISION, "hub_commit"
+ payload = json.dumps(identity.metadata("run-1")) + " " * 70000
+ (tmp_path / provenance.PROVENANCE_FILENAME).write_text(payload, encoding="utf-8")
+ assert provenance.recorded_base_kwargs(str(tmp_path), BASE) == {}
+
+
+def test_registration_copies_historical_identity_without_reopening_data(tmp_path):
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ store = RegistryStore(tmp_path / "registry.db")
+ run_id = _run(tracker)
+ tracker.record_base_revision(run_id, revision=REVISION, source="hub_commit")
+ tracker._get_conn().execute(
+ "UPDATE runs SET training_data_sha256=? WHERE run_id=?", (TRAINING_HASH, run_id),
+ )
+ tracker._get_conn().commit()
+ entry = store.get(store.register_from_run(tracker, run_id, name="model", tag="v1"))
+ assert entry["base_revision"] == REVISION
+ assert entry["base_revision_source"] == "hub_commit"
+ assert entry["training_data_sha256"] == TRAINING_HASH
+ assert entry["data_hash"] == TRAINING_HASH
+ assert entry["entry_hash"] == hash_entry(
+ config={"base": BASE, "task": "sft"}, data_path=None, base_model=BASE,
+ data_sha256=TRAINING_HASH, base_revision=REVISION, base_revision_source="hub_commit",
+ )
+ store.close()
+ tracker.close()
+
+
[email protected]("source_state", ["changed", "deleted"])
+def test_registration_keeps_training_digest_after_source_mutation(tmp_path, source_state):
+ data = tmp_path / "train.jsonl"
+ data.write_text('{"text":"original training bytes"}\n', encoding="utf-8")
+ historical = hash_file(str(data))
+ config = {"base": BASE, "task": "sft", "data": {"train": str(data)}}
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ try:
+ run_id = tracker.start_run(config, "cpu", "CPU", {})
+ tracker._get_conn().execute(
+ "UPDATE runs SET training_data_sha256=? WHERE run_id=?", (historical, run_id),
+ )
+ tracker._get_conn().commit()
+ if source_state == "changed":
+ data.write_text("different bytes after training\n", encoding="utf-8")
+ assert hash_file(str(data)) != historical
+ else:
+ data.unlink()
+ with RegistryStore(tmp_path / "registry.db") as store:
+ entry = store.get(store.register_from_run(tracker, run_id, name="model", tag="v1"))
+ assert entry["training_data_sha256"] == historical
+ assert entry["data_hash"] == historical
+ assert entry["entry_hash"] == hash_entry(
+ config=config, data_path=None, base_model=BASE, data_sha256=historical,
+ )
+ finally:
+ tracker.close()
+
+
+ "adapter_config, expected",
+ [({"base_model_name_or_path": BASE}, BASE),
+ ({"base_model_name_or_path": BASE, "revision": REVISION}, BASE),
+ ({"base_model_name_or_path": "other/base"}, None),
+ ({"base_model_name_or_path": BASE, "revision": OTHER_REVISION}, None),
+ ({"base_model_name_or_path": BASE, "revision": "main"}, None),
+ ({}, None), ([], None)],
+)
+def test_implicit_adapter_base_requires_matching_local_config(tmp_path, adapter_config, expected):
+ from soup_cli.utils import run_provenance as provenance
+
+ identity = provenance.BaseRevision(BASE)
+ identity.revision, identity.source = REVISION, "hub_commit"
+ provenance.write_run_provenance(tmp_path, identity.metadata("run-original"))
+ (tmp_path / "adapter_config.json").write_text(json.dumps(adapter_config), encoding="utf-8")
+ assert provenance.recorded_adapter_base(str(tmp_path)) == expected
+
+
+def test_implicit_adapter_base_preserves_missing_malformed_and_oversized_config(tmp_path):
+ from soup_cli.utils import run_provenance as provenance
+
+ identity = provenance.BaseRevision(BASE)
+ identity.revision, identity.source = REVISION, "hub_commit"
+ provenance.write_run_provenance(tmp_path, identity.metadata("run-original"))
+ assert provenance.recorded_adapter_base(str(tmp_path)) is None
+ for payload in ("not JSON", json.dumps({"base_model_name_or_path": BASE}) + " " * 70000):
+ (tmp_path / "adapter_config.json").write_text(payload, encoding="utf-8")
+ assert provenance.recorded_adapter_base(str(tmp_path)) is None
+
+
+def test_explicit_registered_file_takes_precedence_without_erasing_training_hash(tmp_path):
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ store = RegistryStore(tmp_path / "registry.db")
+ run_id = _run(tracker)
+ tracker._get_conn().execute(
+ "UPDATE runs SET training_data_sha256=? WHERE run_id=?", (TRAINING_HASH, run_id),
+ )
+ tracker._get_conn().commit()
+ data = tmp_path / "registered.jsonl"
+ data.write_text("changed after training\n", encoding="utf-8")
+ entry = store.get(store.register_from_run(
+ tracker, run_id, name="model", tag="v1", data_path=str(data),
+ ))
+ assert entry["data_hash"] == hash_file(str(data))
+ assert entry["training_data_sha256"] == TRAINING_HASH
+ assert entry["entry_hash"] == hash_entry(
+ config={"base": BASE, "task": "sft"}, data_path=str(data), base_model=BASE,
+ )
+ store.close()
+ tracker.close()
+
+
+def test_legacy_registration_keeps_original_hash_and_config_schema(tmp_path):
+ from soup_cli.config.schema import SoupConfig
+
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ store = RegistryStore(tmp_path / "registry.db")
+ run_id = _run(tracker)
+ entry = store.get(store.register_from_run(tracker, run_id, name="model", tag="v1"))
+ assert entry["data_hash"] is None
+ assert entry["base_revision"] is None
+ assert entry["entry_hash"] == hash_entry(
+ config={"base": BASE, "task": "sft"}, data_path=None, base_model=BASE,
+ )
+ assert "base_revision" not in SoupConfig.model_fields
+ assert "training_data_sha256" not in SoupConfig.model_fields
+ store.close()
+ tracker.close()
+
+
+def test_registry_retries_compare_revision_and_historical_training_identity(tmp_path):
+ from soup_cli.registry.store import IdempotencyConflictError
+
+ registered = tmp_path / "registered.jsonl"
+ registered.write_text("registered input\n", encoding="utf-8")
+ with RegistryStore(tmp_path / "registry.db") as store:
+ request = dict(
+ name="model", tag="v1", base_model=BASE, task="sft", run_id="run-1",
+ config={}, base_revision=REVISION, base_revision_source="hub_commit",
+ training_data_sha256=TRAINING_HASH, idempotency_key="job-1",
+ data_path=str(registered),
+ )
+ entry_id = store.push(**request)
+ assert store.push(**request) == entry_id
+ with pytest.raises(IdempotencyConflictError):
+ store.push(**{**request, "base_revision": OTHER_REVISION})
+ with pytest.raises(IdempotencyConflictError):
+ store.push(**{**request, "training_data_sha256": "d" * 64})
+ with pytest.raises(IdempotencyConflictError):
+ store.push(**{**request, "base_revision_source": "cache_path"})
+
+
+def test_entry_hash_uses_the_same_registered_digest_that_is_stored(tmp_path, monkeypatch):
+ from soup_cli.registry import store as store_module
+
+ file_hash = Mock(side_effect=[TRAINING_HASH, "d" * 64])
+ monkeypatch.setattr(store_module, "hash_file", file_hash)
+ with RegistryStore(tmp_path / "registry.db") as store:
+ entry = store.get(store.push(
+ name="model", tag="v1", base_model=BASE, task="sft", run_id=None,
+ config={}, data_path="file-that-may-change-between-reads",
+ ))
+ assert file_hash.call_count == 1
+ assert entry["data_hash"] == TRAINING_HASH
+ assert entry["entry_hash"] == hash_entry(
+ config={}, data_path=None, base_model=BASE, data_sha256=TRAINING_HASH,
+ )
+
+
+def test_entry_fingerprint_binds_both_recorded_identities_and_the_source():
+ envelope = {
+ "config": '{"base":"owner/base"}', "base_model": BASE,
+ "data_sha256": TRAINING_HASH, "base_revision": REVISION,
+ "base_revision_source": "hub_commit",
+ }
+ expected = hashlib.sha256(
+ json.dumps(envelope, sort_keys=True, separators=(",", ":")).encode("utf-8"),
+ ).hexdigest()
+ assert hash_entry(
+ config={"base": BASE}, data_path=None, base_model=BASE, data_sha256=TRAINING_HASH,
+ base_revision=REVISION, base_revision_source="hub_commit",
+ ) == expected
+
+
+def test_recorded_revision_and_source_are_visible_in_run_and_registry_cli(tmp_path, monkeypatch):
+ from typer.testing import CliRunner
+
+ from soup_cli.cli import app
+ from tests.conftest import strip_ansi
+
+ monkeypatch.setenv("SOUP_DB_PATH", str(tmp_path / "runs.db"))
+ monkeypatch.setenv("SOUP_REGISTRY_DB_PATH", str(tmp_path / "registry.db"))
+ tracker = ExperimentTracker(tmp_path / "runs.db")
+ run_id = _run(tracker)
+ tracker.record_base_revision(run_id, revision=REVISION, source="hub_commit")
+ tracker.finish_run(run_id, 1.0, 0.5, 1, 1.0, str(tmp_path / "out"))
+ with RegistryStore(tmp_path / "registry.db") as store:
+ entry_id = store.register_from_run(tracker, run_id, name="model", tag="v1")
+ tracker.close()
+ for args in (["runs", "show", run_id], ["registry", "show", entry_id]):
+ result = CliRunner().invoke(app, args)
+ assert result.exit_code == 0, (result.output, result.exception)
+ output = strip_ansi(result.output)
+ assert REVISION in output
+ assert "hub_commit" in output