archc 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. ac/__init__.py +0 -0
  2. ac/ablation_fit.py +291 -0
  3. ac/architecture.py +1134 -0
  4. ac/auto_calibrate.py +2235 -0
  5. ac/baseline.py +672 -0
  6. ac/baseline_delta.py +492 -0
  7. ac/budget_pareto.py +933 -0
  8. ac/calibration/b200_calibration.json +179 -0
  9. ac/calibration/family_bias_v1.json +125 -0
  10. ac/calibration/h100_calibration.json +155 -0
  11. ac/calibration/tpu_v5p_calibration.json +153 -0
  12. ac/cli_compile.py +2479 -0
  13. ac/cli_delta_eval.py +802 -0
  14. ac/cli_matrix18b.py +358 -0
  15. ac/cli_recipe.py +662 -0
  16. ac/cli_stress.py +784 -0
  17. ac/cli_trust_audit.py +248 -0
  18. ac/decision.py +801 -0
  19. ac/delta_engine.py +361 -0
  20. ac/deltas/__init__.py +56 -0
  21. ac/deltas/add_state_layers.py +155 -0
  22. ac/deltas/base.py +257 -0
  23. ac/deltas/change_moe_topology.py +44 -0
  24. ac/deltas/change_parallelism.py +52 -0
  25. ac/deltas/change_precision_per_component.py +48 -0
  26. ac/deltas/densify_first_k.py +28 -0
  27. ac/deltas/interleave_local_attention.py +99 -0
  28. ac/deltas/scale_d_model.py +71 -0
  29. ac/deltas/scale_n_layers.py +64 -0
  30. ac/deltas/swap_attention_to_gqa.py +69 -0
  31. ac/deltas/swap_attention_to_mla.py +98 -0
  32. ac/deltas/swap_attention_to_swa.py +68 -0
  33. ac/evaluator.py +1501 -0
  34. ac/hardware_specs/b200.json +81 -0
  35. ac/hardware_specs/gb200_nvl72.json +95 -0
  36. ac/hardware_specs/h100_sxm.json +72 -0
  37. ac/hardware_specs/h800.json +74 -0
  38. ac/hardware_specs/tpu_v5e.json +52 -0
  39. ac/hardware_specs/tpu_v5p.json +61 -0
  40. ac/hardware_specs/trainium2.json +67 -0
  41. ac/hardware_specs/trainium3.json +82 -0
  42. ac/implementation_generator.py +475 -0
  43. ac/justification.py +775 -0
  44. ac/justify_transition.py +220 -0
  45. ac/ladder_plan.py +474 -0
  46. ac/lattice_engine.py +1323 -0
  47. ac/modifier.py +830 -0
  48. ac/operational_flags.py +344 -0
  49. ac/optimizer.py +6549 -0
  50. ac/optimizer_bridge.py +234 -0
  51. ac/packaged_configs/gpt_oss_120b.json +159 -0
  52. ac/packaged_configs/mai_thinking_1.json +178 -0
  53. ac/packaged_configs/mistral_7b.json +64 -0
  54. ac/pareto_position.py +388 -0
  55. ac/penalties.py +539 -0
  56. ac/pricing.py +452 -0
  57. ac/pricing_specs/b200.json +73 -0
  58. ac/pricing_specs/h100.json +72 -0
  59. ac/pricing_specs/tpu_v5e.json +70 -0
  60. ac/pricing_specs/tpu_v5p.json +70 -0
  61. ac/pricing_specs/trainium2.json +74 -0
  62. ac/pricing_specs/trainium3.json +62 -0
  63. ac/quality_defaults.yaml +262 -0
  64. ac/quality_model.py +3973 -0
  65. ac/quality_stress.py +244 -0
  66. ac/rank.py +156 -0
  67. ac/report.py +1067 -0
  68. ac/schema.py +1622 -0
  69. ac/serving_workload.py +351 -0
  70. ac/shadow_prices.py +561 -0
  71. ac/sram_derivation.py +295 -0
  72. ac/stress.py +1112 -0
  73. ac/throughput_model.py +3793 -0
  74. ac/transition.py +159 -0
  75. ac/trust_audit.py +934 -0
  76. archc-0.0.0.dist-info/METADATA +1034 -0
  77. archc-0.0.0.dist-info/RECORD +81 -0
  78. archc-0.0.0.dist-info/WHEEL +5 -0
  79. archc-0.0.0.dist-info/entry_points.txt +7 -0
  80. archc-0.0.0.dist-info/licenses/LICENSE +15 -0
  81. archc-0.0.0.dist-info/top_level.txt +1 -0
