|
| 1 | +"""Phase-3b v2 spatial-conv experiment driver. |
| 2 | +
|
| 3 | +Runs three sub-experiments to test whether the kernel-size-3 spatial-conv |
| 4 | +DistinguisherSpatial architecture surfaces signal at depths that collapsed |
| 5 | +with the v1 1×1-conv Distinguisher: |
| 6 | +
|
| 7 | + 1. Δ search at depth 56 (control — should reproduce v1's signal, |
| 8 | + confirming v2 isn't broken). |
| 9 | + 2. Δ search at depth 88 (the primary hypothesis test — did the v1 signal |
| 10 | + horizon move because of the architectural change?). |
| 11 | + 3. If (2) surfaces any Δ above a threshold, a full train at that Δ. |
| 12 | +
|
| 13 | +Writes results to stdout as JSON + markdown to |
| 14 | +``docs/phase3b-results/v2_experiment.md``. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import json |
| 20 | +import time |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +import torch |
| 24 | +from torch import nn |
| 25 | + |
| 26 | +from keeloq.neural.data import generate_pairs |
| 27 | +from keeloq.neural.differences import _default_candidate_set |
| 28 | +from keeloq.neural.distinguisher_v2 import DistinguisherSpatial |
| 29 | + |
| 30 | + |
| 31 | +# ---------- Standalone training loop (uses v2 architecture) ---------- |
| 32 | + |
| 33 | + |
| 34 | +def _set_seeds(seed: int) -> None: |
| 35 | + import random |
| 36 | + |
| 37 | + import numpy as np |
| 38 | + |
| 39 | + torch.manual_seed(seed) |
| 40 | + torch.cuda.manual_seed_all(seed) |
| 41 | + np.random.seed(seed) |
| 42 | + random.seed(seed) |
| 43 | + |
| 44 | + |
| 45 | +def _val_accuracy(model: nn.Module, rounds: int, delta: int, seed: int, |
| 46 | + n_samples: int = 5000, batch_size: int = 1024) -> float: |
| 47 | + model.train(False) |
| 48 | + correct, total = 0, 0 |
| 49 | + with torch.no_grad(): |
| 50 | + for batch in generate_pairs( |
| 51 | + rounds=rounds, delta=delta, n_samples=n_samples, |
| 52 | + seed=seed, batch_size=min(batch_size, n_samples), |
| 53 | + ): |
| 54 | + preds = (model(batch.pairs) >= 0.5).float() |
| 55 | + correct += (preds == batch.labels).sum().item() |
| 56 | + total += batch.labels.shape[0] |
| 57 | + model.train(True) |
| 58 | + return correct / max(1, total) |
| 59 | + |
| 60 | + |
| 61 | +def train_v2( |
| 62 | + rounds: int, |
| 63 | + delta: int, |
| 64 | + n_samples: int, |
| 65 | + batch_size: int, |
| 66 | + epochs: int, |
| 67 | + lr: float, |
| 68 | + weight_decay: float, |
| 69 | + seed: int, |
| 70 | + depth: int, |
| 71 | + width: int, |
| 72 | + kernel_size: int = 3, |
| 73 | +) -> tuple[DistinguisherSpatial, dict]: |
| 74 | + _set_seeds(seed) |
| 75 | + model = DistinguisherSpatial(depth=depth, width=width, kernel_size=kernel_size).cuda() |
| 76 | + opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay) |
| 77 | + criterion = nn.BCELoss() |
| 78 | + |
| 79 | + steps = max(1, n_samples // batch_size) * epochs |
| 80 | + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=steps) |
| 81 | + |
| 82 | + history = [] |
| 83 | + t0 = time.perf_counter() |
| 84 | + for epoch in range(epochs): |
| 85 | + loss_sum, n_batches = 0.0, 0 |
| 86 | + for batch in generate_pairs( |
| 87 | + rounds=rounds, delta=delta, n_samples=n_samples, |
| 88 | + seed=seed + epoch * 991, batch_size=batch_size, |
| 89 | + ): |
| 90 | + opt.zero_grad() |
| 91 | + preds = model(batch.pairs) |
| 92 | + loss = criterion(preds, batch.labels) |
| 93 | + loss.backward() |
| 94 | + opt.step() |
| 95 | + sched.step() |
| 96 | + loss_sum += float(loss.item()) |
| 97 | + n_batches += 1 |
| 98 | + val_acc = _val_accuracy(model, rounds, delta, seed=seed + 1_000_000) |
| 99 | + history.append({ |
| 100 | + "epoch": epoch, |
| 101 | + "train_loss": loss_sum / max(1, n_batches), |
| 102 | + "val_accuracy": val_acc, |
| 103 | + }) |
| 104 | + return model, { |
| 105 | + "final_loss": history[-1]["train_loss"], |
| 106 | + "final_val_accuracy": history[-1]["val_accuracy"], |
| 107 | + "wall_time_s": time.perf_counter() - t0, |
| 108 | + "history": history, |
| 109 | + } |
| 110 | + |
| 111 | + |
| 112 | +# ---------- Δ search wrapper ---------- |
| 113 | + |
| 114 | + |
| 115 | +def search_delta_v2( |
| 116 | + rounds: int, |
| 117 | + candidates: list[int] | None = None, |
| 118 | + tiny_budget_samples: int = 200_000, |
| 119 | + tiny_budget_epochs: int = 2, |
| 120 | + seed: int = 0, |
| 121 | + depth: int = 2, |
| 122 | + width: int = 64, |
| 123 | + kernel_size: int = 3, |
| 124 | +) -> list[dict]: |
| 125 | + if candidates is None: |
| 126 | + candidates = _default_candidate_set() |
| 127 | + seen: set[int] = set() |
| 128 | + uniq: list[int] = [] |
| 129 | + for c in candidates: |
| 130 | + if c not in seen and 0 < c < (1 << 32): |
| 131 | + seen.add(c) |
| 132 | + uniq.append(c) |
| 133 | + |
| 134 | + results = [] |
| 135 | + for i, delta in enumerate(uniq): |
| 136 | + _, res = train_v2( |
| 137 | + rounds=rounds, delta=delta, |
| 138 | + n_samples=tiny_budget_samples, batch_size=1024, |
| 139 | + epochs=tiny_budget_epochs, lr=2e-3, weight_decay=1e-5, |
| 140 | + seed=seed + i * 7919, depth=depth, width=width, |
| 141 | + kernel_size=kernel_size, |
| 142 | + ) |
| 143 | + results.append({ |
| 144 | + "delta": delta, |
| 145 | + "val_accuracy": res["final_val_accuracy"], |
| 146 | + "training_loss_final": res["final_loss"], |
| 147 | + }) |
| 148 | + results.sort(key=lambda c: c["val_accuracy"], reverse=True) |
| 149 | + return results |
| 150 | + |
| 151 | + |
| 152 | +# ---------- Main driver ---------- |
| 153 | + |
| 154 | + |
| 155 | +SIGNAL_THRESHOLD = 0.55 # if best tiny candidate exceeds this, invest in full training |
| 156 | + |
| 157 | + |
| 158 | +def main() -> None: |
| 159 | + out_md = Path("docs/phase3b-results/v2_experiment.md") |
| 160 | + out_md.parent.mkdir(parents=True, exist_ok=True) |
| 161 | + lines: list[str] = ["# Phase 3b v2 Spatial-Conv Experiment\n"] |
| 162 | + |
| 163 | + # Experiment 1: Δ search at depth 56 (control). |
| 164 | + print("[v2-exp] Δ search at depth 56 (control)...", flush=True) |
| 165 | + t0 = time.perf_counter() |
| 166 | + cands_56 = search_delta_v2(rounds=56, tiny_budget_samples=100_000, tiny_budget_epochs=2, seed=0) |
| 167 | + elapsed_56 = time.perf_counter() - t0 |
| 168 | + best_56 = cands_56[0] |
| 169 | + lines.append(f"## Control: Δ search at depth 56 (v1 got best 0.688)\n") |
| 170 | + lines.append(f"Wall clock: {elapsed_56:.1f}s — top 5:\n") |
| 171 | + lines.append("| Δ | val_acc | loss |\n|---|---:|---:|") |
| 172 | + for c in cands_56[:5]: |
| 173 | + lines.append(f"| 0x{c['delta']:08x} | {c['val_accuracy']:.4f} | {c['training_loss_final']:.4f} |") |
| 174 | + print(json.dumps({"experiment": "control_56", "best": best_56, "wall_s": elapsed_56}), flush=True) |
| 175 | + |
| 176 | + # Experiment 2: Δ search at depth 88 (primary hypothesis). |
| 177 | + print("\n[v2-exp] Δ search at depth 88 (primary hypothesis)...", flush=True) |
| 178 | + t0 = time.perf_counter() |
| 179 | + cands_88 = search_delta_v2(rounds=88, tiny_budget_samples=100_000, tiny_budget_epochs=2, seed=0) |
| 180 | + elapsed_88 = time.perf_counter() - t0 |
| 181 | + best_88 = cands_88[0] |
| 182 | + lines.append(f"\n## Primary: Δ search at depth 88 (v1 all < 0.517)\n") |
| 183 | + lines.append(f"Wall clock: {elapsed_88:.1f}s — top 10:\n") |
| 184 | + lines.append("| Δ | val_acc | loss |\n|---|---:|---:|") |
| 185 | + for c in cands_88[:10]: |
| 186 | + lines.append(f"| 0x{c['delta']:08x} | {c['val_accuracy']:.4f} | {c['training_loss_final']:.4f} |") |
| 187 | + print(json.dumps({"experiment": "primary_88", "best": best_88, "wall_s": elapsed_88}), flush=True) |
| 188 | + |
| 189 | + # Experiment 3 (conditional): Δ search at depth 120. |
| 190 | + print("\n[v2-exp] Δ search at depth 120 (stretch)...", flush=True) |
| 191 | + t0 = time.perf_counter() |
| 192 | + cands_120 = search_delta_v2(rounds=120, tiny_budget_samples=100_000, tiny_budget_epochs=2, seed=0) |
| 193 | + elapsed_120 = time.perf_counter() - t0 |
| 194 | + best_120 = cands_120[0] |
| 195 | + lines.append(f"\n## Stretch: Δ search at depth 120 (v1 all < 0.515)\n") |
| 196 | + lines.append(f"Wall clock: {elapsed_120:.1f}s — top 10:\n") |
| 197 | + lines.append("| Δ | val_acc | loss |\n|---|---:|---:|") |
| 198 | + for c in cands_120[:10]: |
| 199 | + lines.append(f"| 0x{c['delta']:08x} | {c['val_accuracy']:.4f} | {c['training_loss_final']:.4f} |") |
| 200 | + print(json.dumps({"experiment": "stretch_120", "best": best_120, "wall_s": elapsed_120}), flush=True) |
| 201 | + |
| 202 | + # Experiment 4 (conditional): if depth 88 has signal, full train. |
| 203 | + verdict_lines: list[str] = [] |
| 204 | + verdict_lines.append(f"\n## Verdict\n") |
| 205 | + if best_88["val_accuracy"] >= SIGNAL_THRESHOLD: |
| 206 | + verdict_lines.append( |
| 207 | + f"- Depth 88 best Δ=0x{best_88['delta']:08x} reached val-acc " |
| 208 | + f"{best_88['val_accuracy']:.4f} — **above the {SIGNAL_THRESHOLD} threshold**. " |
| 209 | + "Spatial conv architecture surfaces signal where v1's 1×1 version failed. " |
| 210 | + "Proceeding with a full-scale train at this Δ.\n" |
| 211 | + ) |
| 212 | + print(f"\n[v2-exp] Depth 88 signal confirmed ({best_88['val_accuracy']:.4f}). " |
| 213 | + "Kicking off full train (10M samples × 20 epochs)...", flush=True) |
| 214 | + t0 = time.perf_counter() |
| 215 | + _, full_res = train_v2( |
| 216 | + rounds=88, delta=best_88["delta"], |
| 217 | + n_samples=10_000_000, batch_size=4096, |
| 218 | + epochs=20, lr=2e-3, weight_decay=1e-5, |
| 219 | + seed=1729, depth=5, width=256, kernel_size=3, |
| 220 | + ) |
| 221 | + verdict_lines.append( |
| 222 | + f"- Full train: val_acc={full_res['final_val_accuracy']:.4f}, " |
| 223 | + f"loss={full_res['final_loss']:.4f}, " |
| 224 | + f"wall_time_s={full_res['wall_time_s']:.1f}.\n" |
| 225 | + ) |
| 226 | + print(json.dumps({"experiment": "full_train_88", "result": full_res}), flush=True) |
| 227 | + else: |
| 228 | + verdict_lines.append( |
| 229 | + f"- Depth 88 best Δ=0x{best_88['delta']:08x} reached val-acc " |
| 230 | + f"{best_88['val_accuracy']:.4f} — **below the {SIGNAL_THRESHOLD} threshold**. " |
| 231 | + "Spatial conv architecture *also* fails to surface signal at depth 88. " |
| 232 | + "This tightens the negative result from 'v1 architecture fails' to " |
| 233 | + "'both 1×1 and spatial 3-tap architectures fail' — suggesting the " |
| 234 | + "signal horizon is a genuine property of KeeLoq's diffusion at these " |
| 235 | + "depths, not an artifact of any one architecture.\n" |
| 236 | + ) |
| 237 | + print("\n[v2-exp] Depth 88 still below threshold. Negative result stands.", flush=True) |
| 238 | + |
| 239 | + lines.extend(verdict_lines) |
| 240 | + out_md.write_text("\n".join(lines) + "\n") |
| 241 | + print(f"\n[v2-exp] Wrote {out_md}", flush=True) |
| 242 | + |
| 243 | + |
| 244 | +if __name__ == "__main__": |
| 245 | + main() |
0 commit comments