diff --git a/ci/test-risk-map.json b/ci/test-risk-map.json index 53d68d58..0db30278 100644 --- a/ci/test-risk-map.json +++ b/ci/test-risk-map.json @@ -86,6 +86,7 @@ "docs/LABELED_SUBSPACE.md", "docs/CANDIDATE_DISCOVERY.md", "docs/EXAMPLE_SELECTION.md", + "docs/ANALYSIS_REUSE.md", "obliteratus/concepts/schema/target-dossier.v1.schema.json", "docs/TARGET_DOSSIERS.md", "obliteratus/concepts/schema/intervention-spec.v1.schema.json", @@ -1399,6 +1400,27 @@ "tests/test_module_imports.py" ] }, + { + "id": "analysis-reuse", + "owner": "mechanistic analysis maintainers", + "description": "O04 safe reuse: full cache identity (partition, fold, normalization, site, tokenizer, model/adapter/weights, dataset revision, algorithm, parameters, data), contamination refusal, exact bitwise hits, incremental moments with a declared error budget, avoided-work and amortization reporting, and opt-in extraction and discovery hooks", + "contract_types": [ + "numerical-invariant", + "reproducibility", + "research-output" + ], + "paths": [ + "obliteratus/analysis/reuse_identity.py", + "obliteratus/analysis/reuse_cache.py", + "obliteratus/analysis/reuse_consumers.py", + "obliteratus/analysis/incremental_stats.py", + "docs/ANALYSIS_REUSE.md" + ], + "required_tests": [ + "tests/test_reuse_cache.py", + "tests/test_reuse_consumers.py" + ] + }, { "id": "example-selection", "owner": "mechanistic analysis maintainers", @@ -2939,7 +2961,8 @@ "tests/test_concept_baseline.py", "tests/test_concept_entry_points.py", "tests/test_concept_affine_extraction.py", - "tests/test_leace_erasure_oracles.py" + "tests/test_leace_erasure_oracles.py", + "tests/test_reuse_consumers.py" ], "conditional_gates": [] }, @@ -4018,7 +4041,8 @@ "risk": "Candidate discovery contrasts, locked-test exclusion, group-disjoint fold refits, group-level shuffled-label and random-direction nulls, validation scoring and fit-on-evaluation labels, and the pack-basis artifact digest binding", "required_tests": [ "tests/test_candidate_discovery.py", - "tests/test_intervention_directions.py" + "tests/test_intervention_directions.py", + "tests/test_reuse_consumers.py" ], "conditional_gates": [] }, @@ -4131,6 +4155,44 @@ ], "conditional_gates": [] }, + { + "path": "obliteratus/analysis/reuse_identity.py", + "risk_class": "cpu-contract", + "risk": "Identity fields, unknown-never-matches, fold contamination refusal and capture-identity scopes", + "required_tests": [ + "tests/test_reuse_cache.py", + "tests/test_reuse_consumers.py" + ], + "conditional_gates": [] + }, + { + "path": "obliteratus/analysis/reuse_cache.py", + "risk_class": "cpu-contract", + "risk": "Exact-key hits with isolated copies, refusal diagnostics, LRU byte bound, avoided work and amortization report", + "required_tests": [ + "tests/test_reuse_cache.py", + "tests/test_reuse_consumers.py" + ], + "conditional_gates": [] + }, + { + "path": "obliteratus/analysis/reuse_consumers.py", + "risk_class": "cpu-contract", + "risk": "Extraction fold-fit, discovery null and labeled-matrix identities that keep consumer outputs bit-identical", + "required_tests": [ + "tests/test_reuse_consumers.py" + ], + "conditional_gates": [] + }, + { + "path": "obliteratus/analysis/incremental_stats.py", + "risk_class": "cpu-contract", + "risk": "Pairwise moment merges within the declared error budget and refusal of overlapping, duplicate or cross-fold blocks", + "required_tests": [ + "tests/test_reuse_cache.py" + ], + "conditional_gates": [] + }, { "path": "obliteratus/analysis/example_selection.py", "risk_class": "cpu-contract", diff --git a/docs/ANALYSIS_REUSE.md b/docs/ANALYSIS_REUSE.md new file mode 100644 index 00000000..1afc2e6d --- /dev/null +++ b/docs/ANALYSIS_REUSE.md @@ -0,0 +1,79 @@ +# Safe reuse of analysis work + +Repeated recipe, layer and rank comparisons often recompute the same layer +fits, decompositions and null samples. The reuse cache serves such results +again only when every input that can change their value or meaning is +identical. Reuse is opt-in. Without it, every analysis runs exactly as before. + +## Identity + +Each cached artifact carries a `ReuseIdentity` with these fields: + +| Field | Meaning | +| --- | --- | +| `kind`, `algorithm` | Artifact type and versioned algorithm (includes the package version) | +| `site` | Readout and phase plus layer or site | +| `partition` | Dataset roles, sets or contrast the rows come from | +| `fold` | `all`, `train:k/F`, `heldout:k/F` or a declared within-partition scope | +| `normalization` | Pooling, denoising, dtype or scaling applied before fitting | +| `tokenizer`, `model`, `adapter`, `weights` | Taken separately from the capture identity, including the weight fingerprint | +| `dataset_revision` | Content and partition revision of the dataset | +| `parameters` | Digest of algorithm options and seeds | +| `data` | Content digest of the input tensors, or a lineage digest of verified rows | + +A missing or `unknown` value never matches, so the result is computed fresh +and not stored. `ReuseScope.from_capture_identity` and +`ReuseScope.from_labeled` fill the model, tokenizer, adapter, weight and +revision fields. If only the labeled set's combined capture digest is known, +all four model-side fields are bound to that digest. + +## Refusal rules + +* A cache hit requires an exact match on every field. A miss is compared with + stored entries of the same kind and site, and the differing fields are + recorded. In that case the cache reports `refused` rather than `miss`. +* Fold contamination: a statistic fitted on all rows, on another fold's + training rows or on held-out rows is never used for a `train:` or + `heldout:` request. `admit` raises `ReuseContamination` for this case and + `ReuseRefused` for any other mismatch. +* Consumers that read a labeled set refuse a scope bound to a different + capture or dataset revision. +* Raw activation rows follow the same fold rule. This is stricter than + necessary, but simple to audit. + +## Accounting + +`ReuseCache.report()` returns lookups, hits, misses, refusals, unreusable +lookups, evictions and the event log. Each hit event lists the fields that +matched and the fold equality. The report also gives avoided work: estimated +operations declared by the consumer, input bytes not re-read, and the +recorded compute seconds of the original computation. Setup cost is reported +next to it: cold computation, identity hashing and copies. Amortization +divides setup by uses. Setup cost is spread over later hits; it is not +removed. All cached results are exact. No approximate sketch is stored. + +## Incremental statistics + +`PooledMoments` keeps count, sum and centered scatter in float64. It merges +appended blocks with the pairwise update, so earlier rows are not revisited. +A merged result is within a declared absolute error budget +(`8 · count · eps · max|x|`, squared and multiplied by count for scatter) of a +one-pass recomputation. It carries a distinct algorithm name, so it is never +served as an exact result. A merge is refused when identities or fold scopes +differ, when the same block is appended twice, or when tracked row keys +overlap. + +## Integrations + +* `extract_directions(..., reuse=scope)` reuses whole-set and per-fold layer + fits. Fold fits are keyed by the fold's held-out indices. Changing only the + intervention rule or the preset reuses every fit, and the resulting + direction is bit-identical. +* `discover_candidates(..., reuse=scope)` reuses the shuffled-label and + random-direction nulls of each contrast. These depend only on the discovery + rows, labels, groups, basis, seed and null options. Changing reporting + options such as `top_n` or `n_bootstrap` leaves the report bit-identical. +* `labeled_matrix` reuses float64 row selections of a verified labeled set. + +The cache lives only for the current process and is never written to disk. +Use `max_bytes` to limit how much it holds. diff --git a/obliteratus/analysis/candidate_discovery.py b/obliteratus/analysis/candidate_discovery.py index 84b5825d..f4ca1c12 100644 --- a/obliteratus/analysis/candidate_discovery.py +++ b/obliteratus/analysis/candidate_discovery.py @@ -127,7 +127,7 @@ def _recipe_top1(scan, y, splits, channel_ids): def discover_candidates(labeled, site, *, mode="binary", discovery_roles=("fit",), validation_roles=("select",), direction=None, layer=None, confounds=None, input_digests=None, seed=0, direction_source=None, - **options): + reuse=None, **options): """Candidate tables per contrast at ``site`` (versioned JSON-ready dict). ``confounds`` holds per-row ``length``/``lexical`` features aligned with @@ -136,6 +136,7 @@ def discover_candidates(labeled, site, *, mode="binary", discovery_roles=("fit", ``options`` override ``DEFAULTS`` within ``CAPS``. ``direction_source`` is the stored artifact ``direction`` was loaded from; its digests are recorded so a pack-basis row can be intervened on with exactly the evaluated bytes. + ``reuse`` (a ``ReuseScope``) opts in to exact reuse of the null samples. """ from obliteratus.analysis.labeled_subspace import ( artifact_binding, basis_fit_overlap, site_layer, stored_basis, @@ -157,7 +158,7 @@ def discover_candidates(labeled, site, *, mode="binary", discovery_roles=("fit", values = labeled.values[site].double() width = values.shape[1] context = {"labeled": labeled, "site": site, "opts": opts, "basis": basis, - "fit_overlap": fit_overlap, "digests": input_digests} + "fit_overlap": fit_overlap, "digests": input_digests, "reuse": reuse} contrasts = [_contrast(context, name, target, rest, values, discovery, validation, confounds, seed) for name, target, rest in _contrasts(labeled, mode, discovery)] @@ -204,8 +205,15 @@ def _contrast(ctx, name, target, rest, values, discovery, validation, confounds, f"{opts['folds']} for group-disjoint folds") splits = _splits(groups, y, opts["folds"], seed) scan = _scan(x, x_all, y, splits, basis) - shuffled, skipped = _shuffled_null(x, x_all, y, groups, basis, opts, seed) - random_aucs = _random_direction_null(x_all, y, splits, opts, seed) + def nulls(): + return (*_shuffled_null(x, x_all, y, groups, basis, opts, seed), + _random_direction_null(x_all, y, splits, opts, seed)) + if ctx["reuse"] is None: + shuffled, skipped, random_aucs = nulls() + else: + from obliteratus.analysis.reuse_consumers import discovery_nulls + shuffled, skipped, random_aucs = discovery_nulls(ctx, name, discovery, x_all, y, groups, + seed, nulls) baselines = confound_baselines(subset(confounds, disc), y, splits) val = labeled.rows(roles=validation, sets=target + rest) if validation else [] y_val = torch.tensor([labeled.sets[i] in target for i in val], dtype=torch.bool) diff --git a/obliteratus/analysis/incremental_stats.py b/obliteratus/analysis/incremental_stats.py new file mode 100644 index 00000000..ab616112 --- /dev/null +++ b/obliteratus/analysis/incremental_stats.py @@ -0,0 +1,137 @@ +"""Mergeable counts, sums and centered scatter for appended activation rows. + +``PooledMoments`` keeps ``count``, ``sum`` and the centered scatter matrix in +float64 and merges blocks with the pairwise update of Chan, Golub and LeVeque, +so appending rows never revisits earlier rows. A merged result is not bitwise +equal to a one-pass recomputation; it carries a declared error budget and a +distinct algorithm name, so it is never served as an exact result. Merging is +refused when identities differ (including fold scope: a held-out fold's rows +cannot join a training-fold statistic), when the same block is appended twice +or when tracked row keys overlap. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace + +import torch + +from obliteratus.analysis.capture_identity import digest +from obliteratus.analysis.reuse_identity import ( + ReuseContamination, ReuseIdentity, ReuseRefused, compare, content_digest, +) + +EXACT = "pooled_moments.exact/1" +INCREMENTAL = "pooled_moments.incremental/1" +# Declared absolute error budget: BUDGET * count * eps64 * max|x| (squared for scatter). +BUDGET = 8.0 +_EPS = torch.finfo(torch.float64).eps + + +@dataclass(frozen=True) +class PooledMoments: + """Sufficient statistics of one or more disjoint row blocks under one identity.""" + + scope: ReuseIdentity + count: int + sum: torch.Tensor + scatter: torch.Tensor + max_abs: float + segments: tuple + row_keys: frozenset | None = None + + @classmethod + def from_rows(cls, rows: torch.Tensor, scope: ReuseIdentity, row_keys=None): + x = torch.as_tensor(rows).detach().to("cpu", torch.float64) + if x.ndim != 2 or not x.shape[0] or not torch.isfinite(x).all(): + raise ValueError("PooledMoments needs a nonempty finite (n, d) matrix") + keys = None if row_keys is None else frozenset(map(str, row_keys)) + if keys is not None and len(keys) != x.shape[0]: + raise ValueError("row_keys must name every row exactly once") + centered = x - x.mean(0) + return cls(scope, int(x.shape[0]), x.sum(0), centered.T @ centered, + float(x.abs().max()), (content_digest(rows),), keys) + + @property + def mean(self) -> torch.Tensor: + return self.sum / self.count + + def covariance(self, ddof: int = 1) -> torch.Tensor: + if self.count - ddof <= 0: + raise ValueError("Covariance needs more rows than ddof") + return self.scatter / (self.count - ddof) + + @property + def exact(self) -> bool: + """True for a single one-pass block (bitwise reproducible).""" + return len(self.segments) == 1 + + @property + def identity(self) -> ReuseIdentity: + """Cache identity; merged statistics carry the incremental algorithm name.""" + return replace(self.scope, algorithm=f"{self.scope.algorithm}+" + f"{EXACT if self.exact else INCREMENTAL}", + data=digest(sorted(self.segments))) + + def merge(self, other: "PooledMoments") -> "PooledMoments": + """Combine two disjoint blocks; refuse incompatible or overlapping inputs.""" + reasons = [r for r in compare(self.scope, other.scope) if r["field"] != "data"] + if any(r["contamination"] for r in reasons): + raise ReuseContamination("Refused merge across fold scopes", reasons) + if reasons: + raise ReuseRefused("Refused merge of incompatible statistics: " + + ", ".join(r["field"] for r in reasons), reasons) + if self.sum.shape != other.sum.shape: + raise ReuseRefused("Refused merge of statistics with different widths", + [{"field": "data", "reason": "width differs", + "contamination": False}]) + if set(self.segments) & set(other.segments): + raise ReuseRefused("Refused merge: a block would be counted twice", + [{"field": "data", "reason": "duplicate block", + "contamination": False}]) + if (self.row_keys is None) != (other.row_keys is None): + raise ReuseRefused("Refused merge: row keys tracked on one side only", + [{"field": "data", "reason": "row keys missing", + "contamination": False}]) + keys = None + if self.row_keys is not None: + if self.row_keys & other.row_keys: + raise ReuseRefused("Refused merge: overlapping rows would be counted twice", + [{"field": "data", "reason": "overlapping rows", + "contamination": False}]) + keys = self.row_keys | other.row_keys + count = self.count + other.count + delta = other.mean - self.mean + scatter = (self.scatter + other.scatter + + delta.outer(delta) * (self.count * other.count / count)) + return PooledMoments(self.scope, count, self.sum + other.sum, scatter, + max(self.max_abs, other.max_abs), self.segments + other.segments, + keys) + + def append(self, rows: torch.Tensor, row_keys=None) -> "PooledMoments": + """Merge newly appended rows (same identity) without revisiting earlier rows.""" + return self.merge(PooledMoments.from_rows(rows, self.scope, row_keys)) + + def error_budget(self) -> dict: + """Declared absolute tolerances against a one-pass float64 recomputation.""" + scale = BUDGET * self.count * _EPS + return {"mean_atol": scale * self.max_abs, + "scatter_atol": scale * self.max_abs ** 2 * self.count, + "covariance_atol": scale * self.max_abs ** 2 * self.count + / max(self.count - 1, 1), + "basis": f"{BUDGET} * count * float64 eps * max|x| (squared, times count, " + "for scatter)", "exact": self.exact} + + def agreement(self, reference: "PooledMoments") -> dict: + """Compare with a one-pass recomputation over the same rows.""" + if self.count != reference.count: + raise ValueError("Agreement needs the same rows") + budget = self.error_budget() + mean_error = float((self.mean - reference.mean).abs().max()) + scatter_error = float((self.scatter - reference.scatter).abs().max()) + return {"mean_error": mean_error, "scatter_error": scatter_error, **budget, + "within_budget": mean_error <= budget["mean_atol"] + and scatter_error <= budget["scatter_atol"]} + + +__all__ = ["BUDGET", "EXACT", "INCREMENTAL", "PooledMoments"] diff --git a/obliteratus/analysis/reuse_cache.py b/obliteratus/analysis/reuse_cache.py new file mode 100644 index 00000000..b4cc71e1 --- /dev/null +++ b/obliteratus/analysis/reuse_cache.py @@ -0,0 +1,188 @@ +"""Process-scoped, exact reuse cache with avoided-work and amortization accounting. + +Entries are keyed by the digest of a full ``ReuseIdentity``. A lookup serves +an entry only on an exact key match; values are deep-copied on store and on +serve, so a consumer can never mutate a cached artifact. When the key misses, +entries of the same kind and site are compared field by field and the +reasons (including fold contamination) are recorded. Identities with an +unobservable field are computed fresh and never stored. + +All reuse here is exact: a hit returns the bytes the same computation +produced earlier. No approximate sketch is stored, so no error budget applies; +incremental statistics live in ``incremental_stats`` with their own tolerance. +""" + +from __future__ import annotations + +import dataclasses +import time +from collections import OrderedDict + +import torch + +from obliteratus.analysis.reuse_identity import FIELDS, ReuseIdentity, admit, compare + +SCHEMA = "obliteratus.reuse_report" +SCHEMA_VERSION = 1 +MAX_EVENTS = 200 +_LABEL = {"hits": "hit", "misses": "miss", "refused": "refused", "not_reusable": "not_reusable"} +OPS_SCOPE = ("estimated floating-point operations declared by the consumer for one " + "computation (order of magnitude, not measured)") + + +def clone(value): + """Deep copy of tensors nested in dicts, lists, tuples and dataclasses.""" + if isinstance(value, torch.Tensor): + return value.detach().clone() + if isinstance(value, dict): + return {k: clone(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return type(value)(clone(v) for v in value) + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return dataclasses.replace(value, **{f.name: clone(getattr(value, f.name)) + for f in dataclasses.fields(value) if f.init}) + return value + + +def nbytes(value) -> int: + """Logical element bytes of tensors nested in ``value``.""" + if isinstance(value, torch.Tensor): + return value.numel() * value.element_size() + if isinstance(value, dict): + return sum(nbytes(v) for v in value.values()) + if isinstance(value, (list, tuple)): + return sum(nbytes(v) for v in value) + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return sum(nbytes(getattr(value, f.name)) for f in dataclasses.fields(value)) + return 0 + + +@dataclasses.dataclass +class _Entry: + identity: ReuseIdentity + value: object + seconds: float + ops: int + input_bytes: int + stored_bytes: int + hits: int = 0 + + +class ReuseCache: + """Bounded in-memory store; ``max_bytes`` evicts least recently used entries.""" + + def __init__(self, *, max_bytes: int | None = None, clock=time.perf_counter): + if max_bytes is not None and (isinstance(max_bytes, bool) or not isinstance( + max_bytes, int) or max_bytes < 0): + raise ValueError("max_bytes must be a non-negative integer or None") + self.max_bytes = max_bytes + self.clock = clock + self._entries: OrderedDict[str, _Entry] = OrderedDict() + self.events: list[dict] = [] + self.counts = dict.fromkeys(("lookups", "hits", "misses", "refused", "not_reusable", + "evicted"), 0) + self.avoided = {"ops": 0, "input_bytes": 0, "compute_seconds": 0.0} + self.setup = {"compute_seconds": 0.0, "overhead_seconds": 0.0, "stored_bytes": 0} + + def __len__(self): + return len(self._entries) + + def add_overhead(self, seconds: float) -> None: + """Charge identity/digest time spent by a consumer to the reuse setup cost.""" + self.setup["overhead_seconds"] += seconds + + def _event(self, identity, outcome, **detail): + self.counts[outcome] += 1 + if len(self.events) < MAX_EVENTS: + self.events.append({"kind": identity.kind, "site": identity.site, + "fold": identity.fold, "outcome": _LABEL[outcome], **detail}) + + def _candidates(self, identity): + return [e for e in self._entries.values() + if e.identity.kind == identity.kind and e.identity.site == identity.site] + + def fetch(self, identity: ReuseIdentity, compute, *, ops: int = 0, input_bytes: int = 0): + """Serve an exact match or run ``compute()``; returns ``(value, outcome)``.""" + start = self.clock() + self.counts["lookups"] += 1 + unobservable = identity.unobservable() + if unobservable: + self._event(identity, "not_reusable", reason="unobservable fields: " + + ", ".join(unobservable)) + self.setup["overhead_seconds"] += self.clock() - start + return compute(), "not_reusable" + entry = self._entries.get(identity.key) + if entry is not None: + matched = admit(entry.identity, identity) + self._entries.move_to_end(identity.key) + entry.hits += 1 + value = clone(entry.value) + self.avoided["ops"] += entry.ops + self.avoided["input_bytes"] += entry.input_bytes + self.avoided["compute_seconds"] += entry.seconds + self._event(identity, "hits", validity={ + "matched_fields": matched, "fold": f"stored fold {entry.identity.fold!r} equals " + "the requested fold", + "exact": "bitwise copy of the stored result of the same computation"}) + self.setup["overhead_seconds"] += self.clock() - start + return value, "hit" + reasons = [compare(e.identity, identity) for e in self._candidates(identity)] + closest = min(reasons, key=len) if reasons else [] + if any(r["contamination"] for rs in reasons for r in rs): + closest = next(rs for rs in reasons if any(r["contamination"] for r in rs)) + self.setup["overhead_seconds"] += self.clock() - start + began = self.clock() + value = compute() + seconds = self.clock() - began + self.setup["compute_seconds"] += seconds + outcome = "refused" if closest else "misses" + self._event(identity, outcome, reasons=closest or [{"field": None, "reason": + "no stored entry of this kind/site", + "contamination": False}]) + if outcome == "refused": + self.counts["misses"] += 1 + self._store(identity, value, seconds, ops, input_bytes) + return value, "refused" if closest else "miss" + + def _store(self, identity, value, seconds, ops, input_bytes): + stored = clone(value) + size = nbytes(stored) + if self.max_bytes is not None and size > self.max_bytes: + return + self._entries[identity.key] = _Entry(identity, stored, seconds, int(ops), + int(input_bytes), size) + self.setup["stored_bytes"] += size + while self.max_bytes is not None and sum( + e.stored_bytes for e in self._entries.values()) > self.max_bytes: + self._entries.popitem(last=False) + self.counts["evicted"] += 1 + + def report(self) -> dict: + """Hits, misses, refusals, avoided work and amortization (JSON-ready).""" + lookups = self.counts["lookups"] + setup = self.setup["compute_seconds"] + self.setup["overhead_seconds"] + return { + "schema": SCHEMA, "schema_version": SCHEMA_VERSION, + "identity_fields": list(FIELDS), **self.counts, + "hit_rate": self.counts["hits"] / lookups if lookups else None, + "entries": len(self._entries), + "resident_bytes": sum(e.stored_bytes for e in self._entries.values()), + "avoided": {"estimated_ops": self.avoided["ops"], "ops_scope": OPS_SCOPE, + "input_bytes": self.avoided["input_bytes"], + "recorded_compute_seconds": self.avoided["compute_seconds"]}, + "setup": {"compute_seconds": self.setup["compute_seconds"], + "overhead_seconds": self.setup["overhead_seconds"], + "stored_bytes": self.setup["stored_bytes"]}, + "amortization": { + "setup_seconds": setup, "uses": lookups, + "setup_seconds_per_use": setup / lookups if lookups else None, + "net_seconds_saved": self.avoided["compute_seconds"] + - self.setup["overhead_seconds"], + "note": "setup (cold computation, identity hashing and copies) is paid once " + "and spread over later hits; it does not disappear"}, + "approximation": {"sketches": [], "note": "all cached results are exact"}, + "events": list(self.events), "events_truncated": lookups > len(self.events), + } + + +__all__ = ["ReuseCache", "clone", "nbytes"] diff --git a/obliteratus/analysis/reuse_consumers.py b/obliteratus/analysis/reuse_consumers.py new file mode 100644 index 00000000..8fbeccb1 --- /dev/null +++ b/obliteratus/analysis/reuse_consumers.py @@ -0,0 +1,163 @@ +"""Opt-in reuse hooks for existing analyses (extraction fits, discovery nulls, row matrices). + +Each hook builds a full ``ReuseIdentity`` from a ``ReuseScope`` (model, +tokenizer, adapter, weights, dataset revision, readout) plus the consumer's +own site, partition, fold, normalization, parameters and a content or lineage +digest of its inputs, then asks the scope's ``ReuseCache`` for an exact +result. Consumers call these only when a scope is passed; without one their +code path is unchanged. Bump an ``ALGORITHM`` string whenever the numerics of +the wrapped computation change. +""" + +from __future__ import annotations + +import json +import math + +from obliteratus import __version__ +from obliteratus.analysis.capture_identity import digest +from obliteratus.analysis.reuse_cache import nbytes +from obliteratus.analysis.reuse_identity import ReuseRefused, content_digest, fold_scope + +ALGORITHM = { + "extraction": f"concepts.extraction.extract_layer/1@{__version__}", + "discovery": f"analysis.candidate_discovery.nulls/1@{__version__}", + "matrix": f"analysis.labeled_selection.rows/1@{__version__}", +} + + +def _timed(cache, function, *args): + start = cache.clock() + value = function(*args) + cache.add_overhead(cache.clock() - start) + return value + + +def _extraction_ops(n, d, recipe): + from obliteratus.analysis.direction_methods import effective_direction_method + + method = effective_direction_method(recipe.method, warn_alias=False) + ops = 4 * n * d + if recipe.denoise is not None: + ops += 4 * n * d * min(n, d) + if method == "svd": + ops += 4 * n * d * min(n, d) + elif method in ("fisher_lda", "leace_exact"): + ops += 2 * n * d * d + d ** 3 + return ops + + +def extraction_fitter(scope, positive, controls, recipe, fit): + """Wrap ``extract_layer`` so whole-set and per-fold layer fits are reused exactly. + + The data digest of a fold fit combines the layer's content digest with the + fold's held-out indices for every set, and its fold scope is + ``train:k/F``; a whole-set fit has scope ``all`` and can never serve a fold. + """ + cache = scope.cache + names = list(controls) + parameters = {"method": recipe.method, "n_directions": recipe.n_directions, + "pool_controls": recipe.pool_controls, "denoise": recipe.denoise} + normalization = json.dumps({"pool_controls": recipe.pool_controls, + "denoise": recipe.denoise}, sort_keys=True) + partition = "sets=" + ",".join(["positive"] + [f"control:{n}" for n in names]) + layer_digests = {} + + def layer_digest(layer): + if layer not in layer_digests: + layer_digests[layer] = _timed(cache, content_digest, names, positive[layer], + *[controls[n][layer] for n in names]) + return layer_digests[layer] + + def run(layer, pos, ctrl, fold=None): + if fold is None: + scope_name, data = fold_scope(), layer_digest(layer) + else: + index, folds, splits = fold + scope_name = fold_scope(index, folds) + held = _timed(cache, content_digest, sorted(splits), + *[splits[n][index] for n in sorted(splits)]) + data = digest([layer_digest(layer), held]) + identity = scope.identity( + kind="extraction.layer_fit", algorithm=ALGORITHM["extraction"], + site=f"layer:{layer}", partition=partition, fold=scope_name, + normalization=normalization, parameters=parameters, data=data) + rows = len(pos) + sum(len(c) for c in ctrl.values()) + value, _ = cache.fetch(identity, lambda: fit(pos, ctrl, recipe, warn_alias=False), + ops=_extraction_ops(rows, pos.shape[1], recipe), + input_bytes=nbytes(pos) + nbytes(ctrl)) + return value + return run + + +def _check_scope(scope, labeled): + manifest = labeled.manifest + if scope.capture is not None and manifest.get("capture_identity_sha256") != scope.capture: + raise ReuseRefused("Reuse scope is bound to a different capture than the labeled set", + [{"field": "data", "reason": "capture digest differs", + "contamination": False}]) + if manifest.get("dataset_revision") != scope.dataset_revision: + raise ReuseRefused("Reuse scope dataset revision differs from the labeled set", + [{"field": "dataset_revision", "reason": "revision differs", + "contamination": False}]) + + +def discovery_nulls(ctx, name, discovery, x_all, y, groups, seed, compute): + """Reuse the shuffled-label and random-direction nulls of one discovery contrast. + + Both nulls draw from their own seeded generators and depend only on the + discovery rows, labels, groups, pack basis, seed and null options, so a + stored result is bit-identical to recomputation. + """ + scope, labeled, opts, basis = ctx["reuse"], ctx["labeled"], ctx["opts"], ctx["basis"] + _check_scope(scope, labeled) + cache = scope.cache + data = _timed(cache, content_digest, x_all, y, [str(g) for g in groups], + basis if basis is not None else "no-basis") + roles = "+".join(sorted(discovery)) + identity = scope.identity( + kind="candidate_discovery.nulls", algorithm=ALGORITHM["discovery"], site=ctx["site"], + partition=f"roles={roles};contrast={name}", fold=f"within:{roles}", + normalization="float64; unit-norm basis rows; label-free channel screen", + parameters={**{k: opts[k] for k in ("n_permutations", "n_random", "folds", + "max_channels")}, "seed": seed}, data=data) + n, d = x_all.shape + m = min(d, opts["max_channels"]) + ops = (opts["n_permutations"] * (n * m * max(1, math.ceil(math.log2(n))) + + opts["folds"] * n * d) + opts["n_random"] * n * d) + value, _ = cache.fetch(identity, compute, ops=ops, input_bytes=nbytes(x_all)) + return value + + +def labeled_matrix(scope, labeled, site, *, roles=None, sets=None, kinds=None, fold="all"): + """Float64 activation rows of a verified labeled set, reused by lineage digest. + + The data digest names the capture, the label sidecar and the stored row + positions rather than rehashing the activations, which ``load_labeled_set`` + already verified. + """ + _check_scope(scope, labeled) + positions = labeled.rows(roles=roles, sets=sets, kinds=kinds) + if not positions: + raise ValueError("No labeled rows match the selection") + manifest = labeled.manifest + identity = scope.identity( + kind="labeled.matrix", algorithm=ALGORITHM["matrix"], site=site, + partition=json.dumps({"roles": roles, "sets": sets, "kinds": kinds}, sort_keys=True, + default=list), + fold=fold, normalization="float64", parameters={}, + data=digest([manifest.get("capture_identity_sha256"), manifest.get("labels_sha256"), + [labeled.index[i] for i in positions]])) + values = labeled.values[site] + value, _ = cache_fetch(scope, identity, lambda: values[positions].double(), + input_bytes=len(positions) * values.shape[1] * values.element_size()) + return value + + +def cache_fetch(scope, identity, compute, *, ops=0, input_bytes=0): + """``scope.cache.fetch`` for callers building their own identities.""" + return scope.cache.fetch(identity, compute, ops=ops, input_bytes=input_bytes) + + +__all__ = ["ALGORITHM", "cache_fetch", "discovery_nulls", "extraction_fitter", + "labeled_matrix"] diff --git a/obliteratus/analysis/reuse_identity.py b/obliteratus/analysis/reuse_identity.py new file mode 100644 index 00000000..d49f859e --- /dev/null +++ b/obliteratus/analysis/reuse_identity.py @@ -0,0 +1,200 @@ +"""Identity of reusable analysis artifacts and the rules that refuse unsafe reuse. + +A reusable artifact (an activation matrix, pooled statistic, decomposition or +null sample) is identified by every input that can change its value or its +meaning. Two identities are compatible only when every field is equal and +observable; ``unknown`` never matches. Fold scope is checked with a stricter +rule: an artifact fitted on more rows than the requested fold (all examples, +another fold's training rows or held-out rows) is *contaminated* for that fold +and is refused with ``ReuseContamination`` even if its other fields agree. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, fields + +import torch + +from obliteratus.analysis.capture_identity import UNKNOWN, digest + +SCHEMA = "obliteratus.reuse_identity" +SCHEMA_VERSION = 1 +ALL_ROWS = "all" +# Fields compared for compatibility, in reporting order. +FIELDS = ("kind", "algorithm", "site", "partition", "fold", "normalization", "tokenizer", + "model", "adapter", "weights", "dataset_revision", "parameters", "data") +_RESTRICTED = ("train:", "heldout:") + + +class ReuseRefused(ValueError): + """A stored artifact is incompatible with the requested use.""" + + def __init__(self, message, reasons): + super().__init__(message) + self.reasons = reasons + + +class ReuseContamination(ReuseRefused): + """A stored artifact saw rows outside the requested fold (e.g. all-data in a held-out fold).""" + + +def fold_scope(fold=None, folds=None, part="train"): + """``all`` for whole-partition fits, else ``train:k/F`` or ``heldout:k/F``.""" + if fold is None: + return ALL_ROWS + if part not in ("train", "heldout") or not 0 <= fold < folds: + raise ValueError("fold scope needs part train/heldout and 0 <= fold < folds") + return f"{part}:{fold}/{folds}" + + +def content_digest(*values) -> str: + """SHA-256 over dtype, shape and bytes of tensors (and canonical JSON of other values).""" + h = hashlib.sha256() + for value in values: + if isinstance(value, torch.Tensor): + tensor = value.detach().to("cpu").contiguous() + h.update(f"tensor:{tensor.dtype}:{tuple(tensor.shape)}\0".encode()) + h.update(tensor.view(torch.uint8).numpy().tobytes() if tensor.numel() else b"") + else: + h.update(b"json:" + json.dumps(value, sort_keys=True, default=repr).encode()) + h.update(b"\0") + return h.hexdigest() + + +@dataclass(frozen=True) +class ReuseIdentity: + """Every field an artifact depends on; ``key`` is the digest of all fields.""" + + kind: str + algorithm: str + site: str + partition: str + fold: str + normalization: str + tokenizer: str + model: str + adapter: str + weights: str + dataset_revision: str + parameters: str + data: str + + @property + def key(self) -> str: + return digest(self.as_dict()) + + def as_dict(self) -> dict: + return {f.name: getattr(self, f.name) for f in fields(self)} + + def unobservable(self) -> list[str]: + """Fields that are missing or unknown; such an artifact is never reusable.""" + return [name for name in FIELDS + if not isinstance(getattr(self, name), str) or not getattr(self, name) + or UNKNOWN in getattr(self, name).split(":")] + + +def compare(stored: ReuseIdentity, requested: ReuseIdentity) -> list[dict]: + """Per-field refusal reasons (empty when the stored artifact may serve the request).""" + reasons = [{"field": name, "reason": "unobservable value never matches", + "contamination": False} + for name in sorted(set(stored.unobservable()) | set(requested.unobservable()), + key=FIELDS.index)] + for name in FIELDS: + old, new = getattr(stored, name), getattr(requested, name) + if old == new or any(r["field"] == name for r in reasons): + continue + if name == "fold" and new.startswith(_RESTRICTED): + reasons.append({"field": "fold", "contamination": True, + "reason": f"artifact fitted on {old!r} rows cannot serve fold " + f"{new!r}: it would leak rows outside that fold"}) + else: + reasons.append({"field": name, "contamination": False, + "reason": f"stored {name} differs from the requested {name}"}) + return reasons + + +def admit(stored: ReuseIdentity, requested: ReuseIdentity) -> list[str]: + """Raise unless ``stored`` may serve ``requested``; return the matched field names.""" + reasons = compare(stored, requested) + if any(r["contamination"] for r in reasons): + raise ReuseContamination("Refused contaminated reuse: " + "; ".join( + r["reason"] for r in reasons if r["contamination"]), reasons) + if reasons: + raise ReuseRefused("Refused incompatible reuse: " + ", ".join( + r["field"] for r in reasons), reasons) + return list(FIELDS) + + +def _section(identity, name): + value = identity.get(name) + if value is None or (isinstance(value, dict) and value.get("state") == UNKNOWN): + return UNKNOWN + return digest(value) + + +@dataclass(frozen=True) +class ReuseScope: + """Model, tokenizer, adapter, weight and dataset fields shared by one analysis context. + + ``capture`` is the capture identity digest when known; consumers that read a + labeled set refuse a scope bound to a different capture. + """ + + cache: object + tokenizer: str + model: str + adapter: str + weights: str + dataset_revision: str + readout: str = "decoder_output" + capture: str | None = None + + @classmethod + def from_capture_identity(cls, cache, identity: dict, **overrides): + """Split a ``capture_identity`` dict into separately compared fields.""" + weights = identity.get("weights") or {} + readout = identity.get("readout") or {} + values = { + "tokenizer": _section(identity, "tokenizer"), + "model": _section(identity, "checkpoint"), + "adapter": _section(identity, "adapter"), + "weights": (f"{weights.get('mode')}:{weights['sha256']}" if weights.get("sha256") + else UNKNOWN), + "dataset_revision": identity.get("dataset_revision") or UNKNOWN, + "readout": f"{readout.get('name', UNKNOWN)}/{readout.get('phase', UNKNOWN)}", + "capture": digest(identity), + } + return cls(cache=cache, **{**values, **overrides}) + + @classmethod + def from_labeled(cls, cache, labeled, capture_identity: dict | None = None): + """Scope of a verified labeled set. + + Without the full capture identity the tokenizer, model, adapter and + weight fields are all bound to the combined capture digest, so any + change to one of them still prevents reuse. + """ + manifest = labeled.manifest + sha = manifest.get("capture_identity_sha256") or UNKNOWN + revision = manifest.get("dataset_revision") or UNKNOWN + if capture_identity is not None: + if digest(capture_identity) != sha: + raise ValueError("Capture identity does not match the labeled set's capture") + return cls.from_capture_identity(cache, capture_identity, dataset_revision=revision) + combined = f"capture:{sha}" + return cls(cache=cache, tokenizer=combined, model=combined, adapter=combined, + weights=combined, dataset_revision=revision, capture=sha) + + def identity(self, *, kind, algorithm, site, partition, fold, normalization, parameters, + data) -> ReuseIdentity: + return ReuseIdentity( + kind=kind, algorithm=algorithm, site=f"{self.readout}:{site}", partition=partition, + fold=fold, normalization=normalization, tokenizer=self.tokenizer, model=self.model, + adapter=self.adapter, weights=self.weights, dataset_revision=self.dataset_revision, + parameters=digest(parameters), data=data) + + +__all__ = ["ALL_ROWS", "FIELDS", "ReuseContamination", "ReuseIdentity", "ReuseRefused", + "ReuseScope", "admit", "compare", "content_digest", "fold_scope"] diff --git a/obliteratus/concepts/extraction.py b/obliteratus/concepts/extraction.py index 6e0cad21..b16ca82b 100644 --- a/obliteratus/concepts/extraction.py +++ b/obliteratus/concepts/extraction.py @@ -387,9 +387,13 @@ def select_intervention_layers(extraction_layers, results, residual_norms, rule) def extract_directions( positive: dict[int, torch.Tensor], controls: dict[str, dict[int, torch.Tensor]], recipe: ExtractionRecipe, *, seed: int | None = None, preset_layers=None, - warn_alias: bool = True, sample_groups=None, **metadata, + warn_alias: bool = True, sample_groups=None, reuse=None, **metadata, ) -> ConceptDirection: - """Fit all layers, score held-out folds, then refit on all cached samples.""" + """Fit all layers, score held-out folds, then refit on all cached samples. + + ``reuse`` (a ``ReuseScope``) opts in to exact reuse of whole-set and per-fold + layer fits; results are bit-identical and the default path is unchanged. + """ effective_direction_method(recipe.method, warn_alias=warn_alias, stacklevel=3) validate_recipe(recipe) if not positive or not controls: @@ -407,10 +411,15 @@ def extract_directions( len(group[layer]) != counts[f"control:{name}"] for name, group in controls.items() )): raise ValueError("Sample counts must agree across cached layers") + def fit(layer, pos, ctrl, fold=None): + return extract_layer(pos, ctrl, recipe, warn_alias=False) + if reuse is not None: + from obliteratus.analysis.reuse_consumers import extraction_fitter + fit = extraction_fitter(reuse, positive, controls, recipe, extract_layer) results, residual_norms = {}, {} for layer in layers: groups = {name: group[layer] for name, group in controls.items()} - results[layer] = extract_layer(positive[layer], groups, recipe, warn_alias=False) + results[layer] = fit(layer, positive[layer], groups) samples, weights, _ = _control_distribution(groups, recipe.pool_controls) residual_norms[layer] = ( (positive[layer].norm(dim=1).mean() + weights @ samples.norm(dim=1)) / 2 @@ -434,10 +443,10 @@ def extract_directions( part for i, part in enumerate(parts) if i != fold ]) return chosen.to(positive[layer].device) - fitted = extract_layer( - positive[layer][indices("positive")], + fitted = fit( + layer, positive[layer][indices("positive")], {name: group[layer][indices(f"control:{name}")] - for name, group in controls.items()}, recipe, warn_alias=False, + for name, group in controls.items()}, (fold, folds, splits), ).subspace[0] pos_scores = positive[layer][indices("positive", True)] @ fitted aucs, sizes = [], [] diff --git a/tests/test_reuse_cache.py b/tests/test_reuse_cache.py new file mode 100644 index 00000000..a3603816 --- /dev/null +++ b/tests/test_reuse_cache.py @@ -0,0 +1,260 @@ +"""O04 reuse cache: identity refusal, exactness, accounting and incremental statistics.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, replace + +import pytest +import torch + +from obliteratus.analysis.incremental_stats import EXACT, INCREMENTAL, PooledMoments +from obliteratus.analysis.reuse_cache import ReuseCache, clone, nbytes +from obliteratus.analysis.reuse_identity import ( + FIELDS, ReuseContamination, ReuseIdentity, ReuseRefused, ReuseScope, admit, compare, + content_digest, fold_scope, +) + +pytestmark = pytest.mark.cpu + + +def identity(**changes): + base = {name: f"{name}-v1" for name in FIELDS} + base.update(fold="all") + return ReuseIdentity(**{**base, **changes}) + + +class Clock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + self.now += 1.0 + return self.now + + +def test_fold_scope_and_content_digest(): + assert fold_scope() == "all" + assert fold_scope(1, 5) == "train:1/5" + assert fold_scope(0, 3, "heldout") == "heldout:0/3" + with pytest.raises(ValueError): + fold_scope(5, 5) + with pytest.raises(ValueError): + fold_scope(0, 2, "test") + x = torch.arange(6.0).reshape(2, 3) + assert content_digest(x) == content_digest(x.clone()) + assert content_digest(x) != content_digest(x.double()) + assert content_digest(x) != content_digest(x.reshape(3, 2)) + assert content_digest(torch.empty(0)) != content_digest([]) + + +@pytest.mark.parametrize("field", [f for f in FIELDS if f != "fold"]) +def test_every_identity_field_refuses_reuse(field): + stored, requested = identity(), identity(**{field: f"{field}-v2"}) + reasons = compare(stored, requested) + assert [r["field"] for r in reasons] == [field] + assert not reasons[0]["contamination"] + with pytest.raises(ReuseRefused) as error: + admit(stored, requested) + assert not isinstance(error.value, ReuseContamination) + cache = ReuseCache() + cache.fetch(stored, lambda: torch.ones(2)) + value, outcome = cache.fetch(requested, lambda: torch.zeros(2)) + assert torch.equal(value, torch.zeros(2)) + event = cache.report()["events"][-1] + if field in ("kind", "site"): + # Entries are compared only within one kind and site: a different artifact, not a refusal. + assert outcome == event["outcome"] == "miss" and event["reasons"][0]["field"] is None + else: + assert outcome == event["outcome"] == "refused" + assert event["reasons"][0]["field"] == field + + +@pytest.mark.parametrize("stored_fold,requested_fold", [ + ("all", "train:0/5"), ("all", "heldout:0/5"), ("train:1/5", "train:0/5"), + ("heldout:0/5", "train:0/5")]) +def test_cross_fold_and_all_data_statistics_are_contaminated(stored_fold, requested_fold): + stored, requested = identity(fold=stored_fold), identity(fold=requested_fold) + with pytest.raises(ReuseContamination, match="leak"): + admit(stored, requested) + cache = ReuseCache() + cache.fetch(stored, lambda: torch.ones(1)) + value, outcome = cache.fetch(requested, lambda: torch.full((1,), 7.0)) + assert outcome == "refused" and value.item() == 7.0 + assert cache.report()["events"][-1]["reasons"][0]["contamination"] is True + + +def test_fold_statistic_cannot_serve_all_rows_but_is_not_contamination(): + reasons = compare(identity(fold="train:0/5"), identity(fold="all")) + assert reasons == [{"field": "fold", "contamination": False, + "reason": "stored fold differs from the requested fold"}] + + +@pytest.mark.parametrize("field", ["tokenizer", "weights", "adapter", "dataset_revision"]) +def test_unknown_fields_are_never_reusable(field): + unknown = identity(**{field: "unknown"}) + assert unknown.unobservable() == [field] + with pytest.raises(ReuseRefused): + admit(unknown, unknown) + cache = ReuseCache() + calls = [] + for _ in range(2): + _, outcome = cache.fetch(unknown, lambda: calls.append(1) or torch.ones(1)) + assert outcome == "not_reusable" + assert len(calls) == 2 and len(cache) == 0 + assert cache.report()["not_reusable"] == 2 + + +def test_exact_hit_is_bitwise_and_isolated_from_mutation(): + cache = ReuseCache(clock=Clock()) + source = torch.randn(4, 3, generator=torch.Generator().manual_seed(1)) + first, outcome = cache.fetch(identity(), lambda: {"m": source.clone(), "n": [1, (2,)]}, + ops=100, input_bytes=48) + assert outcome == "miss" + first["m"].zero_() + second, outcome = cache.fetch(identity(), lambda: pytest.fail("recomputed")) + assert outcome == "hit" and torch.equal(second["m"], source) + assert second["n"] == [1, (2,)] + report = cache.report() + assert (report["lookups"], report["hits"], report["misses"]) == (2, 1, 1) + assert report["avoided"]["estimated_ops"] == 100 + assert report["avoided"]["input_bytes"] == 48 + assert report["avoided"]["recorded_compute_seconds"] == 1.0 + assert report["setup"]["compute_seconds"] == 1.0 + assert report["setup"]["overhead_seconds"] > 0 + amortization = report["amortization"] + assert amortization["setup_seconds"] == pytest.approx( + report["setup"]["compute_seconds"] + report["setup"]["overhead_seconds"]) + assert amortization["uses"] == 2 + assert "does not disappear" in amortization["note"] + hit = report["events"][1] + assert hit["outcome"] == "hit" and hit["validity"]["matched_fields"] == list(FIELDS) + assert report["approximation"]["sketches"] == [] + json.dumps(report, allow_nan=False) + + +def test_eviction_bound_and_oversized_entries(): + with pytest.raises(ValueError): + ReuseCache(max_bytes=-1) + cache = ReuseCache(max_bytes=64) + cache.fetch(identity(data="a"), lambda: torch.zeros(8)) # 32 bytes + cache.fetch(identity(data="b"), lambda: torch.zeros(8)) + cache.fetch(identity(data="c"), lambda: torch.zeros(8)) + assert len(cache) == 2 and cache.report()["evicted"] == 1 + cache.fetch(identity(data="big"), lambda: torch.zeros(100)) + assert len(cache) == 2 and cache.report()["resident_bytes"] == 64 + + +@dataclass +class Box: + tensor: torch.Tensor + label: str + + +def test_clone_and_nbytes_cover_dataclasses(): + box = Box(torch.ones(3), "x") + copied = clone(box) + copied.tensor.zero_() + assert box.tensor.sum() == 3 and nbytes(box) == 12 and nbytes(None) == 0 + + +def scope(**changes): + capture = {"checkpoint": {"model_id": "m"}, "tokenizer": {"name": "t"}, + "adapter": {"state": "none"}, "readout": {"name": "decoder_output", + "phase": "prompt"}, + "dataset_revision": "rev1", "weights": {"mode": "sampled", "sha256": "w" * 64}} + capture.update(changes) + return ReuseScope.from_capture_identity(ReuseCache(), capture) + + +def test_scope_splits_capture_identity_into_fields(): + base = scope() + assert base.weights == "sampled:" + "w" * 64 and base.readout == "decoder_output/prompt" + for field, change in (("tokenizer", {"tokenizer": {"name": "u"}}), + ("model", {"checkpoint": {"model_id": "n"}}), + ("adapter", {"adapter": {"state": "peft", "adapters": []}}), + ("weights", {"weights": {"mode": "sampled", "sha256": "v" * 64}}), + ("dataset_revision", {"dataset_revision": "rev2"})): + assert getattr(scope(**change), field) != getattr(base, field) + assert scope(adapter={"state": "unknown"}).adapter == "unknown" + assert scope(weights=None).weights == "unknown" + built = base.identity(kind="k", algorithm="a/1", site="layer:3", partition="p", + fold="all", normalization="none", parameters={"x": 1}, data="d") + assert built.site == "decoder_output/prompt:layer:3" and not built.unobservable() + + +@dataclass +class Labeled: + manifest: dict + + +def test_scope_from_labeled_binds_combined_capture_digest(): + from obliteratus.analysis.capture_identity import digest + + capture = {"checkpoint": {"model_id": "m"}, "tokenizer": {}, "adapter": {"state": "none"}, + "readout": {"name": "r", "phase": "p"}, "weights": {"mode": "full", + "sha256": "a" * 64}} + labeled = Labeled({"capture_identity_sha256": digest(capture), "dataset_revision": "r1"}) + combined = ReuseScope.from_labeled(ReuseCache(), labeled) + assert combined.tokenizer == combined.weights == "capture:" + digest(capture) + full = ReuseScope.from_labeled(ReuseCache(), labeled, capture) + assert full.dataset_revision == "r1" and full.weights == "full:" + "a" * 64 + with pytest.raises(ValueError, match="does not match"): + ReuseScope.from_labeled(ReuseCache(), labeled, {**capture, "tokenizer": {"x": 1}}) + + +def rows(seed, n, d=5, offset=0.0): + return torch.randn(n, d, generator=torch.Generator().manual_seed(seed), + dtype=torch.float64) * 3 + offset + + +def test_incremental_moments_agree_with_full_recomputation(): + scope_id = identity(algorithm="moments") + blocks = [rows(1, 30, offset=100.0), rows(2, 7, offset=-50.0), rows(3, 64)] + moments = PooledMoments.from_rows(blocks[0], scope_id) + assert moments.exact and moments.identity.algorithm.endswith(EXACT) + for block in blocks[1:]: + moments = moments.append(block) + full = PooledMoments.from_rows(torch.cat(blocks), scope_id) + agreement = moments.agreement(full) + assert agreement["within_budget"] and not agreement["exact"] + assert moments.identity.algorithm.endswith(INCREMENTAL) + assert moments.identity.key != full.identity.key + assert torch.allclose(moments.covariance(), torch.cov(torch.cat(blocks).T), atol=1e-9) + assert torch.allclose(moments.mean, torch.cat(blocks).mean(0), atol=1e-12) + with pytest.raises(ValueError): + moments.agreement(PooledMoments.from_rows(blocks[0], scope_id)) + + +def test_incremental_moments_refuse_unsafe_merges(): + scope_id = identity() + base = PooledMoments.from_rows(rows(1, 4), scope_id, row_keys=["a", "b", "c", "d"]) + with pytest.raises(ReuseRefused, match="overlapping"): + base.append(rows(2, 2), row_keys=["d", "e"]) + with pytest.raises(ReuseRefused, match="one side"): + base.append(rows(2, 2)) + with pytest.raises(ReuseRefused, match="twice"): + PooledMoments.from_rows(rows(1, 4), scope_id).append(rows(1, 4)) + with pytest.raises(ReuseRefused, match="widths"): + PooledMoments.from_rows(rows(1, 4), scope_id).append(rows(2, 4, d=3)) + with pytest.raises(ReuseRefused, match="site"): + base.merge(PooledMoments.from_rows(rows(3, 2), replace(scope_id, site="other"), + ["x", "y"])) + train = PooledMoments.from_rows(rows(1, 4), identity(fold="train:0/5")) + with pytest.raises(ReuseContamination): + train.merge(PooledMoments.from_rows(rows(2, 4), identity(fold="heldout:0/5"))) + with pytest.raises(ValueError): + PooledMoments.from_rows(torch.empty(0, 3), scope_id) + with pytest.raises(ValueError): + PooledMoments.from_rows(rows(1, 3), scope_id, row_keys=["a"]) + with pytest.raises(ValueError): + PooledMoments.from_rows(rows(1, 1), scope_id).covariance() + merged = base.append(rows(4, 2), row_keys=["e", "f"]) + assert merged.count == 6 and merged.row_keys == frozenset("abcdef") + + +def test_float32_rows_are_accumulated_in_float64(): + x = torch.randn(10, 4, generator=torch.Generator().manual_seed(9)) + moments = PooledMoments.from_rows(x[:5], identity()).append(x[5:]) + assert moments.sum.dtype == torch.float64 + assert moments.agreement(PooledMoments.from_rows(x, identity()))["within_budget"] diff --git a/tests/test_reuse_consumers.py b/tests/test_reuse_consumers.py new file mode 100644 index 00000000..fd5a2c3e --- /dev/null +++ b/tests/test_reuse_consumers.py @@ -0,0 +1,165 @@ +"""O04 opt-in reuse in extraction and candidate discovery: bit-identical outcomes.""" + +from __future__ import annotations + +import json +from dataclasses import replace + +import pytest +import torch + +from obliteratus.analysis.candidate_discovery import discover_candidates +from obliteratus.analysis.labeled_selection import LabeledSelection +from obliteratus.analysis.reuse_cache import ReuseCache +from obliteratus.analysis.reuse_consumers import cache_fetch, labeled_matrix +from obliteratus.analysis.reuse_identity import ReuseRefused, ReuseScope +from obliteratus.concepts.extraction import extract_directions +from tests.test_concept_extraction import cv_recipe, planted_cache + +pytestmark = pytest.mark.cpu +OPTIONS = {"n_permutations": 6, "n_bootstrap": 5, "n_random": 8, "folds": 3} + + +@pytest.fixture(autouse=True) +def single_thread(): + previous = torch.get_num_threads() + torch.set_num_threads(1) + yield + torch.set_num_threads(previous) + + +def make_scope(cache=None, **changes): + fields = {"tokenizer": "tok", "model": "model", "adapter": "none", + "weights": "sampled:" + "a" * 64, "dataset_revision": "rev1", "capture": None} + fields.update(changes) + return ReuseScope(cache=ReuseCache() if cache is None else cache, **fields) + + +def assert_same_direction(left, right): + assert left.extraction_layers == right.extraction_layers + assert left.intervention_layers == right.intervention_layers + assert left.cv_scores == right.cv_scores + for name in ("directions", "subspaces", "reference_means", "projector_left", + "projector_right"): + a, b = getattr(left, name), getattr(right, name) + assert a.keys() == b.keys() + assert all(torch.equal(a[k], b[k]) for k in a) + + +@pytest.mark.parametrize("method", ["diff_means", "fisher_lda", "leace_exact"]) +def test_extraction_reuse_is_bit_identical_and_avoids_fold_refits(method): + positive, controls = planted_cache() + recipe = cv_recipe(method=method) + fresh = extract_directions(positive, controls, recipe, seed=227) + scope = make_scope() + cold = extract_directions(positive, controls, recipe, seed=227, reuse=scope) + assert_same_direction(fresh, cold) + after_cold = scope.cache.report() + layers, folds = len(positive), recipe.layer_select["folds"] + assert after_cold["misses"] == layers * (folds + 1) and after_cold["hits"] == 0 + other_rule = replace(recipe, intervention_layer={"rule": "norm_ratio", "target": 0.5}) + warm = extract_directions(positive, controls, other_rule, seed=227, reuse=scope) + assert_same_direction(extract_directions(positive, controls, other_rule, seed=227), warm) + report = scope.cache.report() + assert report["hits"] == layers * (folds + 1) + assert report["avoided"]["estimated_ops"] > 0 and report["avoided"]["input_bytes"] > 0 + assert {e["fold"] for e in report["events"]} == {"all"} | { + f"train:{k}/{folds}" for k in range(folds)} + assert all(e["validity"]["matched_fields"] for e in report["events"] + if e["outcome"] == "hit") + + +def test_extraction_reuse_misses_when_fit_inputs_change(): + positive, controls = planted_cache() + scope = make_scope() + extract_directions(positive, controls, cv_recipe(), seed=227, reuse=scope) + before = scope.cache.report()["hits"] + extract_directions(positive, controls, cv_recipe(), seed=228, reuse=scope) + # Whole-set fits are shared; a different seed changes every fold split. + assert scope.cache.report()["hits"] - before == len(positive) + changed = {layer: value + 1e-3 for layer, value in positive.items()} + hits = scope.cache.report()["hits"] + extract_directions(changed, controls, cv_recipe(), seed=227, reuse=scope) + assert scope.cache.report()["hits"] == hits + extract_directions(positive, controls, cv_recipe(method="fisher_lda"), seed=227, + reuse=scope) + assert scope.cache.report()["hits"] == hits + other_model = make_scope(scope.cache, weights="sampled:" + "b" * 64) + extract_directions(positive, controls, cv_recipe(), seed=227, reuse=other_model) + report = scope.cache.report() + assert report["hits"] == hits and report["refused"] > 0 + assert any(r["field"] == "weights" for e in report["events"] if e["outcome"] == "refused" + for r in e["reasons"]) + + +def test_extraction_preset_path_with_reuse_matches_default(): + positive, controls = planted_cache() + recipe = replace(cv_recipe(), layer_select={"strategy": "preset", "preset": "all"}) + scope = make_scope() + for _ in range(2): + assert_same_direction(extract_directions(positive, controls, recipe), + extract_directions(positive, controls, recipe, reuse=scope)) + assert scope.cache.report()["hits"] == len(positive) + + +def labeled_fixture(seed=5, revision="rev1", capture="c" * 64): + generator = torch.Generator().manual_seed(seed) + sets = ["positive"] * 24 + ["control:neutral"] * 24 + values = torch.randn(48, 6, generator=generator) + values[:24, 2] += 2.5 + roles = tuple("select" if i % 4 == 3 else "fit" for i in range(48)) + groups = tuple(f"g{i // 2}" for i in range(48)) + manifest = {"capture_identity_sha256": capture, "labels_sha256": "l" * 64, + "dataset_revision": revision, "pack": {"id": "p"}, "partitioned": True, + "locked_test_acknowledged": False} + return LabeledSelection( + manifest=manifest, values={"layer.0": values}, index=tuple(range(48)), + record_ids=tuple(f"r{i}" for i in range(48)), paths=tuple("p" for _ in range(48)), + sets=tuple(sets), kinds=tuple("positive" if s == "positive" else "control" + for s in sets), + roles=roles, groups=groups, families=tuple(None for _ in range(48))) + + +def test_discovery_null_reuse_is_bit_identical(): + labeled = labeled_fixture() + fresh = discover_candidates(labeled, "layer.0", seed=3, **OPTIONS) + scope = make_scope(capture="c" * 64) + cold = discover_candidates(labeled, "layer.0", seed=3, reuse=scope, **OPTIONS) + warm = discover_candidates(labeled, "layer.0", seed=3, reuse=scope, + **{**OPTIONS, "top_n": 3, "n_bootstrap": 7}) + assert json.dumps(fresh, sort_keys=True) == json.dumps(cold, sort_keys=True) + reference = discover_candidates(labeled, "layer.0", seed=3, + **{**OPTIONS, "top_n": 3, "n_bootstrap": 7}) + assert json.dumps(reference, sort_keys=True) == json.dumps(warm, sort_keys=True) + report = scope.cache.report() + assert (report["misses"], report["hits"]) == (1, 1) + assert report["avoided"]["estimated_ops"] > 0 + discover_candidates(labeled, "layer.0", seed=4, reuse=scope, **OPTIONS) + assert scope.cache.report()["refused"] == 1 + + +def test_discovery_refuses_scope_bound_to_another_capture_or_revision(): + labeled = labeled_fixture() + with pytest.raises(ReuseRefused, match="different capture"): + discover_candidates(labeled, "layer.0", reuse=make_scope(capture="d" * 64), **OPTIONS) + with pytest.raises(ReuseRefused, match="revision"): + discover_candidates(labeled, "layer.0", reuse=make_scope(dataset_revision="rev2"), + **OPTIONS) + + +def test_labeled_matrix_reuse_by_lineage(): + labeled = labeled_fixture() + scope = make_scope(capture="c" * 64) + first = labeled_matrix(scope, labeled, "layer.0", roles="fit") + again = labeled_matrix(scope, labeled.take(range(48)), "layer.0", roles="fit") + assert first.dtype == torch.float64 and torch.equal(first, again) + assert torch.equal(first, labeled.values["layer.0"][labeled.rows(roles="fit")].double()) + assert scope.cache.report()["hits"] == 1 + with pytest.raises(ValueError): + labeled_matrix(scope, labeled, "layer.0", roles="test") + held = labeled_matrix(scope, labeled, "layer.0", roles="fit", fold="heldout:0/3") + assert torch.equal(held, first) and scope.cache.report()["refused"] == 1 + value, outcome = cache_fetch(scope, scope.identity( + kind="custom", algorithm="a/1", site="s", partition="p", fold="all", + normalization="none", parameters={}, data="d"), lambda: 1) + assert (value, outcome) == (1, "miss")