ac/__init__.py ADDED
File without changes
ac/ablation_fit.py ADDED
@@ -0,0 +1,291 @@
1
+ """Wave 18h — paired-ablation residual fitting (zero-compute calibration).
2
+
3
+ Consumes a machine-readable corpus of PUBLISHED paired ablations (same data,
4
+ same scale, one architecture axis flipped — see
5
+ tests/fixtures/public_ablation_pairs_v1.json) and:
6
+
7
+ 1. Scores both arms of every pair with the quality model and compares the
8
+ predicted loss delta with the published delta.
9
+ 2. Fits a per-term scale factor by attributing each pair's residual to the
10
+ term the pair targets (least squares over the pairs touching a term).
11
+ 3. Emits a COVERAGE AUDIT: which residual terms have zero constraining
12
+ pairs, and which operating-point regions of a constrained term are
13
+ unanchored. This is the check that would have caught the pure-SSM bug
14
+ mechanically — the state-benefit term had no anchor below p_attn=0.07,
15
+ so its behavior there was pure extrapolation.
16
+
17
+ This is curation, not compute: it upgrades hand-tuned residual constants
18
+ into a reproducible fit with per-term error bars, without a single training
19
+ run. Cross-paper deltas carry datamix/tokenizer confounds, so fitted scales
20
+ are written as an *overlay pack* (like ac-auto-calibrate's) rather than
21
+ edited into the defaults.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import math
28
+ import os
29
+ from dataclasses import dataclass, field
30
+ from typing import Any, Dict, List, Optional
31
+
32
+ try:
33
+ from .quality_model import ArchConfig as QArch, estimate_quality
34
+ except ImportError: # pragma: no cover
35
+ from quality_model import ArchConfig as QArch, estimate_quality
36
+
37
+
38
+ # Residual terms a pair may target. Terms in the quality model but absent
39
+ # here can never be constrained by this corpus format — they are reported
40
+ # as uncovered in the audit.
41
+ KNOWN_TERMS = (
42
+ "state_residual", "architecture_residual", "attention_locality",
43
+ "effective_capacity", "moe_residual", "mtp_residual", "context_utility",
44
+ "precision_residual", "large_shape_stability_prior", "risk_residual",
45
+ )
46
+
47
+ # Some corpus terms live inside a differently-named term in the model's
48
+ # breakdown; map corpus terms to model term names for delta attribution.
49
+ # (The SWA/interleave locality penalty is booked under context_utility —
50
+ # verified by term-delta inspection, Wave 18h.)
51
+ _MODEL_TERM_ALIAS = {"attention_locality": "context_utility"}
52
+
53
+
54
+ def _arm_to_arch(arm: Dict[str, Any]) -> QArch:
55
+ kind = str(arm.get("kind", "dense"))
56
+ kw: Dict[str, Any] = dict(
57
+ d_model=int(arm["d_model"]), n_layers=int(arm["n_layers"]),
58
+ n_heads=int(arm["n_heads"]), d_head=int(arm["d_head"]),
59
+ n_kv_heads=int(arm["n_kv_heads"]), ffn_dim=int(arm["ffn_dim"]),
60
+ vocab_size=int(arm.get("vocab_size", 32000)),
61
+ )
62
+ if kind in ("hybrid", "pure_state"):
63
+ kw.update(model_type="hybrid",
64
+ state_config={
65
+ "enabled": True,
66
+ "state_type": arm.get("state_type", "mamba2"),
67
+ "d_state": int(arm.get("d_state", 128)),
68
+ "state_layers": int(arm["state_layers"]),
69
+ "attention_layers": int(arm["attention_layers"]),
70
+ })
71
+ elif kind == "mla":
72
+ kw.update(attention_type="mla",
73
+ mla_latent_dim=int(arm.get("mla_kv_latent", 512)),
74
+ mla_q_latent_dim=int(arm.get("mla_q_latent", 1536)),
75
+ mla_rope_head_dim=64)
76
+ elif kind == "moe":
77
+ kw.update(model_type="moe",
78
+ moe_config={
79
+ "n_experts": int(arm["n_experts"]),
80
+ "top_k": int(arm["top_k"]),
81
+ "expert_dim": int(arm.get("expert_dim", arm["ffn_dim"])),
82
+ })
83
+ elif kind in ("local_global", "swa"):
84
+ kw.update(local_window=int(arm["local_window"]),
85
+ local_attention_fraction=float(arm.get("local_fraction", 1.0)))
86
+ elif kind == "mtp":
87
+ kw.update(mtp_n_predict_depths=int(arm.get("mtp_depths", 1)))
88
+ elif kind == "rope":
89
+ kw.update(rope_scaling_method=str(arm.get("rope_method", "none")),
90
+ rope_scaling_factor=float(arm.get("rope_factor", 1.0)),
91
+ rope_original_max_position=8192)
92
+ return QArch(**kw)
93
+
94
+
95
+ @dataclass
96
+ class PairResult:
97
+ pair_id: str
98
+ term: str
99
+ source: str
100
+ observed_pct: float
101
+ predicted_pct: float
102
+ term_predicted_pct: float
103
+ residual_pct: float
104
+ tolerance_pct: float
105
+ within_tolerance: bool
106
+ operating_point: Dict[str, Any] = field(default_factory=dict)
107
+
108
+
109
+ @dataclass
110
+ class TermFit:
111
+ term: str
112
+ n_pairs: int
113
+ scale: Optional[float] # None when unidentifiable (|pred|~0)
114
+ bias_pct: float # mean residual
115
+ rms_pct: float
116
+ covered_points: List[Dict[str, Any]] = field(default_factory=list)
117
+ warnings: List[str] = field(default_factory=list)
118
+
119
+
120
+ def evaluate_pairs(corpus: Dict[str, Any]) -> List[PairResult]:
121
+ out: List[PairResult] = []
122
+ for p in corpus.get("pairs", []):
123
+ tr = {"training_tokens": int(float(p["training_tokens_t"]) * 1e12)}
124
+ w = {"context_length": int(p["context"])}
125
+ qa = estimate_quality(_arm_to_arch(p["arm_a"]), tr, workload_spec=w)
126
+ qb = estimate_quality(_arm_to_arch(p["arm_b"]), tr, workload_spec=w)
127
+ la, lb = qa.predicted_loss, qb.predicted_loss
128
+ pred_pct = 100.0 * (lb - la) / max(1e-9, la)
129
+ model_term = _MODEL_TERM_ALIAS.get(p["term"], p["term"])
130
+ ta = (qa.terms or {}).get(model_term)
131
+ tb = (qb.terms or {}).get(model_term)
132
+ term_pred_pct = 100.0 * (
133
+ float(getattr(tb, "value", 0.0) or 0.0)
134
+ - float(getattr(ta, "value", 0.0) or 0.0))
135
+ obs = float(p["observed_delta_pct"])
136
+ tol = float(p.get("tolerance_pct", 0.5))
137
+ out.append(PairResult(
138
+ pair_id=p["id"], term=p["term"], source=p.get("source", ""),
139
+ observed_pct=obs, predicted_pct=round(pred_pct, 4),
140
+ term_predicted_pct=round(term_pred_pct, 4),
141
+ residual_pct=round(obs - pred_pct, 4),
142
+ tolerance_pct=tol,
143
+ within_tolerance=abs(obs - pred_pct) <= tol,
144
+ operating_point=p.get("operating_point", {}),
145
+ ))
146
+ return out
147
+
148
+
149
+ def fit_terms(results: List[PairResult]) -> List[TermFit]:
150
+ """Least-squares per-term scale: attribute each pair's residual to its
151
+ targeted term. observed ≈ (predicted_total − term_pred) + scale × term_pred
152
+ ⇒ scale* = Σ(adj·t)/Σ(t²) with adj = observed − (predicted − term_pred)."""
153
+ by_term: Dict[str, List[PairResult]] = {}
154
+ for r in results:
155
+ by_term.setdefault(r.term, []).append(r)
156
+ fits: List[TermFit] = []
157
+ for term in KNOWN_TERMS:
158
+ rs = by_term.get(term, [])
159
+ if not rs:
160
+ fits.append(TermFit(
161
+ term=term, n_pairs=0, scale=None, bias_pct=0.0, rms_pct=0.0,
162
+ warnings=[f"UNCOVERED: no published pair constrains "
163
+ f"'{term}' — its constants are hand priors; any "
164
+ f"decision it dominates is extrapolation."]))
165
+ continue
166
+ num = sum((r.observed_pct - (r.predicted_pct - r.term_predicted_pct))
167
+ * r.term_predicted_pct for r in rs)
168
+ den = sum(r.term_predicted_pct ** 2 for r in rs)
169
+ scale = (num / den) if den > 1e-8 else None
170
+ bias = sum(r.residual_pct for r in rs) / len(rs)
171
+ rms = math.sqrt(sum(r.residual_pct ** 2 for r in rs) / len(rs))
172
+ warnings = []
173
+ if scale is None:
174
+ warnings.append(
175
+ f"'{term}' pairs exist but the model predicts ~0 delta for "
176
+ f"all of them — the term is UNIDENTIFIABLE from this corpus "
177
+ f"(shape error, or the pairs sit where the term is flat).")
178
+ elif not (0.5 <= scale <= 2.0):
179
+ warnings.append(
180
+ f"fitted scale {scale:.2f} is far from 1.0 — the term's "
181
+ f"magnitude disagrees with published evidence; inspect "
182
+ f"before trusting decisions dominated by '{term}'.")
183
+ if len(rs) < 2:
184
+ warnings.append(
185
+ f"only {len(rs)} pair(s) — scale is a point estimate with "
186
+ f"no cross-validation; treat as directional.")
187
+ fits.append(TermFit(
188
+ term=term, n_pairs=len(rs),
189
+ scale=None if scale is None else round(scale, 3),
190
+ bias_pct=round(bias, 3), rms_pct=round(rms, 3),
191
+ covered_points=[r.operating_point for r in rs],
192
+ warnings=warnings))
193
+ return fits
194
+
195
+
196
+ def coverage_gaps(fits: List[TermFit]) -> List[str]:
197
+ """Region-level audit for terms whose operating points carry a known
198
+ sweep axis. Flags unanchored extrapolation regions explicitly."""
199
+ gaps: List[str] = []
200
+ for f in fits:
201
+ if f.term == "state_residual" and f.n_pairs:
202
+ p_attns = sorted(
203
+ v for pt in f.covered_points
204
+ for k, v in pt.items() if k.startswith("p_attn"))
205
+ ctxs = sorted(pt.get("context", 0) for pt in f.covered_points)
206
+ if p_attns:
207
+ msg = (f"state_residual: anchored p_attn range "
208
+ f"[{min(p_attns):.2f}, {max(p_attns):.2f}], contexts "
209
+ f"{ctxs}.")
210
+ if min(p_attns) > 0.0:
211
+ msg += (f" Behavior at p_attn < {min(p_attns):.2f} is "
212
+ f"extrapolation — this exact gap allowed the "
213
+ f"pre-18f pure-SSM winners.")
214
+ if max(c for c in ctxs) < 1048576:
215
+ msg += (f" No anchor above ctx {max(ctxs):,} — the "
216
+ f"long-context benefit magnitude at 1M+ is "
217
+ f"extrapolation.")
218
+ gaps.append(msg)
219
+ if f.term == "attention_locality" and f.n_pairs:
220
+ fracs = sorted(pt.get("local_fraction", 0.0) for pt in f.covered_points)
221
+ windows = sorted(pt.get("window", 0) for pt in f.covered_points)
222
+ gaps.append(
223
+ f"attention_locality: anchored local fractions "
224
+ f"{fracs}, windows {windows}; other regions are priors.")
225
+ if f.term == "effective_capacity" and f.n_pairs:
226
+ ratios = sorted(pt.get("ratio", 0.0) for pt in f.covered_points)
227
+ gaps.append(
228
+ f"effective_capacity: anchored sparsity ratios {ratios}; "
229
+ f"ratios beyond this range (e.g. >8x) lean on the N_eff "
230
+ f"functional form, not on paired evidence.")
231
+ return gaps
232
+
233
+
234
+ def render_report(results: List[PairResult], fits: List[TermFit],
235
+ gaps: List[str]) -> str:
236
+ lines = ["# Paired-ablation residual fit (Wave 18h)", ""]
237
+ n_ok = sum(1 for r in results if r.within_tolerance)
238
+ lines.append(f"Pairs: {len(results)} | within tolerance: {n_ok} | "
239
+ f"outside: {len(results) - n_ok}")
240
+ lines.append("")
241
+ lines.append("| pair | term | observed Δ% | predicted Δ% | residual | ok |")
242
+ lines.append("|---|---|---:|---:|---:|---|")
243
+ for r in results:
244
+ lines.append(
245
+ f"| {r.pair_id} | {r.term} | {r.observed_pct:+.2f} | "
246
+ f"{r.predicted_pct:+.2f} | {r.residual_pct:+.2f} | "
247
+ f"{'✓' if r.within_tolerance else '✗'} |")
248
+ lines.append("")
249
+ lines.append("## Per-term fit")
250
+ lines.append("")
251
+ lines.append("| term | pairs | scale | bias % | rms % |")
252
+ lines.append("|---|---:|---:|---:|---:|")
253
+ for f in fits:
254
+ lines.append(
255
+ f"| {f.term} | {f.n_pairs} | "
256
+ f"{'—' if f.scale is None else f.scale} | "
257
+ f"{f.bias_pct:+.2f} | {f.rms_pct:.2f} |")
258
+ lines.append("")
259
+ lines.append("## Coverage audit")
260
+ lines.append("")
261
+ for f in fits:
262
+ for wmsg in f.warnings:
263
+ lines.append(f"- **{f.term}**: {wmsg}")
264
+ for g in gaps:
265
+ lines.append(f"- {g}")
266
+ lines.append("")
267
+ lines.append(
268
+ "Fitted scales are cross-paper (datamix/tokenizer confounded); use "
269
+ "as priors and ingest lab pairs via the same format to sharpen.")
270
+ return "\n".join(lines)
271
+
272
+
273
+ def run_fit_pairs(pairs_path: str, out_dir: str) -> Dict[str, Any]:
274
+ with open(pairs_path) as f:
275
+ corpus = json.load(f)
276
+ results = evaluate_pairs(corpus)
277
+ fits = fit_terms(results)
278
+ gaps = coverage_gaps(fits)
279
+ os.makedirs(out_dir, exist_ok=True)
280
+ payload = {
281
+ "schema_version": "wave18h.pair_fit.v1",
282
+ "pairs_path": os.path.abspath(pairs_path),
283
+ "results": [vars(r) for r in results],
284
+ "term_fits": [vars(f) for f in fits],
285
+ "coverage_gaps": gaps,
286
+ }
287
+ with open(os.path.join(out_dir, "pair_fit.json"), "w") as f:
288
+ json.dump(payload, f, indent=2)
289
+ with open(os.path.join(out_dir, "pair_fit_report.md"), "w") as f:
290
+ f.write(render_report(results, fits, gaps))
291
+ return payload