okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
10.4 KiB247 linesraw
1"""Tuning history: what makes two measurements comparable.
2
3Checklist T06 asks that an engine, model, driver, workload or context change invalidates
4incompatible history, and that model identity is more than a name. Both matter for the same reason:
5a tuning result is only meaningful relative to the machine and the exact bytes it was measured on,
6and a history that silently mixes two configurations produces a confident recommendation from
7incomparable numbers.
8
9The design follows from that:
10
11* **Identity is a content hash, not a label.** A model is identified by the digest of its file(s), an
12  engine by the digest of its binary. "qwen3.8-flash-next" and "the same filename" are not
13  identities: a re-quantised model keeps its name and changes its behaviour.
14* **The comparison key is explicit and complete.** Engine + model + backend + workload + context +
15  the machine. Any element changing makes two records incomparable, and the *reason* is reported
16  rather than the record being quietly dropped.
17* **Nothing is deleted.** Incomparable history is retained and labelled. A previous sweep may still
18  answer a question ("did that flag help on the old driver?"), so it is not the store's business to
19  discard it — only to refuse to average it with the new numbers.
20* **Hashing a multi-gigabyte model is bounded.** A full digest of a 40 GB pack is not something to do
21  casually, so a partial digest (size plus sampled regions) is used by default, and the method is
22  recorded so two records can never be compared as though they used the same one.
23"""
24
25from __future__ import annotations
26
27import hashlib
28import json
29import os
30from strata_control import sysinfo
31import time
32import uuid
33from dataclasses import asdict, dataclass, field
34from pathlib import Path
35from typing import Any
36
37SCHEMA_VERSION = 1
38
39#: How a file's identity was computed. Two records with different methods are not comparable, so the
40#: method travels with the digest.
41FULL = "sha256-full"
42SAMPLED = "sha256-sampled-head-tail-mid"
43
44#: Bytes read at each sampled region.
45SAMPLE_BYTES = 4 << 20
46
47
48def file_identity(path: Path, *, full: bool = False) -> dict[str, Any]:
49    """A content identity for a file, cheaply by default.
50
51    A model pack is tens of gigabytes; hashing it fully on every CLI invocation would be its own kind
52    of bug. The sampled digest reads the head, the middle and the tail plus the exact size, which
53    catches a different quantisation, a truncated download and a swapped file in practice. `full=True`
54    is available for a release-time record where the cost is acceptable.
55    """
56    p = Path(path)
57    if not p.exists():
58        return {"path": str(p), "exists": False, "method": None, "digest": None, "bytes": None}
59    size = p.stat().st_size
60    h = hashlib.sha256()
61    if full:
62        method = FULL
63        with p.open("rb") as fh:
64            for block in iter(lambda: fh.read(1 << 20), b""):
65                h.update(block)
66    else:
67        method = SAMPLED
68        h.update(str(size).encode())
69        with p.open("rb") as fh:
70            regions = []
71            if size <= 3 * SAMPLE_BYTES:
72                regions.append((0, size))
73            else:
74                regions = [(0, SAMPLE_BYTES),
75                           (size // 2, SAMPLE_BYTES),
76                           (size - SAMPLE_BYTES, SAMPLE_BYTES)]
77            for offset, length in regions:
78                fh.seek(offset)
79                h.update(fh.read(length))
80    return {"path": str(p), "exists": True, "method": method, "digest": h.hexdigest(),
81            "bytes": size}
82
83
84def machine_identity() -> dict[str, Any]:
85    """The machine, at the granularity that makes measurements incomparable when it changes.
86
87    The CPU/GPU model and the driver version are what matter; the hostname is not (a renamed machine
88    is the same machine), so it is deliberately absent.
89    """
90    return {
91        "system": sysinfo.system(),
92        "release": sysinfo.release(),
93        "machine": sysinfo.machine(),
94        "processor": sysinfo.processor(),
95        "cpu_count": os.cpu_count(),
96    }
97
98
99def comparison_key(*, engine: dict[str, Any], model: dict[str, Any], backend: str,
100                   workload: dict[str, Any], context: int | None,
101                   machine: dict[str, Any] | None = None) -> dict[str, Any]:
102    """The tuple that two records must share to be comparable.
103
104    Every element is either a digest or a fixed number, so an equality test on this dict is the whole
105    comparability rule. A field that is unknown is `None` and therefore *not* equal to a known value,
106    which is deliberate: an unknown is not evidence of sameness.
107    """
108    return {
109        "engine_digest": engine.get("digest"),
110        "engine_bytes": engine.get("bytes"),
111        "model_digest": model.get("digest"),
112        "model_bytes": model.get("bytes"),
113        "digest_method": model.get("method"),
114        "backend": backend,
115        "workload": dict(sorted(workload.items())),
116        "context": context,
117        "machine": dict(sorted((machine or machine_identity()).items())),
118    }
119
120
121def incomparable_reasons(a: dict[str, Any], b: dict[str, Any]) -> list[str]:
122    """Why two comparison keys cannot be compared, in plain words.
123
124    Returning the reasons rather than a boolean is what lets a report say *"the model changed, so the
125    earlier sweep no longer applies"* instead of showing a recommendation built across a change.
126    """
127    reasons: list[str] = []
128    if a.get("engine_digest") != b.get("engine_digest"):
129        reasons.append("a different engine build")
130    if a.get("model_digest") != b.get("model_digest"):
131        reasons.append("different model bytes")
132    a_method, b_method = a.get("digest_method"), b.get("digest_method")
133    if a_method != b_method:
134        reasons.append(f"the identity was computed differently ({a_method} vs {b_method})")
135    if a.get("backend") != b.get("backend"):
136        reasons.append(f"a different backend ({a.get('backend')} vs {b.get('backend')})")
137    if a.get("workload") != b.get("workload"):
138        reasons.append("a different workload")
139    if a.get("context") != b.get("context"):
140        reasons.append(f"a different context ({a.get('context')} vs {b.get('context')})")
141    if a.get("machine") != b.get("machine"):
142        reasons.append("a different machine or driver")
143    return reasons
144
145
146@dataclass
147class HistoryRecord:
148    """One completed sweep, as the history store keeps it."""
149
150    id: str
151    recorded_at: float
152    key: dict[str, Any]
153    outcome: str                       # accepted | inconclusive | conflict | cancelled
154    recommendation_args: dict[str, str] = field(default_factory=dict)
155    median: float | None = None
156    baseline_median: float | None = None
157    metric: str = "tokens_per_s"
158    trials_run: int = 0
159    combinations_total: int = 0
160    engine_path: str = ""
161    model_path: str = ""
162    note: str = ""
163
164    def to_dict(self) -> dict[str, Any]:
165        return asdict(self)
166
167
168class HistoryStore:
169    """Recorded sweeps, kept so a later one can say what it is and is not comparable to.
170
171    The store is a directory of JSON records rather than a database: it is small, it is read whole by
172    a human when something looks wrong, and it has no server to be unavailable.
173    """
174
175    def __init__(self, root: Path) -> None:
176        self.root = Path(root)
177        self.root.mkdir(parents=True, exist_ok=True)
178
179    @property
180    def index(self) -> Path:
181        return self.root / "history.jsonl"
182
183    def record(self, *, key: dict[str, Any], outcome: str, recommendation_args: dict[str, str] | None = None,
184               median: float | None = None, baseline_median: float | None = None,
185               metric: str = "tokens_per_s", trials_run: int = 0, combinations_total: int = 0,
186               engine_path: str = "", model_path: str = "", note: str = "") -> HistoryRecord:
187        rec = HistoryRecord(
188            id=uuid.uuid4().hex, recorded_at=time.time(), key=key, outcome=outcome,
189            recommendation_args=dict(recommendation_args or {}), median=median,
190            baseline_median=baseline_median, metric=metric, trials_run=trials_run,
191            combinations_total=combinations_total, engine_path=engine_path, model_path=model_path,
192            note=note)
193        with self.index.open("a", encoding="utf-8") as fh:
194            fh.write(json.dumps({"schema_version": SCHEMA_VERSION, **rec.to_dict()},
195                                sort_keys=True) + "\n")
196        return rec
197
198    def records(self) -> list[HistoryRecord]:
199        """Every record, newest last. A damaged line is skipped, not fatal."""
200        if not self.index.exists():
201            return []
202        out: list[HistoryRecord] = []
203        for line in self.index.read_text(encoding="utf-8").splitlines():
204            if not line.strip():
205                continue
206            try:
207                data = json.loads(line)
208            except json.JSONDecodeError:
209                continue
210            if data.get("schema_version") != SCHEMA_VERSION:
211                continue
212            data.pop("schema_version", None)
213            try:
214                out.append(HistoryRecord(**data))
215            except TypeError:
216                continue
217        return out
218
219    def comparable(self, key: dict[str, Any]) -> tuple[list[HistoryRecord], list[dict[str, Any]]]:
220        """Split the history into what *is* comparable and what is not, with reasons.
221
222        Nothing is dropped: an incomparable record is returned with the reason it differs, because
223        the honest answer to "is there relevant history?" is often "yes, but from a different model".
224        """
225        usable: list[HistoryRecord] = []
226        unusable: list[dict[str, Any]] = []
227        for rec in self.records():
228            reasons = incomparable_reasons(rec.key, key)
229            if reasons:
230                unusable.append({"id": rec.id, "recorded_at": rec.recorded_at, "reasons": reasons,
231                                 "outcome": rec.outcome})
232            else:
233                usable.append(rec)
234        return usable, unusable
235
236
237def summarise_history(store: HistoryStore, key: dict[str, Any]) -> dict[str, Any]:
238    """The block a report carries so a reader knows what the numbers sit next to."""
239    usable, unusable = store.comparable(key)
240    return {
241        "comparable_records": len(usable),
242        "incomparable_records": len(unusable),
243        "incomparable": unusable[-8:],          # the most recent few, with their reasons
244        "note": ("earlier sweeps on this exact engine, model, workload, context and machine"
245                 if usable else
246                 "no earlier sweep is comparable to this one"),
247    }