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.

bench: publish determinism reconstruction harness (#1286)

Samarth Mukhijaad1b27566f35
diff --git a/benchmarks/README.md b/benchmarks/README.md
index b6f533a2..d3f31b69 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -98,6 +98,7 @@ only in a scratchpad on a machine that is gone, which is
| [issue725_lorafa_operating_point.py](harness/issue725_lorafa_operating_point.py) | #725 / [gate-725-lorafa-operating-point.md](gate-725-lorafa-operating-point.md) | Measures trainable parameter counts, AdamW state tensor allocations, step latency, and multi-step loss finiteness between LoRA and LoRA-FA | ~20 s, CPU or GPU, no downloads |
| [`ab_burn_in_sweep.py`](harness/ab_burn_in_sweep.py) | [#1227](https://github.com/MakazhanAlpamys/Soup/issues/1227) / [`gate-1227-ab-burn-in.md`](gate-1227-ab-burn-in.md) | What false-positive rate does `soup ab`'s burn-in leave when the test is re-run after every new pair? A vectorised H0 simulation of the shipped statistic, checked against `_verdict_from_summary` first, by effect_size / sigma, burn-in, alpha and horizon; picks `BURN_IN_ROWS_BY_ALPHA` | CPU + numpy; ~55 s per ratio at 100,000 runs over 1000 rows; `run` writes JSON parts, `report` merges them |
| [`head_prefetch_ab.py`](harness/head_prefetch_ab.py) | [#1174](https://github.com/MakazhanAlpamys/Soup/issues/1174) / [#1258](https://github.com/MakazhanAlpamys/Soup/pull/1258) | Interleaved A/B, in one process on one model, of where the output head's load into the shared large-layer slot is issued: `StreamPrefetcher.head_prefetch_layer` at `None` (the last decoder layer, the original timing) against a chosen layer (`0`, right after the embedding lookup). Judges each arm by the step's TOTAL wait from the committed `stream_probe.Instruments` brackets, plus per-group medians (embedding, head, layer 0, other decoder layers), since a decoder entry behind the head on the copy stream can get worse while the head's own entry improves. Covers both tiers, `--read-ahead`, and a `--step-shape preference` (a no-grad forward first) for the disk-tier case where the reader's queue gets replanned. Refuses to run on a tree without `head_prefetch_layer` instead of comparing an arm with itself; the JSON records `soup_cli_file` and `git_sha`, the tree it measured | CUDA GPU; model weights; a few minutes per arm pair |
+| [`determinism.py`](harness/determinism.py) | STEP 2b / Measurements 1-2 | Historical reconstruction that measures forward, backward repetitions 1 and 3, and trained loss-curve reproducibility in-process against a resident NF4 reference; optional JSON replay remains separate from measurement | CUDA measurement requires the recorded H100-class stack and checkpoint; CPU tests cover the real measurement and invalid-measurement guards; empty overlap, non-finite values, missing measurements, or absent asymmetry fail |
| [`ab_nig_sweep.py`](harness/ab_nig_sweep.py) | [#1265](https://github.com/MakazhanAlpamys/Soup/issues/1265) / [`gate-1265-ab-nig.md`](gate-1265-ab-nig.md) | Type-I and power of `soup ab`'s NIG mixture under a peek after every pair, side by side with the #1227 burn-in design, by effect_size / sigma, held-out rows, alpha and horizon; checked against `_nig_log_bayes_factor` and `msprt_step` first; picks `PRIOR_SCALE_ROWS` | CPU + numpy; ~350 s per ratio at 100,000 H0 runs over 1000 rows; `run --mode h0/h1` writes JSON parts, `report` merges them |
| [`ab_cs_accept_sweep.py`](harness/ab_cs_accept_sweep.py) | [#1418](https://github.com/MakazhanAlpamys/Soup/issues/1418) / [`gate-1418-ab-cs-accept.md`](gate-1418-ab-cs-accept.md) | Time to `accept_h0` under H0 and wrong `accept_h0` under H1 for `soup ab`'s confidence-sequence accept rule against #1265's, at level beta or alpha and with or without the accept hold; replays #1265's seeded runs and checks its counts against that record; checked against `_nig_confidence_half_width` and `msprt_step` first | CPU + numpy; ~430-600 s per ratio at 100,000 H0 runs over 1000 rows; `run --mode h0/h1` writes JSON parts, `report` merges them, `check` re-runs only the self-check |
diff --git a/benchmarks/harness/determinism.py b/benchmarks/harness/determinism.py
new file mode 100644
index 00000000..7ec79c62
--- /dev/null
+++ b/benchmarks/harness/determinism.py
@@ -0,0 +1,275 @@
+#!/usr/bin/env python3
+"""Measure the STEP 2b forward/backward/curve determinism protocol.
+
+This is a historical reconstruction. The record's meaningful pattern is an
+exact forward, a deterministic resident backward, and a non-deterministic
+streamed backward/curve. The JSON input mode keeps replay separate from a
+claim that this machine performed CUDA measurement; the normal ``--weights``
+path performs the measurement in-process.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+HARNESS_DIR = Path(__file__).resolve().parent
+if str(HARNESS_DIR) not in sys.path:
+ sys.path.insert(0, str(HARNESS_DIR))
+
+
+class MeasurementInvalidError(RuntimeError):
+ """The supplied determinism record cannot support a verdict."""
+
+
+def curve_diff(first: list[float], second: list[float]) -> tuple[bool, float, float]:
+ if len(first) != len(second) or not first:
+ raise MeasurementInvalidError("loss curves must be non-empty and equal length")
+ max_abs = 0.0
+ max_rel = 0.0
+ for left, right in zip(first, second, strict=True):
+ if not math.isfinite(left) or not math.isfinite(right):
+ raise MeasurementInvalidError("loss curve contains non-finite values")
+ difference = abs(left - right)
+ max_abs = max(max_abs, difference)
+ max_rel = max(max_rel, difference / max(abs(right), 1.0e-30))
+ return first == second, max_abs, max_rel
+
+
+def _finite(values: list[float], label: str) -> None:
+ if not values or any(not math.isfinite(value) for value in values):
+ raise MeasurementInvalidError(f"{label} must be non-empty and finite")
+
+
+def determinism_verdict(record: dict[str, Any]) -> bool:
+ """Require the recorded streamed-vs-resident determinism asymmetry."""
+ required = (
+ "streamed_forward_equal",
+ "resident_forward_equal",
+ "streamed_gradient_equal",
+ "resident_gradient_equal",
+ "streamed_curve_equal",
+ "resident_curve_equal",
+ )
+ if any(key not in record for key in required):
+ raise MeasurementInvalidError("determinism record is missing fields")
+ for label in ("streamed_losses", "resident_losses"):
+ _finite(list(record.get(label, [])), label)
+ values = [record[key] for key in required]
+ if any(not isinstance(value, bool) for value in values):
+ raise MeasurementInvalidError("determinism flags must be booleans")
+ return (
+ record["streamed_forward_equal"]
+ and record["resident_forward_equal"]
+ and not record["streamed_gradient_equal"]
+ and record["resident_gradient_equal"]
+ and not record["streamed_curve_equal"]
+ and record["resident_curve_equal"]
+ )
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Measure the STEP 2b determinism reconstruction."
+ )
+ parser.add_argument(
+ "--records",
+ type=Path,
+ help="replay a previously measured JSON record instead of measuring",
+ )
+ parser.add_argument("--weights", type=Path)
+ parser.add_argument("--shards", type=Path, default=Path("./soup-shards"))
+ parser.add_argument("--seq", type=int, default=128)
+ parser.add_argument("--buffers", type=int, default=2)
+ parser.add_argument("--self-test", action="store_true")
+ return parser.parse_args()
+
+
+def _gradient_map(model: Any) -> dict[str, Any]:
+ return {
+ name: parameter.grad.detach().clone()
+ for name, parameter in model.named_parameters()
+ if "lora_" in name and parameter.grad is not None
+ }
+
+
+def _finite_tensors(values: dict[str, Any], label: str) -> None:
+ import torch
+
+ if not values or any(not torch.isfinite(value).all() for value in values.values()):
+ raise MeasurementInvalidError(f"{label} contains no finite gradients")
+
+
+def measure_models(
+ streamed: Any,
+ resident: Any,
+ input_ids: Any,
+ curve_batches: list[Any],
+) -> dict[str, Any]:
+ """Run forward, repeated backward, and curve measurements on both models."""
+ import bitexact
+ import torch
+
+ from soup_cli.utils.layer_stream_runtime import assert_canonical_parameters_intersect
+
+ assert_canonical_parameters_intersect(streamed, resident)
+
+ def forward(model: Any) -> Any:
+ return model(input_ids=input_ids, labels=input_ids).logits.detach().clone()
+
+ streamed_forward = torch.equal(forward(streamed), forward(streamed))
+ resident_forward = torch.equal(forward(resident), forward(resident))
+ gradients: dict[str, list[dict[str, Any]]] = {"streamed": [], "resident": []}
+ losses: dict[str, list[float]] = {"streamed": [], "resident": []}
+ for name, model in (("streamed", streamed), ("resident", resident)):
+ for _ in range(3):
+ model.zero_grad(set_to_none=True)
+ loss = model(input_ids=input_ids, labels=input_ids).loss
+ if not torch.isfinite(loss).all():
+ raise MeasurementInvalidError(f"{name} loss is non-finite")
+ losses[name].append(float(loss.detach()))
+ loss.backward()
+ current = _gradient_map(model)
+ _finite_tensors(current, f"{name} gradients")
+ gradients[name].append(current)
+
+ def equal(left: dict[str, Any], right: dict[str, Any]) -> bool:
+ if set(left) != set(right):
+ raise MeasurementInvalidError("gradient parameter sets differ")
+ return all(torch.equal(left[key], right[key]) for key in left)
+
+ def curve_pair(model: Any) -> tuple[list[float], list[float]]:
+ state = {
+ name: parameter.detach().clone()
+ for name, parameter in model.named_parameters()
+ if "lora_" in name
+ }
+ if not state:
+ raise MeasurementInvalidError("curve model has no LoRA parameters")
+
+ def restore() -> None:
+ with torch.no_grad():
+ parameters = dict(model.named_parameters())
+ for name, value in state.items():
+ parameters[name].copy_(value)
+
+ try:
+ first = bitexact.train_curve(model, curve_batches)
+ restore()
+ second = bitexact.train_curve(model, curve_batches)
+ curve_diff(first, second)
+ return first, second
+ finally:
+ restore()
+
+ streamed_curve = curve_pair(streamed)
+ resident_curve = curve_pair(resident)
+ return {
+ "streamed_forward_equal": streamed_forward,
+ "resident_forward_equal": resident_forward,
+ "streamed_gradient_equal": equal(
+ gradients["streamed"][0], gradients["streamed"][2]
+ ),
+ "resident_gradient_equal": equal(
+ gradients["resident"][0], gradients["resident"][2]
+ ),
+ "streamed_curve_equal": curve_diff(*streamed_curve)[0],
+ "resident_curve_equal": curve_diff(*resident_curve)[0],
+ "streamed_losses": losses["streamed"],
+ "resident_losses": losses["resident"],
+ }
+
+
+def run_measurement(args: argparse.Namespace) -> int:
+ if args.weights is None:
+ print("ERROR: --weights is required for an in-process measurement")
+ return 2
+ import bitexact
+ import torch
+ from mechanism_cost import build_streamed_arm, prepare_shards
+
+ from soup_cli.utils.spectrum_scan import resolve_model_weights
+
+ if not torch.cuda.is_available():
+ print("SKIP: CUDA is required for the measurement path")
+ return 0
+ weights = resolve_model_weights(str(args.weights))
+ shards = str(args.shards.expanduser().resolve())
+ index, arch = prepare_shards(weights, shards)
+ streamed, runtime, restore = build_streamed_arm(
+ weights, shards, index, arch, "control", args.buffers
+ )
+ resident = None
+ try:
+ resident = bitexact.load_resident_reference(weights, "nf4")
+ bitexact.make_non_vacuous_lora(streamed)
+ bitexact.copy_lora(streamed, resident)
+ generator = torch.Generator(device="cuda").manual_seed(17)
+ inputs = torch.randint(
+ 0, resident.config.vocab_size,
+ (1, args.seq),
+ generator=generator,
+ device="cuda",
+ )
+ batches = [inputs.clone() for _ in range(5)]
+ record = measure_models(streamed, resident, inputs, batches)
+ print(json.dumps(record, indent=2, sort_keys=True))
+ ok = determinism_verdict(record)
+ print(
+ "RESULT: historical determinism pattern reproduced"
+ if ok
+ else "ERROR: historical determinism pattern not reproduced"
+ )
+ return 0 if ok else 1
+ finally:
+ if resident is not None:
+ del resident
+ runtime.close()
+ restore()
+
+
+def run_self_test() -> int:
+ record = {
+ "streamed_forward_equal": True,
+ "resident_forward_equal": True,
+ "streamed_gradient_equal": False,
+ "resident_gradient_equal": True,
+ "streamed_curve_equal": False,
+ "resident_curve_equal": True,
+ "streamed_losses": [1.0, 0.9],
+ "resident_losses": [1.0, 0.9],
+ }
+ assert determinism_verdict(record)
+ record["streamed_gradient_equal"] = True
+ assert not determinism_verdict(record)
+ print("PASS: determinism verdict distinguishes streamed instability from control")
+ return 0
+
+
+def main() -> int:
+ args = parse_args()
+ try:
+ if args.self_test:
+ return run_self_test()
+ if args.records is None:
+ return run_measurement(args)
+ record = json.loads(args.records.read_text(encoding="utf-8"))
+ if not determinism_verdict(record):
+ print("ERROR: historical determinism pattern not reproduced")
+ return 1
+ print("RESULT: historical determinism pattern reproduced")
+ return 0
+ except (MeasurementInvalidError, ValueError) as exc:
+ print(f"ERROR: invalid measurement: {exc}")
+ return 3
+ except (OSError, json.JSONDecodeError, TypeError) as exc:
+ print(f"ERROR: invalid records: {exc}")
+ return 2
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_determinism.py b/tests/test_determinism.py
new file mode 100644
index 00000000..982aadda
--- /dev/null
+++ b/tests/test_determinism.py
@@ -0,0 +1,47 @@
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "determinism.py"
+SPEC = importlib.util.spec_from_file_location("determinism", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+module = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(module)
+
+
+def record():
+ return {
+ "streamed_forward_equal": True,
+ "resident_forward_equal": True,
+ "streamed_gradient_equal": False,
+ "resident_gradient_equal": True,
+ "streamed_curve_equal": False,
+ "resident_curve_equal": True,
+ "streamed_losses": [1.0, 0.9],
+ "resident_losses": [1.0, 0.9],
+ }
+
+
+def test_expected_pattern_passes():
+ assert module.determinism_verdict(record())
+
+
+def test_stable_streamed_control_fails():
+ item = record()
+ item["streamed_curve_equal"] = True
+ assert not module.determinism_verdict(item)
+
+
+def test_missing_comparison_fails():
+ item = record()
+ del item["resident_gradient_equal"]
+ with pytest.raises(module.MeasurementInvalidError):
+ module.determinism_verdict(item)
+
+
+def test_nonfinite_losses_fail():
+ item = record()
+ item["streamed_losses"] = [float("nan")]
+ with pytest.raises(module.MeasurementInvalidError):
+ module.determinism_verdict(item)
diff --git a/tests/test_issue379_determinism.py b/tests/test_issue379_determinism.py
new file mode 100644
index 00000000..f90d302c
--- /dev/null
+++ b/tests/test_issue379_determinism.py
@@ -0,0 +1,68 @@
+"""CPU-testable verdict guards for the determinism reconstruction."""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "determinism.py"
+SPEC = importlib.util.spec_from_file_location("determinism_issue379", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+module = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(module)
+
+
+def record():
+ return {
+ "streamed_forward_equal": True,
+ "resident_forward_equal": True,
+ "streamed_gradient_equal": False,
+ "resident_gradient_equal": True,
+ "streamed_curve_equal": False,
+ "resident_curve_equal": True,
+ "streamed_losses": [1.0, 0.9],
+ "resident_losses": [1.0, 0.9],
+ }
+
+
+def test_expected_measurement_pattern_passes():
+ assert module.determinism_verdict(record())
+
+
+ "streamed_forward_equal",
+ "resident_forward_equal",
+ "streamed_gradient_equal",
+ "resident_gradient_equal",
+ "streamed_curve_equal",
+ "resident_curve_equal",
+])
+def test_each_verdict_clause_is_load_bearing(field):
+ item = record()
+ item[field] = not item[field]
+ assert not module.determinism_verdict(item)
+
+
+def test_non_boolean_flags_are_not_truthy_measurements():
+ item = record()
+ item["streamed_curve_equal"] = "false"
+ with pytest.raises(module.MeasurementInvalidError, match="booleans"):
+ module.determinism_verdict(item)
+
+
+def test_empty_and_nonfinite_measurements_fail():
+ item = record()
+ item["streamed_losses"] = []
+ with pytest.raises(module.MeasurementInvalidError):
+ module.determinism_verdict(item)
+ item = record()
+ item["resident_losses"] = [float("nan")]
+ with pytest.raises(module.MeasurementInvalidError):
+ module.determinism_verdict(item)
+
+
+def test_curve_diff_rejects_degenerate_or_nonfinite_data():
+ with pytest.raises(module.MeasurementInvalidError):
+ module.curve_diff([], [])
+ with pytest.raises(module.MeasurementInvalidError):
+ module.curve_diff([1.0], [float("inf")])
diff --git a/tests/test_issue379_determinism_main.py b/tests/test_issue379_determinism_main.py
new file mode 100644
index 00000000..923e9479
--- /dev/null
+++ b/tests/test_issue379_determinism_main.py
@@ -0,0 +1,96 @@
+"""CPU tests of determinism.main() through the real measurement path."""
+
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+HARNESS = Path(__file__).parents[1] / "benchmarks" / "harness"
+sys.path.insert(0, str(HARNESS))
+import bitexact # noqa: E402
+import mechanism_cost # noqa: E402
+
+from tests.test_issue379_determinism_measure import VOCAB, _Out, _Toy, module # noqa: E402
+
+_REAL_GENERATOR = torch.Generator
+_REAL_RANDINT = torch.randint
+
+
+class _CpuGenerator(_REAL_GENERATOR):
+ def __new__(cls, device="cpu"):
+ return _REAL_GENERATOR.__new__(cls)
+
+
+class _NanLoss(_Toy):
+ def forward(self, input_ids, labels):
+ out = super().forward(input_ids, labels)
+ return _Out(out.logits, out.loss * float("nan"))
+
+
+class _Runtime:
+ def close(self):
+ pass
+
+
+def _run(monkeypatch, streamed, resident=None):
+ resident = resident if resident is not None else _Toy(defect=False)
+ streamed.config = resident.config = SimpleNamespace(vocab_size=VOCAB)
+ seen = {"arms": [], "restored": 0}
+ monkeypatch.setattr(torch, "Generator", _CpuGenerator)
+ monkeypatch.setattr(
+ torch,
+ "randint",
+ lambda *args, **kwargs: _REAL_RANDINT(
+ *args, **{key: value for key, value in kwargs.items() if key != "device"}
+ ),
+ )
+ monkeypatch.setattr(
+ mechanism_cost, "prepare_shards", lambda weights, shards: ({}, "llama")
+ )
+
+ def build(weights, shards, index, arch, arm, buffers):
+ seen["arms"].append(arm)
+ return streamed, _Runtime(), lambda: seen.__setitem__(
+ "restored", seen["restored"] + 1
+ )
+
+ monkeypatch.setattr(mechanism_cost, "build_streamed_arm", build)
+ monkeypatch.setattr(bitexact, "load_resident_reference", lambda weights, quant: resident)
+ import soup_cli.utils.spectrum_scan as scan
+
+ monkeypatch.setattr(scan, "resolve_model_weights", lambda value: value)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["determinism.py", "--weights", "w", "--shards", "s", "--seq", "8"],
+ )
+ calls = {"n": 0}
+
+ def available_once():
+ calls["n"] += 1
+ return calls["n"] == 1
+
+ monkeypatch.setattr(torch.cuda, "is_available", available_once)
+ return module.main(), seen
+
+
+def test_record_pattern_is_reproduced_with_the_historical_control(monkeypatch):
+ code, seen = _run(monkeypatch, _Toy(defect=True))
+ assert code == 0
+ assert seen["arms"] == ["control"]
+ assert seen["restored"] == 1
+
+
+def test_healthy_pair_is_not_reproduced(monkeypatch):
+ code, seen = _run(monkeypatch, _Toy(defect=False))
+ assert code == 1
+ assert seen["restored"] == 1
+
+
+def test_nan_loss_is_an_invalid_measurement(monkeypatch):
+ code, seen = _run(monkeypatch, _NanLoss(defect=True))
+ assert code == 3
+ assert seen["restored"] == 1
diff --git a/tests/test_issue379_determinism_measure.py b/tests/test_issue379_determinism_measure.py
new file mode 100644
index 00000000..09cf0553
--- /dev/null
+++ b/tests/test_issue379_determinism_measure.py
@@ -0,0 +1,119 @@
+"""CPU tests of determinism.measure_models() with toy LoRA models."""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+from torch import nn # noqa: E402
+
+MODULE_PATH = Path(__file__).parents[1] / "benchmarks" / "harness" / "determinism.py"
+SPEC = importlib.util.spec_from_file_location("determinism_measure", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+module = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(module)
+
+VOCAB = 64
+
+
+class _GradScale(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, factor):
+ ctx.factor = factor
+ return x.view_as(x)
+
+ @staticmethod
+ def backward(ctx, grad):
+ return grad * ctx.factor, None
+
+
+class _Out:
+ def __init__(self, logits, loss):
+ self.logits = logits
+ self.loss = loss
+
+
+class _Toy(nn.Module):
+ def __init__(self, defect, layers=6, hidden=16):
+ super().__init__()
+ torch.manual_seed(0)
+ self.embed = nn.Embedding(VOCAB, hidden).requires_grad_(False)
+ self.base = nn.ModuleList(
+ nn.Linear(hidden, hidden, bias=False).requires_grad_(False)
+ for _ in range(layers)
+ )
+ self.lora_A = nn.ModuleList(
+ nn.Linear(hidden, 4, bias=False) for _ in range(layers)
+ )
+ self.lora_B = nn.ModuleList(
+ nn.Linear(4, hidden, bias=False) for _ in range(layers)
+ )
+ for linear in self.lora_B:
+ nn.init.normal_(linear.weight, std=0.02)
+ self.head = nn.Linear(hidden, VOCAB, bias=False).requires_grad_(False)
+ self.defect = defect
+ self.backwards = 0
+
+ def _count(self, grad):
+ self.backwards += 1
+ return grad
+
+ def forward(self, input_ids, labels):
+ x = self.embed(input_ids)
+ layers = len(self.base)
+ for index in range(layers):
+ delta = self.lora_B[index](self.lora_A[index](x))
+ if self.defect and self.backwards >= 1 and index < layers - 2:
+ delta = _GradScale.apply(delta, 1.0 + 0.5 * self.backwards)
+ x = torch.tanh(self.base[index](x) + delta)
+ logits = self.head(x)
+ if logits.requires_grad:
+ logits.register_hook(self._count)
+ loss = nn.functional.cross_entropy(
+ logits.view(-1, VOCAB), labels.view(-1)
+ )
+ return _Out(logits, loss)
+
+
+class _Renamed(nn.Module):
+ def __init__(self, toy):
+ super().__init__()
+ self.wrapped = toy
+
+ def forward(self, input_ids, labels):
+ return self.wrapped(input_ids=input_ids, labels=labels)
+
+
+def _inputs():
+ generator = torch.Generator().manual_seed(17)
+ ids = torch.randint(0, VOCAB, (1, 12), generator=generator)
+ return ids, [ids.clone() for _ in range(5)]
+
+
+def test_measure_models_reports_the_record_pattern():
+ ids, batches = _inputs()
+ record = module.measure_models(_Toy(defect=True), _Toy(defect=False), ids, batches)
+ assert record["streamed_forward_equal"] is True
+ assert record["resident_forward_equal"] is True
+ assert record["streamed_gradient_equal"] is False
+ assert record["resident_gradient_equal"] is True
+ assert record["streamed_curve_equal"] is False
+ assert record["resident_curve_equal"] is True
+ assert module.determinism_verdict(record)
+
+
+def test_measure_models_healthy_pair_is_not_the_pattern():
+ ids, batches = _inputs()
+ record = module.measure_models(_Toy(defect=False), _Toy(defect=False), ids, batches)
+ assert record["streamed_gradient_equal"] is True
+ assert record["streamed_curve_equal"] is True
+ assert not module.determinism_verdict(record)
+
+
+def test_measure_models_refuses_an_empty_intersection():
+ ids, batches = _inputs()
+ with pytest.raises(ValueError, match="no canonical parameter name"):
+ module.measure_models(
+ _Toy(defect=True), _Renamed(_Toy(defect=False)), ids, batches
+ )