# -*- coding: utf-8 -*- """Shared plumbing for the BCS/BES/ISS/KTS metric stack. Everything here is deliberately read-only with respect to data/: the fact set and the query bank are frozen artefacts (protocol 2.1), and this package only consumes them. Path resolution has one rule: entries under `paths:` in configs/metrics.yaml are taken relative to the repository root unless they are absolute, and each is overridable by an environment variable so nobody has to edit a tracked config to run on their own filesystem. """ import os, json, math, functools import numpy as np import yaml HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) CONFIGS = os.path.join(ROOT, "configs") @functools.lru_cache(maxsize=None) def cfg(): with open(os.path.join(CONFIGS, "metrics.yaml")) as f: return yaml.safe_load(f) def _root(key, env): p = os.environ.get(env) or cfg()["paths"][key] return p if os.path.isabs(p) else os.path.join(ROOT, p) def data_file(name): """A frozen input artefact: the fact set or the query bank.""" return os.path.join(_root("data", "FKS_DATA"), name) def runner_dir(): """Where eval_run.py lives; imported so the prompt format has one owner.""" return os.path.join(ROOT, "runner") @functools.lru_cache(maxsize=None) def models_cfg(): with open(os.path.join(CONFIGS, "models.yaml")) as f: return yaml.safe_load(f) def model_entry(name): for m in models_cfg()["evaluated_models"]: if m["name"] == name: return m aux = models_cfg().get("auxiliary_models", {}) for m in aux.values(): if m["name"] == name: return m raise KeyError(f"{name} is not in configs/models.yaml") def model_path(name): """Local weights if we have them, otherwise the hub id. Resolution order: $FKS_MODELS/, then configs/models.yaml:model_root (absent by default), then the entry's `hf` id, which transformers resolves against the hub. A model that is in neither the config nor the hub has to be passed explicitly by the caller. """ entry = model_entry(name) root = os.environ.get("FKS_MODELS") or models_cfg().get("model_root") if root: local = os.path.join(root, entry.get("path", name)) if os.path.isdir(local): return local if entry.get("hf"): return entry["hf"] raise SystemExit( f"cannot locate weights for {name}: set FKS_MODELS to a directory " f"containing '{entry.get('path', name)}', or add an `hf:` id to " f"configs/models.yaml") def out(kind, *parts): """kind in {evaluation, hidden, jlens, metrics}.""" p = os.path.join(_root("outputs", "FKS_OUTPUTS"), kind, *parts) os.makedirs(os.path.dirname(p) if os.path.splitext(p)[1] else p, exist_ok=True) return p def generations(model): """Where eval_run.py put this model's raw generations.""" return out("evaluation", f"{model}.jsonl") def read_jsonl(path): with open(path) as f: for line in f: line = line.strip() if line: yield json.loads(line) def write_jsonl(path, rows): os.makedirs(os.path.dirname(path), exist_ok=True) n = 0 with open(path, "w") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False, default=_jsonable) + "\n") n += 1 return n def write_json(path, obj): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as f: json.dump(obj, f, indent=2, ensure_ascii=False, default=_jsonable) def _jsonable(o): if isinstance(o, (np.floating, np.integer)): return o.item() if isinstance(o, np.ndarray): return o.tolist() raise TypeError(type(o)) # ------------------------------------------------------------------- queries QUERY_BANK = "evaluation_queries_44416.jsonl" @functools.lru_cache(maxsize=None) def main_forward_queries(): """The 39,260 queries that protocol 1.1 admits to the main analysis. The filter reads each row's own `use_for_main_forward` flag rather than testing `condition_family in main_families`: the flags are derived from eval_conditions.yaml and are what the build-time validator checks, so trusting them keeps one definition of the split instead of two that can drift. """ rows = [] for r in read_jsonl(data_file(QUERY_BANK)): if r.get("use_for_main_forward"): rows.append(r) fams = set(cfg()["main_families"]) bad = {r["condition_family"] for r in rows} - fams if bad: raise SystemExit(f"main_forward rows carry unexpected families: {bad}") return rows @functools.lru_cache(maxsize=None) def facts(): """fact_id -> record, plus the relation of each fact.""" return {r["fact_id"]: r for r in read_jsonl(data_file("benchmark_facts_2592.jsonl"))} @functools.lru_cache(maxsize=None) def fact_relation(): return {fid: r["relation"]["relation_id"] for fid, r in facts().items()} @functools.lru_cache(maxsize=None) def coverage(): """fact_id -> set of main families that actually contain it. Protocol 1.3: coverage is ragged (multilingual 2,402, context 2,591), and the two reporting modes below are both mandatory. """ cov = {} for r in main_forward_queries(): cov.setdefault(r["fact_id"], set()).add(r["condition_family"]) return cov @functools.lru_cache(maxsize=None) def complete_family_facts(): """D_cap: the facts carrying all five main families (protocol 1.3). This set is a property of the query bank, not of any model, so every model is scored on exactly the same facts -- which is the point of protocol 1.3's prohibition on per-model effective sets. """ need = set(cfg()["main_families"]) return sorted(f for f, c in coverage().items() if c >= need) def eval_fact_set(mode): if mode == "complete_family": return complete_family_facts() if mode == "full_set": return sorted(coverage()) raise ValueError(mode) # -------------------------------------------------------------- layer window def layer_window(n_layers, min_depth=None): """Protocol 7.10: {l : d_l >= min_depth}, d_l = l / (L - 1). `l` indexes decoder blocks 0..L-1, so l = L-1 is the final residual stream that J-Lens transports to. In HF terms the state is hidden_states[l+1], because hidden_states[0] is the embedding output. """ if min_depth is None: min_depth = cfg()["extraction"]["window_min_depth"] return [l for l in range(n_layers) if l / max(n_layers - 1, 1) >= min_depth - 1e-9] def late_window(n_layers): return layer_window(n_layers, cfg()["extraction"]["late_min_depth"]) # --------------------------------------------------------------- linear alg def l2_normalize(x, axis=-1, eps=1e-12): n = np.linalg.norm(x, axis=axis, keepdims=True) return x / np.maximum(n, eps) def pca_whiten(X, dim, shrinkage, eps=1e-12): """Return the whitened matrix and the fitted transform. Protocol 7.5 forbids fitting a separate transform per condition family, so this is called once per (model, layer) on the pooled matrix and the same components are then applied to every family. """ mu = X.mean(axis=0, keepdims=True) Xc = X - mu # Economy SVD on the centred matrix is the covariance eigendecomposition # without ever forming a d x d matrix -- d can be 5120 and n is ~39k. k = min(dim, Xc.shape[0], Xc.shape[1]) U, S, Vt = np.linalg.svd(Xc, full_matrices=False) U, S, Vt = U[:, :k], S[:k], Vt[:k] var = (S ** 2) / max(Xc.shape[0] - 1, 1) # lambda is expressed as a fraction of the mean retained variance so that # one config value behaves the same across models with different scales. lam = shrinkage * float(var.mean()) Z = (Xc @ Vt.T) / np.sqrt(var + lam + eps) return Z.astype(np.float32), {"mean": mu, "components": Vt, "scale": np.sqrt(var + lam + eps)} # ------------------------------------------------------------------ negatives def negative_sample(fact_ids, relation_of, max_negatives, seed): """Protocol 7.8: for each fact, up to `max_negatives` same-relation others. Drawn ONCE from the fixed fact set and reused for every model. If each model drew its own, a model could score well merely by having been handed more distant negatives. """ rng = np.random.default_rng(seed) by_rel = {} for f in fact_ids: by_rel.setdefault(relation_of[f], []).append(f) for r in by_rel: by_rel[r].sort() negs = {} for f in fact_ids: pool = [g for g in by_rel[relation_of[f]] if g != f] if len(pool) > max_negatives: idx = rng.choice(len(pool), size=max_negatives, replace=False) pool = [pool[i] for i in sorted(idx)] negs[f] = pool return negs # ----------------------------------------------------------------- bootstrap def relation_clustered_bootstrap(values, relation_of, n_resamples, seed, ci=0.95): """Protocol 14.1: resample relations, then facts within each drawn relation. A plain per-fact bootstrap would understate the interval because the 21 relations are very unevenly sized and facts inside one relation are far from independent. """ fact_ids = [f for f in values if values[f] == values[f]] # drop NaN if not fact_ids: return {"mean": float("nan"), "lo": float("nan"), "hi": float("nan"), "n": 0} by_rel = {} for f in fact_ids: by_rel.setdefault(relation_of[f], []).append(f) rels = sorted(by_rel) arr = {r: np.array([values[f] for f in by_rel[r]], dtype=np.float64) for r in rels} rng = np.random.default_rng(seed) draws = np.empty(n_resamples, dtype=np.float64) for b in range(n_resamples): picked = rng.integers(0, len(rels), size=len(rels)) pool = [] for i in picked: a = arr[rels[i]] pool.append(a[rng.integers(0, len(a), size=len(a))]) draws[b] = np.concatenate(pool).mean() lo, hi = np.percentile(draws, [(1 - ci) / 2 * 100, (1 + ci) / 2 * 100]) point = float(np.mean([values[f] for f in fact_ids])) return {"mean": point, "lo": float(lo), "hi": float(hi), "n": len(fact_ids)}