shanto268's picture
v4 flagship Space (3 tiers) from registry v2 (earlier contents: 906bc45ae05c)
4f5e603 verified
Raw History Blame Contribute Delete
20.9 kB
"""Final recipes of the paper (paper_v3; TRAINING_PLAN Amendment E-matrix, scored by scripts/tm_final.py):
C0 = R(1.5, 3) log-Richardson of the slab lite micro-MoM at 1.5 and 3 panels per gap (no fitted parameter)
E1 = R(0.75, 1.5) + c_kind per-entry-kind log offsets of the model (no network)
E3 = R(1.5, 3) + c_kind + correction bounded (+-3 %) local correction (SceneGNN on pair tokens), mean log C of 3 seeds
The rows are built as the evaluation rows of scripts/tm_eval.py (build_one): training-convention scene (uncropped ground),
pair tokens (tlsq.uge.blocks) on every pair (pairs within 150 smallest gaps on layouts with > 8 conductors), local tokens
(localtok), and per resolution the slab lite prior (local-gap mesh on sliver layouts, PRIOR_SCHEME.md section 19; identical to
the plain lite prior elsewhere). Prediction on rows reproduces tm_final.score_em exactly (deploy/tests/test_final_parity.py).
Other substrates: the slab lite priors are solved at the requested (eps_r, thickness) and the recipe's offsets / corrections, fit on
the training stack (Si 11.45, 350 um), are applied unchanged; the features stay at the training stack (tlsq_infer.substrate).
"""
from __future__ import annotations
import copy
import hashlib
import json
import os
import time
from dataclasses import dataclass, field
from itertools import combinations
from pathlib import Path
import numpy as np
from . import __version__
from ._vendor import em as EM
from ._vendor import mom as _mom
from ._vendor.graph import prior_dict
from ._vendor.scene import make_scene
from .layout import PreparedLayout
from .registry import PRIORS, load_registry
from . import substrate as SUB
from .substrate import EPS_TRAIN, T_TRAIN
RECIPES = {"C0": (1.5, 3.0), "E1": (0.75, 1.5), "E3": (1.5, 3.0)}
TAU = 1.254e-3 # trust rule (tm_final.TAU): seed spread above this -> C0 on the near graph entries
NEAR_UM = 100.0
SPARSE_MIN, SPARSE_R_GAPS = 8, 150.0 # tm_eval: > 8 signal conductors -> pair tokens only within 150 smallest gaps
class PriorError(ValueError):
"""The physics prior produced no usable mutual entry."""
def internal_names(n_signal: int) -> list[str]:
"""Entry-kind names of the deployment convention (as predict.py and the qm116 / atlas / large-N rows): G, N, S, P1, ..."""
return ["G"] + (["N", "S"] + [f"P{k}" for k in range(1, n_signal - 1)])[:n_signal]
# ------------------------------------------------------------------ rows (tm_eval.build_one)
def far_mask(metals: list) -> np.ndarray:
import shapely
from ._vendor.fastprior import gap_of
n = len(metals)
far = np.zeros((n, n), bool)
if n - 1 <= SPARSE_MIN:
return far
conds = list(metals[1:])
a, b = shapely.STRtree(conds).query(conds, predicate="dwithin", distance=SPARSE_R_GAPS * gap_of(list(metals)))
far[:] = True
far[a + 1, b + 1] = False
far[0, :] = far[:, 0] = False
np.fill_diagonal(far, False)
return far
def graph(scene, far: np.ndarray) -> dict:
"""tm_eval.graph: tlsq.uge.graph.scene_graph without the prior, pairs restricted to the non-far ones."""
from ._vendor.blocks import boundary_points, edge_features, global_features, node_features
bpts, widths = boundary_points(scene)
nodes = [node_features(scene, i) for i in range(scene.n)]
edges = {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in combinations(range(scene.n), 2) if not far[i, j]}
tot = np.zeros(scene.n)
for (i, j), f in edges.items():
tot[i] += f["_cps"]
tot[j] += f["_cps"]
for (i, j), f in edges.items():
si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12)
f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj)
f.pop("_cps")
return {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges}
def solve(metals: list, ppg: float, mesh: str = "loc", eps_r: float = EPS_TRAIN, t_um: float = T_TRAIN) -> dict:
"""Slab lite micro-MoM at ppg panels per smallest gap on a substrate of eps_r and thickness t_um: mesh "loc" (training rows:
local-gap mesh on sliver layouts, otherwise the plain lite mesh) or "plain" (liteppg<p>_slab everywhere)."""
with _mom.substrate(None, float(t_um)):
if mesh == "loc":
from ._vendor.mom_loc import PRIORS_LOC, solve_prior_loc
return solve_prior_loc(metals, eps_r=float(eps_r), **PRIORS_LOC[f"liteppg{ppg:g}-slab-loc"])
return _mom.solve_prior(metals, eps_r=float(eps_r), **PRIORS[f"liteppg{ppg:g}-slab"])
def build_rows(metals: list, names: list[str], ppgs, features: bool = True, mesh: str = "loc", timing: dict | None = None,
stack: tuple | None = None) -> dict:
"""{ppg: row} for one layout (metals[0] = ground; names[0] = 'G'). features=False: prior matrices only (C0 / E1).
stack: (eps_r, thickness_um) the priors are solved at (default the training stack); the features always use the training stack."""
timing = {} if timing is None else timing
t = time.perf_counter()
far = far_mask(metals)
g = {"names": list(names), "nodes": [], "edges": {}, "global": {}}
if features:
from .localtok import add_tokens
sc = make_scene(metals[0], list(metals[1:]), list(names[1:]))
timing["scene_s"] = time.perf_counter() - t
t = time.perf_counter()
g = graph(sc, far)
timing["features_s"] = time.perf_counter() - t
t = time.perf_counter()
g = add_tokens(sc, g)
timing["tokens_s"] = time.perf_counter() - t
out = {}
for p in ppgs:
t = time.perf_counter()
px = solve(metals, p, mesh, *(stack or (EPS_TRAIN, T_TRAIN)))
timing[f"prior_ppg{p:g}_s"] = time.perf_counter() - t
r = copy.deepcopy(g)
d = prior_dict(px["C"], px["n_cells"], px["h_min"], list(g["edges"]), (px.get("mesh") or {}).get("min_gap_um"))
for i, v in d["node"].items():
if features:
r["nodes"][i].update({f"proxy_{k}": x for k, x in v.items()})
for e, v in d["edge"].items():
r["edges"][e].update({f"proxy_{k}": x for k, x in v.items()})
r["global"].update({f"proxy_{k}": x for k, x in d["global"].items()})
r["proxy_matrix"] = px["C"]
r["_mesh"] = px.get("mesh") or {}
out[p] = r
out["far"] = far
return out
# ------------------------------------------------------------------ models
@dataclass
class FinalModel:
name: str
recipe: str
pair: tuple
c_kind: dict = field(default_factory=dict)
scaling: dict | None = None
nets: list = field(default_factory=list)
files_sha256: list = field(default_factory=list)
entry: dict = field(default_factory=dict)
def _sha(f) -> str:
return hashlib.sha256(Path(f).read_bytes()).hexdigest()
def _paths(reg, name: str, model_dir=None) -> tuple[str, Path | None]:
"""("export", dir) for an exported model (<model_dir>/<name>/info.json: Space bundle) or ("source", path) for the
training artefacts named in the registry (repository checkout)."""
m = reg["final_models"][name]
md = os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir
if md and (Path(md) / name / "info.json").exists():
return "export", Path(md) / name
if m.get("source"):
return "source", reg.root / m["source"]
return "none", None
_CACHE: dict = {}
def load_model(name: str, registry=None, model_dir=None) -> FinalModel:
reg = registry or load_registry()
key = (str(reg.path), name, str(os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir))
if key in _CACHE:
return _CACHE[key]
m = reg["final_models"][name]
recipe, pair = m["recipe"], tuple(float(x) for x in m["pair"])
fm = FinalModel(name, recipe, pair, entry={"name": name, **m})
kind, p = _paths(reg, name, model_dir)
if recipe == "E1":
f = p / "info.json" if kind == "export" else p
fm.c_kind = json.loads(Path(f).read_text())["c_kind"]
fm.files_sha256 = [_sha(f)]
elif recipe == "E3":
import torch
lo = pair[0]
if kind == "export":
info = json.loads((p / "info.json").read_text())
files = [p / f for f in info["files"]]
states = [torch.load(f, map_location="cpu", weights_only=True) for f in files]
else:
info = json.loads((p / f"info_p{lo:g}.json").read_text())
files = [p / f"s{s}_p{lo:g}.pt" for s in (0, 1, 2)]
states = [torch.load(f, map_location="cpu", weights_only=False)["state"] for f in files]
fm.c_kind = info["c_kind"]
fm.scaling = {k: np.asarray(v) for k, v in info["scaling"].items()}
assert list(info.get("edge_keys", EM.EDGE_KEYS)) == list(EM.EDGE_KEYS), f"{name}: edge keys differ from the package"
for st in states:
net = EM.make_model(len(EM.EDGE_KEYS))
net.load_state_dict(st)
net.eval()
fm.nets.append(net)
fm.files_sha256 = [_sha(f) for f in files]
elif recipe != "C0":
raise ValueError(f"{name}: unknown recipe {recipe!r}")
_CACHE[key] = fm
return fm
def export_model(name: str, dst, registry=None) -> list[str]:
"""Weights-only export of a final model into dst (Space bundle / model repo): info.json (+ seed<k>.pt state dicts)."""
import torch
reg = registry or load_registry()
fm = load_model(name, reg, model_dir="")
dst = Path(dst)
dst.mkdir(parents=True, exist_ok=True)
m = reg["final_models"][name]
info = {"name": name, "recipe": fm.recipe, "pair": list(fm.pair), "c_kind": fm.c_kind, "ledger_id": m.get("ledger_id"),
"role": m.get("role"), "package_version": __version__, "source_sha256": fm.files_sha256, "files": []}
if fm.recipe == "E3":
info["scaling"] = {k: np.asarray(v).tolist() for k, v in fm.scaling.items()}
info["edge_keys"] = list(EM.EDGE_KEYS)
for k, net in enumerate(fm.nets):
torch.save({k_: v.clone() for k_, v in net.state_dict().items()}, dst / f"seed{k}.pt")
info["files"].append(f"seed{k}.pt")
(dst / "info.json").write_text(json.dumps(info, indent=1))
return ["info.json"] + info["files"]
# ------------------------------------------------------------------ prediction on rows (tm_final.score_em)
def predict_rows(model: FinalModel, pairs: list, seeds: bool = False):
"""pairs: [(row_lo, row_hi)] at model.pair. Returns a list of (n, n) log|C_ij| matrices (diagonal NaN), in the order of
the rows; seeds=True also returns the per-seed E3 matrices (S, n, n) per design (None for C0 / E1). One batch, as
tm_final (E3: one pack of all rows; the padding is max(8, max n))."""
out, per_seed = [], []
if model.recipe == "E3":
items = [EM.item(rl, rh) for rl, rh in pairs]
d = EM.pack(items)
d["E"] = EM.apply_scale(d["E"], d["A"], model.scaling)
cvec = np.array([0.0] + [model.c_kind[k] for k in EM.KIND_ID], np.float32)
P = np.asarray([EM.predict(net, d, np.arange(len(items)), cvec) for net in model.nets])
Pm = np.mean(P, 0)
for b, (rl, rh) in enumerate(pairs):
nm = list(rh["names"])
n = len(nm)
LR, _ = EM.logR(rl, rh)
L = np.full((n, n), np.nan)
for i in range(n):
for j in range(i + 1, n):
if model.recipe == "E3":
v = float(Pm[b, i, j])
elif model.recipe == "E1":
v = float(LR[i, j] + model.c_kind[EM.entry_kind(nm[i], nm[j])])
else:
v = float(LR[i, j])
L[i, j] = L[j, i] = v
out.append(L)
per_seed.append(P[:, b, :n, :n] if model.recipe == "E3" else None)
return (out, per_seed) if seeds else out
def pair_distance_um(metals: list, pairs) -> dict:
"""{(i, j): exact polygon distance (um)} for the given pairs: the paper's pair distance (scripts/grid_scaling.pair_distances,
the near / far slices of the test tables; ground pairs included)."""
import shapely
return {(i, j): float(shapely.distance(metals[i], metals[j])) for i, j in pairs}
def seed_spread(seeds: np.ndarray, row: dict, near_um: float | None = NEAR_UM, dist: dict | None = None) -> tuple[float, np.ndarray]:
"""Trust statistic of tm_final (TRUST): median seed std over the near graph entries (pairs with an edge and a pair distance
below near_um: dist = pair_distance_um, else the edge feature's sampled minimum distance; near_um=None: every graph edge,
the convention of rows without a pair distance); returns (s, near mask)."""
n = len(row["names"])
near = np.zeros((n, n), bool)
for (a, b), f in row["edges"].items():
d = dist[(a, b)] if dist is not None else np.exp(f["log_dmin"])
if near_um is None or d < near_um:
near[a, b] = near[b, a] = True
sd = seeds.std(0)[:n, :n]
return (float(np.median(sd[near])) if near.any() else float("inf")), near
def apply_trust(L: np.ndarray, seeds: np.ndarray, LR: np.ndarray, row: dict, near_um: float | None = NEAR_UM,
dist: dict | None = None) -> tuple[np.ndarray, dict]:
"""Trust rule (TRAINING_PLAN Amendment Trust rule; tm_final TRUST, tau fixed before unblinding): s = seed spread over the near
graph entries. s <= TAU: E3 (L) on the near entries, C0 (LR) on every other entry; s > TAU: C0 on every entry. Returns the
log|C| matrix and the trust record."""
s, near = seed_spread(seeds, row, near_um, dist)
use = s <= TAU
out = np.where(use & near, L, LR)
np.fill_diagonal(out, np.nan)
rec = {"seed_spread": s, "tau": TAU, "exceeds_tau": bool(s > TAU), "applied": True, "fallback_to_C0": not use,
"used": "E3 on near entries, C0 elsewhere" if use else "C0 (seed spread above tau)",
"near_um": near_um, "n_near_entries": int(np.triu(near, 1).sum()),
"n_E3_entries": int(np.triu(near, 1).sum()) if use else 0}
return out, rec
# ------------------------------------------------------------------ layout -> Maxwell matrix
def model_names(registry=None) -> list[str]:
reg = registry or load_registry()
return [k for k, v in (reg.data.get("final_models") or {}).items() if v.get("status", "available") == "available"]
def available(name: str, registry=None, model_dir=None) -> bool:
reg = registry or load_registry()
m = reg["final_models"][name]
if m["recipe"] == "C0":
return True
kind, p = _paths(reg, name, model_dir)
if kind == "export":
return True
if kind == "none":
return False
return p.exists() and (m["recipe"] == "E1" or all((p / f"s{s}_p{float(m['pair'][0]):g}.pt").exists() for s in (0, 1, 2)))
def predict_final(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0,
self_from_rows: bool = True, names: list[str] | None = None, registry=None, model_dir=None, mesh: str = "loc",
trust_rule: bool | None = None, trust_near_um: float | None = NEAR_UM, return_debug: bool = False) -> dict:
"""Maxwell capacitance matrix (fF) of a prepared layout with a final recipe (registry final_models; default
final_defaults.model). names: entry-kind names (default G, N, S, P1, ...: the deployment convention). Self terms: row
sums / (1 - row_sum_eps) (not trained, not scored) when self_from_rows, else not returned (null). trust_rule (E3 recipes):
the paper's seed-spread rule (apply_trust); None = registry final_defaults.trust_rule (on), False = raw E3 (spread still
reported). trust_near_um: near = graph pairs whose polygon distance (the paper's pair distance) is below this; None = every
graph pair."""
reg = registry or load_registry()
if trust_rule is None:
trust_rule = bool(reg["final_defaults"].get("trust_rule", True))
model = model or reg["final_defaults"]["model"]
if model not in (reg.data.get("final_models") or {}):
raise ValueError(f"unknown final model {model!r}; available: {model_names(reg)}")
t_all = time.perf_counter()
timing: dict = {}
t = time.perf_counter()
fm = load_model(model, reg, model_dir)
timing["load_s"] = time.perf_counter() - t
eps, t_um = reg.eps_of(substrate), float(thickness_um)
sub, sub_w = SUB.route(eps, t_um, physics_only=(fm.recipe == "C0"))
metals = [prepared.ground] + list(prepared.conductors)
k = len(metals)
nm = list(names) if names is not None else internal_names(k - 1)
lo, hi = fm.pair
need = sorted({lo, hi} | ({1.5, 3.0} if trust_rule and fm.recipe == "E3" else set()))
rows = build_rows(metals, nm, need, features=(fm.recipe == "E3"), mesh=mesh, timing=timing, stack=(eps, t_um))
for p in need:
mut = -np.asarray(rows[p]["proxy_matrix"])[np.triu_indices(k, 1)]
if not np.all(np.isfinite(mut)) or np.any(mut <= 0):
raise PriorError(f"the slab lite prior at {p:g} panels per gap returned {int((~np.isfinite(mut)).sum())} non-finite and "
f"{int((mut <= 0).sum())} non-positive mutual entries on this layout: no matrix is returned")
t = time.perf_counter()
L, S = predict_rows(fm, [(rows[lo], rows[hi])], seeds=True)
L, S = L[0], S[0]
timing["network_s" if fm.recipe == "E3" else "recipe_s"] = time.perf_counter() - t
debug = {"rows": rows, "logC": L.copy()}
trust = None
if fm.recipe == "E3":
dist = pair_distance_um(metals, rows[hi]["edges"]) if trust_near_um is not None else None
if trust_rule:
L, trust = apply_trust(L, S, EM.logR(rows[1.5], rows[3.0])[0], rows[hi], trust_near_um, dist)
else:
s, near = seed_spread(S, rows[hi], trust_near_um, dist)
trust = {"seed_spread": s, "tau": TAU, "exceeds_tau": bool(s > TAU), "applied": False, "fallback_to_C0": False,
"used": "E3 everywhere (trust rule switched off)", "near_um": trust_near_um, "n_near_entries": int(np.triu(near, 1).sum())}
Cabs = np.exp(L)
M = -Cabs
e_rs = float(reg["self_capacitance"]["row_sum_eps"])
for i in range(k):
M[i, i] = np.nan
if self_from_rows:
for i in range(1, k):
M[i, i] = sum(Cabs[i, j] for j in range(k) if j != i) / (1 - e_rs)
timing["total_s"] = time.perf_counter() - t_all
timing["threads"] = int(_mom.NUM_THREADS or 0) or None
labels = ["G"] + list(prepared.names)
iu = np.triu_indices(k, 1)
mut = np.abs(M[iu])
m = fm.entry
acc = m.get("accuracy") or {}
warnings = list(prepared.warnings)
far = rows["far"]
if far.any():
warnings.append(f"{int(np.triu(far, 1).sum())} conductor pairs farther apart than {SPARSE_R_GAPS:g} smallest gaps have no pair "
"tokens (large layout); their entries carry the prior's long-range value (aF scale, weakest entries)")
if trust and trust["exceeds_tau"]:
warnings.append(f"trust rule: seed spread {trust['seed_spread']:.3g} > tau {TAU:g}: "
+ ("fell back to the physics-only C0 recipe for this whole layout" if trust["applied"] else
"the rule (switched off here) would use the physics-only C0 recipe for this layout"))
warnings += sub_w
mesh_info = {p: rows[p]["_mesh"] for p in need}
out = {"names": labels, "matrix_fF": [[None if np.isnan(v) else float(v) for v in row] for row in M], "units": "fF",
"convention": "Maxwell matrix: diagonal = self, off-diagonal = -mutual; row/column 0 = ground (self not predicted)",
"self_capacitance": (f"row sums / (1 - {e_rs}); not trained, not scored" if self_from_rows else "not returned"),
"model": model, "model_title": m.get("title"), "recipe": fm.recipe, "pair": list(fm.pair), "role": m.get("role"),
"ledger_id": m.get("ledger_id"), "weights_sha256": fm.files_sha256, "package_version": __version__,
"registry_version": reg["version"], "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}",
"eps_r": eps, "thickness_um": t_um, "substrate_route": sub,
"training_stack": {"eps_r": EPS_TRAIN, "thickness_um": T_TRAIN}, "kind_names": nm, "timing_s": timing,
"prior_mesh": {f"{p:g}": {kk: v for kk, v in mi.items() if kk in ("prior", "local", "min_gap_um", "h_min_um", "panels", "n_windows")}
for p, mi in mesh_info.items()},
"accuracy": acc, "expected_error": {}, "trust": trust, "far_mask": far.tolist() if far.any() else None,
"warnings": warnings, "stored": False}
if m.get("warning"):
out["warnings"].insert(0, m["warning"])
if return_debug:
out["debug"] = debug
return out