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: share one source_sha() across the harnesses (#1387) (#1403)

Maxi5df5b8d5dd91
diff --git a/benchmarks/harness/head_prefetch_ab.py b/benchmarks/harness/head_prefetch_ab.py
index 9399f7e9..b2238f93 100644
--- a/benchmarks/harness/head_prefetch_ab.py
+++ b/benchmarks/harness/head_prefetch_ab.py
@@ -50,14 +50,14 @@ A machine without CUDA is an intentional skip and exits 0.
import argparse
import json
-import re
import statistics
-import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
+from source_provenance import source_sha
+
def _harness() -> Any:
"""Import the sibling probe and labeller, whichever directory this ran from."""
@@ -122,58 +122,8 @@ def arm_name(arm: Optional[int]) -> str:
def _source_sha() -> str:
- """The commit of the tree that ``soup_cli`` got imported from, or ``unknown``.
-
- I resolve this from ``soup_cli.__file__``, not from this driver's own file:
- the driver and the ``soup_cli`` it measures can come from different
- checkouts (a ``PYTHONPATH`` override, an editable install elsewhere), and I
- want the tree that was actually measured. ``-dirty`` covers an uncommitted
- change on top of that commit, scoped to ``src`` so an untracked output file
- left at the repo root (this driver's own ``--out``, say) does not turn a
- clean tree dirty. Written the way ``variant2_gate.py``'s ``_source_sha`` is.
- """
- import soup_cli
-
- package_file = getattr(soup_cli, "__file__", None)
- if package_file is None:
- return "unknown"
- try:
- package_dir = Path(package_file).resolve().parent
- root = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- cwd=package_dir,
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout.strip()
- if not root:
- return "unknown"
- commit = (
- subprocess.run(
- ["git", "rev-parse", "HEAD"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- )
- .stdout.strip()
- .lower()
- )
- dirty = subprocess.run(
- ["git", "status", "--porcelain", "--untracked-files=normal", "--", "src"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout
- except (OSError, subprocess.SubprocessError):
- return "unknown"
- if not re.fullmatch(r"[0-9a-f]{40}", commit):
- return "unknown"
- return f"{commit}-dirty" if dirty else commit
+ """Shared with the other harnesses; see ``source_provenance``."""
+ return source_sha(dirty_pathspec="src")
def group_of(name: str) -> str:
diff --git a/benchmarks/harness/issue361_nf4_throughput.py b/benchmarks/harness/issue361_nf4_throughput.py
index 7d9d6376..ec3ef011 100644
--- a/benchmarks/harness/issue361_nf4_throughput.py
+++ b/benchmarks/harness/issue361_nf4_throughput.py
@@ -50,7 +50,6 @@ from __future__ import annotations
import argparse
import json
-import re
import statistics
import subprocess
import sys
@@ -58,6 +57,8 @@ import threading
import time
from pathlib import Path
+from source_provenance import source_sha
+
DEFAULT_SEQ = 512
DEFAULT_BATCH = 1
DEFAULT_WARMUP = 10
@@ -99,58 +100,8 @@ def _soup_version() -> str:
def _source_sha() -> str:
- """The tree the row was produced from, or ``unknown``.
-
- ``soup-cli`` reports a release version that does not move between commits,
- so without this a row cannot name its own tree — and this harness measures a
- path that three post-#361-base commits changed (#989 above all). Resolved
- from the ``soup_cli`` package's own location (not this harness file's), so a
- shadow install elsewhere on ``sys.path`` is not misreported as the checkout
- that produced the row, and marked ``-dirty`` when that tree has uncommitted
- changes (#1085's ``variant2_gate._source_sha`` first added both checks).
- """
- import soup_cli
-
- package_file = getattr(soup_cli, "__file__", None)
- if package_file is None:
- return "unknown"
- try:
- package_dir = Path(package_file).resolve().parent
- root = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- cwd=package_dir,
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout.strip()
- if not root:
- return "unknown"
- commit = (
- subprocess.run(
- ["git", "rev-parse", "HEAD"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- )
- .stdout.strip()
- .lower()
- )
- dirty = subprocess.run(
- ["git", "status", "--porcelain", "--untracked-files=normal"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout
- except (OSError, subprocess.SubprocessError):
- return "unknown"
- if not re.fullmatch(r"[0-9a-f]{40}", commit):
- return "unknown"
- return f"{commit}-dirty" if dirty else commit
+ """Shared with the other harnesses; see ``source_provenance``."""
+ return source_sha()
def _versions() -> dict:
@@ -302,7 +253,6 @@ class GpuSampler:
def _poll(self) -> None:
import shutil
- import subprocess
tool = shutil.which("nvidia-smi")
if tool is None:
diff --git a/benchmarks/harness/source_provenance.py b/benchmarks/harness/source_provenance.py
new file mode 100644
index 00000000..168e4869
--- /dev/null
+++ b/benchmarks/harness/source_provenance.py
@@ -0,0 +1,59 @@
+"""Which tree a benchmark row measured (#1387).
+
+``soup-cli`` reports a release version that does not move between commits, so a
+harness records the commit of the ``soup_cli`` it imported. Resolved from the
+package's own location, not the harness file's: the two can come from different
+checkouts (a ``PYTHONPATH`` override, an editable install elsewhere).
+"""
+
+from __future__ import annotations
+
+import re
+import subprocess
+from pathlib import Path
+from typing import Optional
+
+
+def _git(args: list[str], cwd: Path) -> str:
+ return subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ ).stdout
+
+
+def source_sha(*, dirty_pathspec: Optional[str] = None) -> str:
+ """The commit of the tree ``soup_cli`` was imported from, or ``unknown``.
+
+ ``-dirty`` marks uncommitted changes on top of that commit; ``dirty_pathspec``
+ limits which ones count (``"src"`` keeps a harness's own output file at the
+ repo root from marking a clean tree dirty).
+
+ A ``soup-cli`` wheel installed into a gitignored ``.venv/`` inside the checkout
+ resolves to the checkout too, but the code measured is the wheel's, so
+ ``soup_cli/__init__.py`` must be a file the checkout tracks.
+ """
+ import soup_cli
+
+ package_file = getattr(soup_cli, "__file__", None)
+ if package_file is None:
+ return "unknown"
+ try:
+ package_path = Path(package_file).resolve()
+ root = _git(["rev-parse", "--show-toplevel"], package_path.parent).strip()
+ if not root:
+ return "unknown"
+ _git(["ls-files", "--error-unmatch", str(package_path)], Path(root))
+ commit = _git(["rev-parse", "HEAD"], Path(root)).strip().lower()
+ status = ["status", "--porcelain", "--untracked-files=normal"]
+ if dirty_pathspec is not None:
+ status += ["--", dirty_pathspec]
+ dirty = _git(status, Path(root))
+ except (OSError, subprocess.SubprocessError):
+ return "unknown"
+ if not re.fullmatch(r"[0-9a-f]{40}", commit):
+ return "unknown"
+ return f"{commit}-dirty" if dirty else commit
diff --git a/benchmarks/harness/variant2_gate.py b/benchmarks/harness/variant2_gate.py
index 18f47725..3c946555 100644
--- a/benchmarks/harness/variant2_gate.py
+++ b/benchmarks/harness/variant2_gate.py
@@ -47,7 +47,6 @@ import gc
import json
import re
import statistics
-import subprocess
import sys
import time
from dataclasses import asdict, dataclass
@@ -58,6 +57,7 @@ from types import ModuleType
from typing import Any, Callable
import bitexact as shared
+from source_provenance import source_sha
DEFAULT_BATCH = 1
DEFAULT_BUFFERS = 2
@@ -211,48 +211,8 @@ def _rewired_modules(model: Any) -> int:
def _source_sha() -> str:
- import soup_cli
-
- package_file = getattr(soup_cli, "__file__", None)
- if package_file is None:
- return "unknown"
- try:
- package_dir = Path(package_file).resolve().parent
- root = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- cwd=package_dir,
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout.strip()
- if not root:
- return "unknown"
- commit = (
- subprocess.run(
- ["git", "rev-parse", "HEAD"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- )
- .stdout.strip()
- .lower()
- )
- dirty = subprocess.run(
- ["git", "status", "--porcelain", "--untracked-files=normal"],
- cwd=Path(root),
- check=True,
- capture_output=True,
- text=True,
- timeout=5,
- ).stdout
- except (OSError, subprocess.SubprocessError):
- return "unknown"
- if not re.fullmatch(r"[0-9a-f]{40}", commit):
- return "unknown"
- return f"{commit}-dirty" if dirty else commit
+ """Shared with the other harnesses; see ``source_provenance``."""
+ return source_sha()
def _versions() -> dict[str, str]:
diff --git a/tests/test_issue1174_head_prefetch_ab_provenance.py b/tests/test_issue1174_head_prefetch_ab_provenance.py
index bb590c5b..3c59c7ce 100644
--- a/tests/test_issue1174_head_prefetch_ab_provenance.py
+++ b/tests/test_issue1174_head_prefetch_ab_provenance.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib.util
import json
+import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -62,11 +63,12 @@ def test_git_sha_names_the_imported_tree_and_marks_it_dirty(
return SimpleNamespace(stdout=status)
monkeypatch.chdir(tmp_path)
- monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _driver._source_sha() == expected_sha + ("-dirty" if status else "")
assert calls == [
(["git", "rev-parse", "--show-toplevel"], package_dir),
+ (["git", "ls-files", "--error-unmatch", str(Path(package_file).resolve())], tmp_path),
(["git", "rev-parse", "HEAD"], tmp_path),
(["git", "status", "--porcelain", "--untracked-files=normal", "--", "src"], tmp_path),
]
@@ -76,7 +78,7 @@ def test_source_sha_is_unknown_without_a_git_toplevel(monkeypatch: pytest.Monkey
def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
return SimpleNamespace(stdout="\n")
- monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _driver._source_sha() == "unknown"
@@ -84,7 +86,7 @@ def test_source_sha_is_unknown_when_git_is_missing(monkeypatch: pytest.MonkeyPat
def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
raise FileNotFoundError("no git")
- monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _driver._source_sha() == "unknown"
@@ -93,9 +95,9 @@ def test_source_sha_is_unknown_when_git_exits_non_zero(monkeypatch: pytest.Monke
--show-toplevel`` exit 128; with ``check=True`` that is a ``CalledProcessError``."""
def fake_run(command: list[str], *, cwd: Path, **kwargs: object) -> Any:
- raise _driver.subprocess.CalledProcessError(128, command)
+ raise subprocess.CalledProcessError(128, command)
- monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _driver._source_sha() == "unknown"
@@ -109,7 +111,7 @@ def test_source_sha_does_not_record_a_head_that_is_not_a_commit(
return SimpleNamespace(stdout="not-a-commit\n")
return SimpleNamespace(stdout="")
- monkeypatch.setattr(_driver.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _driver._source_sha() == "unknown"
diff --git a/tests/test_issue1387_source_provenance.py b/tests/test_issue1387_source_provenance.py
new file mode 100644
index 00000000..6a884f9c
--- /dev/null
+++ b/tests/test_issue1387_source_provenance.py
@@ -0,0 +1,125 @@
+"""#1387: one ``source_sha()`` for every benchmark harness that records its tree.
+
+These run real ``git`` against a throwaway checkout holding a stand-in ``soup_cli``
+package, so the resolution is exercised end to end rather than through a fake
+``subprocess.run``.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import io
+import shutil
+import subprocess
+import sys
+import types
+import zipfile
+from pathlib import Path
+
+import pytest
+
+_HARNESS_DIR = Path(__file__).resolve().parents[1] / "benchmarks" / "harness"
+
+
+def _load(name: str):
+ sys.path.insert(0, str(_HARNESS_DIR))
+ try:
+ spec = importlib.util.spec_from_file_location(
+ f"_issue1387_{name}", _HARNESS_DIR / f"{name}.py"
+ )
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module # dataclasses look their module up here
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.path.remove(str(_HARNESS_DIR))
+
+
+provenance = _load("source_provenance")
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout
+
+
+def checkout(tmp_path: Path) -> Path:
+ if shutil.which("git") is None:
+ pytest.skip("git is not installed")
+ root = tmp_path / "checkout"
+ (root / "src" / "soup_cli").mkdir(parents=True)
+ (root / "src" / "soup_cli" / "__init__.py").write_text("", encoding="utf-8")
+ (root / ".gitignore").write_text(".venv/\n", encoding="utf-8")
+ _git(root, "init", "-q")
+ _git(root, "add", ".")
+ _git(
+ root,
+ "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false",
+ "commit", "-q", "-m", "init",
+ )
+ return root
+
+
+def _import_soup_cli_from(monkeypatch: pytest.MonkeyPatch, init_file: Path) -> None:
+ fake = types.ModuleType("soup_cli")
+ fake.__file__ = str(init_file)
+ monkeypatch.setitem(sys.modules, "soup_cli", fake)
+
+
+def test_clean_tree_records_its_commit(monkeypatch, checkout):
+ _import_soup_cli_from(monkeypatch, checkout / "src" / "soup_cli" / "__init__.py")
+ assert provenance.source_sha() == _git(checkout, "rev-parse", "HEAD").strip()
+
+
+def test_tracked_edit_is_dirty(monkeypatch, checkout):
+ init_file = checkout / "src" / "soup_cli" / "__init__.py"
+ init_file.write_text("x = 1\n", encoding="utf-8")
+ _import_soup_cli_from(monkeypatch, init_file)
+ assert provenance.source_sha() == _git(checkout, "rev-parse", "HEAD").strip() + "-dirty"
+
+
+def test_dirty_pathspec_ignores_changes_outside_it(monkeypatch, checkout):
+ (checkout / "result.json").write_text("{}", encoding="utf-8")
+ _import_soup_cli_from(monkeypatch, checkout / "src" / "soup_cli" / "__init__.py")
+ head = _git(checkout, "rev-parse", "HEAD").strip()
+ assert provenance.source_sha() == head + "-dirty"
+ assert provenance.source_sha(dirty_pathspec="src") == head
+
+
+def test_untracked_copy_inside_the_checkout_is_unknown(monkeypatch, checkout):
+ """A wheel installed into a gitignored .venv/ in the checkout resolves to the
+ checkout too, but the code measured is the wheel's, not the commit's."""
+ installed = checkout / ".venv" / "lib" / "site-packages" / "soup_cli" / "__init__.py"
+ installed.parent.mkdir(parents=True)
+ installed.write_text("", encoding="utf-8")
+ _import_soup_cli_from(monkeypatch, installed)
+ assert provenance.source_sha() == "unknown"
+
+
+def test_git_archive_tree_is_unknown(monkeypatch, checkout, tmp_path):
+ extracted = tmp_path / "extracted"
+ extracted.mkdir()
+ archive = subprocess.run(
+ ["git", "archive", "--format=zip", "HEAD"], cwd=checkout, check=True, capture_output=True
+ ).stdout
+ zipfile.ZipFile(io.BytesIO(archive)).extractall(extracted)
+ _import_soup_cli_from(monkeypatch, extracted / "src" / "soup_cli" / "__init__.py")
+ assert provenance.source_sha() == "unknown"
+
+
+ "harness, expected",
+ [
+ ("variant2_gate", {}),
+ ("issue361_nf4_throughput", {}),
+ ("head_prefetch_ab", {"dirty_pathspec": "src"}),
+ ],
+)
+def test_every_harness_uses_the_shared_helper(monkeypatch, harness, expected):
+ module = _load(harness)
+ monkeypatch.setattr(module, "source_sha", lambda **kwargs: kwargs)
+ assert module._source_sha() == expected
+ assert "def source_sha" not in (_HARNESS_DIR / f"{harness}.py").read_text(encoding="utf-8")
diff --git a/tests/test_issue361_nf4_throughput.py b/tests/test_issue361_nf4_throughput.py
index ef6212b7..e3914051 100644
--- a/tests/test_issue361_nf4_throughput.py
+++ b/tests/test_issue361_nf4_throughput.py
@@ -34,12 +34,18 @@ _HARNESS = _REPO_ROOT / "benchmarks" / "harness" / "issue361_nf4_throughput.py"
def _load_harness():
- spec = importlib.util.spec_from_file_location("issue361_nf4_throughput", _HARNESS)
- assert spec is not None and spec.loader is not None
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
+ # The harness imports its sibling ``source_provenance`` (#1387), as it does
+ # when run as a script from benchmarks/harness.
+ sys.path.insert(0, str(_HARNESS.parent))
+ try:
+ spec = importlib.util.spec_from_file_location("issue361_nf4_throughput", _HARNESS)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.path.remove(str(_HARNESS.parent))
_harness = _load_harness()
@@ -211,6 +217,7 @@ class TestTheRowNamesItsTree:
assert _harness._source_sha() == expected_sha + ("-dirty" if status else "")
assert calls == [
(["git", "rev-parse", "--show-toplevel"], package_dir),
+ (["git", "ls-files", "--error-unmatch", str(Path(package_file).resolve())], tmp_path),
(["git", "rev-parse", "HEAD"], tmp_path),
(["git", "status", "--porcelain", "--untracked-files=normal"], tmp_path),
]
diff --git a/tests/test_issue379_variant2_gate.py b/tests/test_issue379_variant2_gate.py
index 0249a5e1..f0a5334e 100644
--- a/tests/test_issue379_variant2_gate.py
+++ b/tests/test_issue379_variant2_gate.py
@@ -9,6 +9,7 @@ the non-vacuous contract on CPU; real 32B/72B numbers still require CUDA.
from __future__ import annotations
import importlib.util
+import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -304,11 +305,12 @@ class TestSourceCommit:
return SimpleNamespace(stdout=status)
monkeypatch.chdir(tmp_path)
- monkeypatch.setattr(_harness.subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "run", fake_run)
assert _harness._source_sha() == expected_sha + ("-dirty" if status else "")
assert calls == [
(["git", "rev-parse", "--show-toplevel"], package_dir),
+ (["git", "ls-files", "--error-unmatch", str(Path(package_file).resolve())], tmp_path),
(["git", "rev-parse", "HEAD"], tmp_path),
(["git", "status", "--porcelain", "--untracked-files=normal"], tmp_path),
]