exp014 shipped: router v1 honest negative (state keys already route by prompt; raw-flat address = disease geometry; null lesson -> v2)
Browse files- README.md +1 -0
- exp014_te_dispatch/README.md +36 -0
- exp014_te_dispatch/dexp014_te_dispatch.py +383 -0
- exp014_te_dispatch/results.json +55 -0
README.md
CHANGED
|
@@ -82,6 +82,7 @@ resolution) so gaps live in a narrow band — the paired design is load-bearing.
|
|
| 82 |
| exp009_bandroles | role objectives: **directional hit 4/4 but noise-adjacent — frequency reweighting too collinear; needs qualitatively different supervision + generation-side gauges (exp010)** | **shipped (2 seeds + rejudge)** |
|
| 83 |
| exp010_controller | **StepGatedSampler ships**: controller lifts grounding +0.089 over frozen; monotonic lesion ladder; HIGH lesion 14x LP-dominant (coarse-to-fine confirmed in image space); eps-trained HIGH band concentrates (diversity = open training goal) | **shipped (candidate)** |
|
| 84 |
| exp011a_fused_multiband | multiband on REAL fused data: **adapters pay 2-3x more; structural story replicates (3/3 surgical, monolith edge persists); blob targets built 100% after a schema lesson** | **shipped (candidate, s0; s1 running)** |
|
|
|
|
| 85 |
| exp013_blob_flow | **CONDITIONING HYPOTHESIS CONFIRMED**: same blob coupling, ~200x the eps effect on the flow substrate (−5.9% vs +0.03%); blob supervision belongs on flow/v-pred trunks | **shipped (candidate, s0; s1 running)** |
|
| 86 |
|
| 87 |
Numbering: a number binds to a preregistered design at assignment and is never reassigned — gaps mean reserved-not-yet-run (exp004 = the Anima relay train, integration-certified by R0b; exp005 = the SDXL Tree-4a battery, designed). Sub-letters (000b) extend a shipped experiment without disturbing its rows.
|
|
|
|
| 82 |
| exp009_bandroles | role objectives: **directional hit 4/4 but noise-adjacent — frequency reweighting too collinear; needs qualitatively different supervision + generation-side gauges (exp010)** | **shipped (2 seeds + rejudge)** |
|
| 83 |
| exp010_controller | **StepGatedSampler ships**: controller lifts grounding +0.089 over frozen; monotonic lesion ladder; HIGH lesion 14x LP-dominant (coarse-to-fine confirmed in image space); eps-trained HIGH band concentrates (diversity = open training goal) | **shipped (candidate)** |
|
| 84 |
| exp011a_fused_multiband | multiband on REAL fused data: **adapters pay 2-3x more; structural story replicates (3/3 surgical, monolith edge persists); blob targets built 100% after a schema lesson** | **shipped (candidate, s0; s1 running)** |
|
| 85 |
+
| exp014_te_dispatch | router-solidifier v1: **honest negative** — state keys already route by prompt; raw-flattened address kills routing (the known high-D disease geometry); null-design lesson → v2 | **shipped (candidate, s0; s1 running)** |
|
| 86 |
| exp013_blob_flow | **CONDITIONING HYPOTHESIS CONFIRMED**: same blob coupling, ~200x the eps effect on the flow substrate (−5.9% vs +0.03%); blob supervision belongs on flow/v-pred trunks | **shipped (candidate, s0; s1 running)** |
|
| 87 |
|
| 88 |
Numbering: a number binds to a preregistered design at assignment and is never reassigned — gaps mean reserved-not-yet-run (exp004 = the Anima relay train, integration-certified by R0b; exp005 = the SDXL Tree-4a battery, designed). Sub-letters (000b) extend a shipped experiment without disturbing its rows.
|
exp014_te_dispatch/README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# exp014_te_dispatch — the router-solidifier v1 (CANDIDATE s0; s1 running)
|
| 2 |
+
|
| 3 |
+
**Question.** Does text-side addressing in the DISPATCH KEY (a trained
|
| 4 |
+
text-encoder adapter, or the frozen canonical byte-trigram address) route
|
| 5 |
+
the expert bank better than state+sigma keys alone?
|
| 6 |
+
|
| 7 |
+
**Arms** (flow trunk, fused cache, A=4 r=8 banks, dense signed dispatch):
|
| 8 |
+
sigma_key (control) | addr_key (frozen [32,128] address flattened → key) |
|
| 9 |
+
te_key (trained CLIP-pooler adapter → key).
|
| 10 |
+
|
| 11 |
+
**Results** (`results.json`):
|
| 12 |
+
|
| 13 |
+
| arm | val flow-MSE | per-prompt usage var | shuffled-key null |
|
| 14 |
+
|---|---|---|---|
|
| 15 |
+
| sigma_key | **0.57371** | 2.36e-02 | 0 (no text) |
|
| 16 |
+
| addr_key | 0.57755 | **1.40e-05 (dead)** | 1.40e-05 |
|
| 17 |
+
| te_key | 0.57422 | 2.60e-02 | 2.71e-02 |
|
| 18 |
+
|
| 19 |
+
**Verdict (honest negative + two instrument findings).**
|
| 20 |
+
1. P1 MISS: no val win for text keys at this scale (all within 0.07%).
|
| 21 |
+
2. **The hidden-state key already routes by prompt** (2.36e-02 usage
|
| 22 |
+
variance with zero text input) — prompt-level structure reaches the
|
| 23 |
+
usage surface through x itself; exp007's flatness was across SIGMA
|
| 24 |
+
BANDS, a different axis. The TE key adds ~nothing on top.
|
| 25 |
+
3. **The raw-flattened address kills routing** (1.4e-05) and dents val —
|
| 26 |
+
reproducing the text line's documented disease geometry (addressing raw
|
| 27 |
+
high-D flattens the oriented softmax; healthy forms bottleneck to low-D
|
| 28 |
+
FIRST). The canonical address needs a structured reduction (slots/M̂
|
| 29 |
+
read) before it can serve as a router key — v2's design, not a defect
|
| 30 |
+
of the address itself.
|
| 31 |
+
4. **Confessed instrument gap:** the shuffled-key null measures key
|
| 32 |
+
DIVERSITY, not routing CORRECTNESS (te null ≈ te real). v2's null:
|
| 33 |
+
repeated-key, plus matched-vs-mismatched key val deltas.
|
| 34 |
+
|
| 35 |
+
**Caveats.** s0 (s1 running); one scale (A=4, 3k steps); pooler-only TE
|
| 36 |
+
feature; flow trunk only. Cost ≈ 4.6 GPU-h incl. text-feature build.
|
exp014_te_dispatch/dexp014_te_dispatch.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""dexp014_te_dispatch.py — exp014: TEXT-ADDRESSED DISPATCH (Phil's "router
|
| 2 |
+
solidifier": the MoE accepts a trained text-encoder adapter as an addressing
|
| 3 |
+
conditioning router).
|
| 4 |
+
|
| 5 |
+
The junction of three findings: diffusion-side codes compress caption
|
| 6 |
+
structure to ~0 (exp003) | the text-address channel is live where not
|
| 7 |
+
redundant (exp002) | state+sigma dispatch alone finds nothing to route on
|
| 8 |
+
(exp007). Here the TEXT side enters the DISPATCH KEY, not the content path.
|
| 9 |
+
|
| 10 |
+
Per site: AmoeBank-style expert bank (A=4, rank-8 zero-init deltas, dense
|
| 11 |
+
signed aleph dispatch, no selectors). Dispatch-key arms:
|
| 12 |
+
sigma_key — key = key_proj(x) + sig_proj(fourier(sigma)) [exp007 ctrl]
|
| 13 |
+
addr_key — + txt_proj(frozen byte-trigram aleph address of the
|
| 14 |
+
caption, flattened [32*128]) — the CANONICAL address as
|
| 15 |
+
router (frozen address, trained projection).
|
| 16 |
+
te_key — + te_adapter(CLIP text pooler_output [768] -> D) — THE
|
| 17 |
+
TRAINED TE ADAPTER AS ROUTER SOLIDIFIER (trained jointly
|
| 18 |
+
through the diffusion loss).
|
| 19 |
+
Substrate: base_lune flow + the fused cache (exp013's regime — largest
|
| 20 |
+
adapter headroom; blob gauge carried as the role-aligned instrument).
|
| 21 |
+
|
| 22 |
+
Judged (all arms, in-bed): common flow-MSE per band; HIGH-band blob gauge;
|
| 23 |
+
ROUTER SIGNATURE = per-prompt usage variance vs a SHUFFLED-KEY null (val
|
| 24 |
+
pass rerun with deranged text keys; text-specific routing must beat the
|
| 25 |
+
null); toggle bit-exact.
|
| 26 |
+
Prereg: P1 te_key >= sigma_key on common val; P2 router signature: usage-
|
| 27 |
+
by-prompt variance(te_key) > 3x shuffled null; P3 toggle; P4 addr_key vs
|
| 28 |
+
te_key ordering = which text representation routes better (no prediction —
|
| 29 |
+
first measurement). 1-seed CANDIDATE.
|
| 30 |
+
|
| 31 |
+
Pod: bash pod2/run_exp014.sh [DEXP14_SEED=0]
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import json
|
| 36 |
+
import math
|
| 37 |
+
import os
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
|
| 41 |
+
sys.path[:0] = ["pod2", "."]
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
import torch.nn as nn
|
| 45 |
+
import torch.nn.functional as F
|
| 46 |
+
|
| 47 |
+
from pod_ledger import ledger_run, note, burn_down
|
| 48 |
+
from d1_substrate import MEM_FRACTION, enumerate_sd15_sites
|
| 49 |
+
from aleph_diffusion_core import derangement
|
| 50 |
+
from dexp009_bandroles import lp
|
| 51 |
+
from dexp013_blob_flow import load_lune, blob_lp_err
|
| 52 |
+
|
| 53 |
+
SHIFT = 2.5
|
| 54 |
+
N_TRAIN, N_VAL = 4096, 256
|
| 55 |
+
A_EXPERTS, RANK = 4, 8
|
| 56 |
+
BATCH = int(os.environ.get("DEXP14_BATCH", "16"))
|
| 57 |
+
STEPS = int(os.environ.get("DEXP14_STEPS", "3000"))
|
| 58 |
+
SEED = int(os.environ.get("DEXP14_SEED", "0"))
|
| 59 |
+
LR, CFG_DROPOUT = 1e-3, 0.1
|
| 60 |
+
D11 = ("/workspace/data/dexp011" if os.path.isdir("/workspace")
|
| 61 |
+
else "./data/dexp011")
|
| 62 |
+
DATA_DIR = ("/workspace/data/dexp014" if os.path.isdir("/workspace")
|
| 63 |
+
else os.path.join(os.environ.get("GEOLIP_DATA", "./data"),
|
| 64 |
+
"dexp014"))
|
| 65 |
+
CKPT_DIR = ("/workspace/ckpts2/dexp014" if os.path.isdir("/workspace")
|
| 66 |
+
else DATA_DIR)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def fourier_sigma(s, dim=8):
|
| 70 |
+
freqs = torch.pow(2.0, torch.arange(dim // 2, device=s.device))
|
| 71 |
+
ang = 2 * math.pi * s[:, None] * freqs[None]
|
| 72 |
+
return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TeDispatchBank(nn.Module):
|
| 76 |
+
"""Expert bank with a text-conditioned dense signed dispatch key."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, d: int, txt_dim: int = 0, A: int = A_EXPERTS,
|
| 79 |
+
r: int = RANK, D: int = 4, tau: float = 0.1):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.d, self.A, self.txt_dim = d, A, txt_dim
|
| 82 |
+
self.tau = tau
|
| 83 |
+
self.down = nn.ModuleList(nn.Linear(d, r, bias=False)
|
| 84 |
+
for _ in range(A))
|
| 85 |
+
self.up = nn.ModuleList(nn.Linear(r, d) for _ in range(A))
|
| 86 |
+
for dn, up in zip(self.down, self.up):
|
| 87 |
+
nn.init.orthogonal_(dn.weight)
|
| 88 |
+
nn.init.zeros_(up.weight)
|
| 89 |
+
nn.init.zeros_(up.bias)
|
| 90 |
+
self.key_proj = nn.Linear(d, D, bias=False)
|
| 91 |
+
self.sig_proj = nn.Linear(8, D, bias=False)
|
| 92 |
+
nn.init.orthogonal_(self.key_proj.weight)
|
| 93 |
+
nn.init.orthogonal_(self.sig_proj.weight)
|
| 94 |
+
if txt_dim > 0:
|
| 95 |
+
self.txt_proj = nn.Linear(txt_dim, D, bias=False)
|
| 96 |
+
nn.init.orthogonal_(self.txt_proj.weight)
|
| 97 |
+
self.codebook = nn.Parameter(F.normalize(torch.randn(A, D), dim=-1))
|
| 98 |
+
self.gates = nn.Parameter(torch.full((A,), -3.0))
|
| 99 |
+
self.enabled = True
|
| 100 |
+
self.last_usage = None
|
| 101 |
+
|
| 102 |
+
def assert_zero_init(self):
|
| 103 |
+
for up in self.up:
|
| 104 |
+
assert up.weight.abs().max().item() == 0.0
|
| 105 |
+
assert up.bias.abs().max().item() == 0.0
|
| 106 |
+
|
| 107 |
+
def dispatch(self, x, sig_feat, txt_feat):
|
| 108 |
+
key = self.key_proj(x)
|
| 109 |
+
sig = self.sig_proj(sig_feat)
|
| 110 |
+
sig = sig.view(sig.shape[0], *([1] * (x.ndim - 2)), sig.shape[-1])
|
| 111 |
+
key = key + sig
|
| 112 |
+
if self.txt_dim > 0 and txt_feat is not None:
|
| 113 |
+
tx = self.txt_proj(txt_feat)
|
| 114 |
+
tx = tx.view(tx.shape[0], *([1] * (x.ndim - 2)), tx.shape[-1])
|
| 115 |
+
key = key + tx
|
| 116 |
+
Ax = F.normalize(self.codebook, dim=-1)
|
| 117 |
+
u = (F.normalize(key, dim=-1) @ Ax.transpose(-1, -2)) / self.tau
|
| 118 |
+
m = u.abs().amax(dim=-1, keepdim=True)
|
| 119 |
+
ep, en = torch.exp(u - m), torch.exp(-u - m)
|
| 120 |
+
return (ep - en) / (ep + en).sum(dim=-1, keepdim=True)
|
| 121 |
+
|
| 122 |
+
def forward(self, x, sig_feat, txt_feat=None):
|
| 123 |
+
if not self.enabled:
|
| 124 |
+
return x
|
| 125 |
+
w = self.dispatch(x, sig_feat, txt_feat)
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
self.last_usage = w.abs().mean(dim=tuple(
|
| 128 |
+
range(1, w.ndim - 1))).detach().cpu() # (B, A) per prompt
|
| 129 |
+
g = torch.sigmoid(self.gates)
|
| 130 |
+
delta = 0
|
| 131 |
+
for k in range(self.A):
|
| 132 |
+
delta = delta + g[k] * w[..., k:k + 1] * self.up[k](
|
| 133 |
+
self.down[k](x))
|
| 134 |
+
return x + delta
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class Wrap(nn.Module):
|
| 138 |
+
def __init__(self, block, bank):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.block = block
|
| 141 |
+
self.bank = bank
|
| 142 |
+
self.sig_feat = None
|
| 143 |
+
self.txt_feat = None
|
| 144 |
+
|
| 145 |
+
def forward(self, *args, **kwargs):
|
| 146 |
+
out = self.block(*args, **kwargs)
|
| 147 |
+
h = out[0] if isinstance(out, tuple) else out
|
| 148 |
+
h = self.bank(h, self.sig_feat, self.txt_feat)
|
| 149 |
+
return (h,) + out[1:] if isinstance(out, tuple) else h
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def attach_banks(unet, txt_dim):
|
| 153 |
+
sites = enumerate_sd15_sites(unet)
|
| 154 |
+
assert len(sites) == 16
|
| 155 |
+
mods, wraps = nn.ModuleList(), []
|
| 156 |
+
for name, block, d in sites:
|
| 157 |
+
p0 = next(block.parameters())
|
| 158 |
+
m = TeDispatchBank(d, txt_dim).to(device=p0.device, dtype=p0.dtype)
|
| 159 |
+
w = Wrap(block, m)
|
| 160 |
+
parent = unet
|
| 161 |
+
parts = name.split(".")
|
| 162 |
+
for p in parts[:-1]:
|
| 163 |
+
parent = getattr(parent, p) if not p.isdigit() else parent[int(p)]
|
| 164 |
+
if parts[-1].isdigit():
|
| 165 |
+
parent[int(parts[-1])] = w
|
| 166 |
+
else:
|
| 167 |
+
setattr(parent, parts[-1], w)
|
| 168 |
+
mods.append(m)
|
| 169 |
+
wraps.append(w)
|
| 170 |
+
return mods, wraps
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def build_text_feats(device):
|
| 174 |
+
"""addr: frozen byte-trigram aleph address of each fused caption
|
| 175 |
+
(canonical recipe, flattened 4096); pooler: CLIP text pooler_output."""
|
| 176 |
+
f = os.path.join(DATA_DIR, "textfeats.pt")
|
| 177 |
+
if os.path.exists(f):
|
| 178 |
+
return torch.load(f, map_location="cpu", weights_only=True)
|
| 179 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 180 |
+
from dexp011_fused_multiband import _iter_fused
|
| 181 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 182 |
+
caps = []
|
| 183 |
+
for r in _iter_fused(N_TRAIN + N_VAL):
|
| 184 |
+
caps.append(str(r.get("caption_joycaption")
|
| 185 |
+
or r.get("prompt_fused") or ""))
|
| 186 |
+
from dexp002_sd15_addrcond import Addr
|
| 187 |
+
enc = Addr(device)
|
| 188 |
+
addr = enc.encode(caps).reshape(len(caps), -1) # (N, 4096)
|
| 189 |
+
del enc
|
| 190 |
+
torch.cuda.empty_cache()
|
| 191 |
+
tok = CLIPTokenizer.from_pretrained(
|
| 192 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="tokenizer")
|
| 193 |
+
te = CLIPTextModel.from_pretrained(
|
| 194 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 195 |
+
subfolder="text_encoder", torch_dtype=torch.float32).to(device).eval()
|
| 196 |
+
pools = []
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
for i in range(0, len(caps), 64):
|
| 199 |
+
ids = tok(caps[i:i + 64], padding="max_length", max_length=77,
|
| 200 |
+
truncation=True, return_tensors="pt").input_ids
|
| 201 |
+
pools.append(te(ids.to(device)).pooler_output.cpu())
|
| 202 |
+
del te
|
| 203 |
+
torch.cuda.empty_cache()
|
| 204 |
+
out = {"addr": addr, "pooler": torch.cat(pools)}
|
| 205 |
+
torch.save(out, f)
|
| 206 |
+
print(f"[textfeats] built: addr {out['addr'].shape}, "
|
| 207 |
+
f"pooler {out['pooler'].shape}", flush=True)
|
| 208 |
+
return out
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def run(device="cuda"):
|
| 212 |
+
torch.cuda.set_per_process_memory_fraction(MEM_FRACTION, 0)
|
| 213 |
+
os.makedirs(CKPT_DIR, exist_ok=True)
|
| 214 |
+
cache = torch.load(os.path.join(D11, "cache.pt"), map_location="cpu",
|
| 215 |
+
weights_only=True)
|
| 216 |
+
with ledger_run("dexp014 text feats", budget_h=0.5):
|
| 217 |
+
tf = build_text_feats(device)
|
| 218 |
+
gv = torch.Generator().manual_seed(SEED + 11)
|
| 219 |
+
u = torch.linspace(0.02, 0.98, N_VAL)
|
| 220 |
+
val_sigma = (SHIFT * u) / (1 + (SHIFT - 1) * u)
|
| 221 |
+
ARMS = {"sigma_key": (0, None),
|
| 222 |
+
"addr_key": (4096, "addr"),
|
| 223 |
+
"te_key": (768, "pooler")}
|
| 224 |
+
|
| 225 |
+
def txt_of(kind, sel):
|
| 226 |
+
if kind is None:
|
| 227 |
+
return None
|
| 228 |
+
return tf[kind][sel].float().to("cuda")
|
| 229 |
+
|
| 230 |
+
def set_feats(wraps, s01, txt):
|
| 231 |
+
sf = fourier_sigma(s01)
|
| 232 |
+
for wr in wraps:
|
| 233 |
+
wr.sig_feat = sf
|
| 234 |
+
wr.txt_feat = txt
|
| 235 |
+
|
| 236 |
+
def loss_of(unet, wraps, lat, ehs, gen):
|
| 237 |
+
bsz = lat.shape[0]
|
| 238 |
+
drop = torch.rand(bsz, generator=gen, device=device) < CFG_DROPOUT
|
| 239 |
+
ehs = ehs.clone()
|
| 240 |
+
ehs[drop] = 0
|
| 241 |
+
s = torch.rand(bsz, generator=gen, device=device)
|
| 242 |
+
s = (SHIFT * s) / (1 + (SHIFT - 1) * s)
|
| 243 |
+
noise = torch.randn(lat.shape, generator=gen, device=device)
|
| 244 |
+
s4 = s[:, None, None, None]
|
| 245 |
+
x_t, v = noise * s4 + lat * (1 - s4), noise - lat
|
| 246 |
+
for wr in wraps:
|
| 247 |
+
wr.sig_feat = fourier_sigma(s)
|
| 248 |
+
pred = unet(x_t, s * 1000, ehs, return_dict=False)[0]
|
| 249 |
+
return F.mse_loss(pred, v)
|
| 250 |
+
|
| 251 |
+
@torch.no_grad()
|
| 252 |
+
def val(unet, wraps, kind, shuffle_txt=False):
|
| 253 |
+
tot, blob_high, usages = [], [], []
|
| 254 |
+
perm = derangement(N_VAL, seed=SEED + 3)
|
| 255 |
+
for i in range(0, N_VAL, 32):
|
| 256 |
+
lat = cache["val_lat"][i:i + 32].to(device)
|
| 257 |
+
ehs = cache["val_ehs"][i:i + 32].to(device)
|
| 258 |
+
noise = cache["val_noise"][i:i + 32].to(device)
|
| 259 |
+
blob = cache["val_blob"][i:i + 32].float().to(device)
|
| 260 |
+
s = val_sigma[i:i + 32].to(device)
|
| 261 |
+
sel = torch.arange(N_TRAIN + i, N_TRAIN + i + lat.shape[0])
|
| 262 |
+
if shuffle_txt:
|
| 263 |
+
sel = N_TRAIN + perm[i:i + lat.shape[0]]
|
| 264 |
+
set_feats(wraps, s, txt_of(kind, sel))
|
| 265 |
+
s4 = s[:, None, None, None]
|
| 266 |
+
x_t, v = noise * s4 + lat * (1 - s4), noise - lat
|
| 267 |
+
pred = unet(x_t, s * 1000, ehs, return_dict=False)[0]
|
| 268 |
+
tot += ((pred - v) ** 2).mean(dim=(1, 2, 3)).tolist()
|
| 269 |
+
x0_hat = x_t - s4 * pred
|
| 270 |
+
bg = blob_lp_err(x0_hat, lat, blob)
|
| 271 |
+
for j, sv in enumerate(s.tolist()):
|
| 272 |
+
if sv > 0.75:
|
| 273 |
+
blob_high.append(bg[j].item())
|
| 274 |
+
for wr in wraps[8:9]:
|
| 275 |
+
if wr.bank.last_usage is not None:
|
| 276 |
+
usages.append(wr.bank.last_usage)
|
| 277 |
+
usage = torch.cat(usages) if usages else None
|
| 278 |
+
usage_var = float(usage.var(dim=0).mean()) if usage is not None else 0
|
| 279 |
+
return (sum(tot) / len(tot),
|
| 280 |
+
round(sum(blob_high) / max(len(blob_high), 1), 6),
|
| 281 |
+
round(usage_var, 8))
|
| 282 |
+
|
| 283 |
+
results = {"config": {"steps": STEPS, "batch": BATCH, "seed": SEED,
|
| 284 |
+
"trunk": "base_lune flow", "A": A_EXPERTS,
|
| 285 |
+
"r": RANK}}
|
| 286 |
+
with ledger_run(f"dexp014 frozen s{SEED}", budget_h=0.2) as h:
|
| 287 |
+
unet = load_lune(device)
|
| 288 |
+
v, bg, _ = val(unet, [], None)
|
| 289 |
+
results["frozen"] = {"val": v, "blob_high": bg}
|
| 290 |
+
del unet
|
| 291 |
+
torch.cuda.empty_cache()
|
| 292 |
+
h["verdict"] = f"val {v:.5f}"
|
| 293 |
+
|
| 294 |
+
for arm, (txt_dim, kind) in ARMS.items():
|
| 295 |
+
with ledger_run(f"dexp014 {arm} s{SEED}", budget_h=2.2) as h:
|
| 296 |
+
unet = load_lune(device)
|
| 297 |
+
mods, wraps = attach_banks(unet, txt_dim)
|
| 298 |
+
for m in mods:
|
| 299 |
+
m.assert_zero_init()
|
| 300 |
+
# bind txt feats into the TRAIN loss via a wrapper closure
|
| 301 |
+
opt = torch.optim.Adam(mods.parameters(), lr=LR, weight_decay=0.0)
|
| 302 |
+
gen = torch.Generator(device=device).manual_seed(SEED + 42)
|
| 303 |
+
idx = torch.Generator().manual_seed(SEED + 7)
|
| 304 |
+
t0 = time.time()
|
| 305 |
+
for step in range(1, STEPS + 1):
|
| 306 |
+
sel = torch.randint(0, N_TRAIN, (BATCH,), generator=idx)
|
| 307 |
+
for wr in wraps:
|
| 308 |
+
wr.txt_feat = txt_of(kind, sel)
|
| 309 |
+
loss = loss_of(unet, wraps, cache["lat"][sel].to(device),
|
| 310 |
+
cache["ehs"][sel].to(device), gen)
|
| 311 |
+
loss.backward()
|
| 312 |
+
opt.step()
|
| 313 |
+
opt.zero_grad(set_to_none=True)
|
| 314 |
+
if step == 50 or step % 500 == 0:
|
| 315 |
+
print(f"[{arm}] step {step}: loss {loss.item():.4f} | "
|
| 316 |
+
f"{(time.time() - t0) / step:.2f}s/step",
|
| 317 |
+
flush=True)
|
| 318 |
+
v, bg, uv = val(unet, wraps, kind)
|
| 319 |
+
_, _, uv_null = val(unet, wraps, kind, shuffle_txt=True) \
|
| 320 |
+
if kind else (0, 0, 0)
|
| 321 |
+
for m in mods:
|
| 322 |
+
m.enabled = False
|
| 323 |
+
v_off, _, _ = val(unet, wraps, kind)
|
| 324 |
+
d = abs(v_off - results["frozen"]["val"])
|
| 325 |
+
assert d < 1e-9, f"toggle parity broken: {d}"
|
| 326 |
+
for m in mods:
|
| 327 |
+
m.enabled = True
|
| 328 |
+
torch.save({"mods": [m.state_dict() for m in mods]},
|
| 329 |
+
os.path.join(CKPT_DIR, f"{arm}_s{SEED}.pt"))
|
| 330 |
+
results[arm] = {"val": v, "blob_high": bg,
|
| 331 |
+
"usage_var_by_prompt": uv,
|
| 332 |
+
"usage_var_shuffled_null": uv_null,
|
| 333 |
+
"val_toggled_off": v_off}
|
| 334 |
+
del unet, mods
|
| 335 |
+
torch.cuda.empty_cache()
|
| 336 |
+
h["verdict"] = f"val {v:.5f} uvar {uv:.2e}"
|
| 337 |
+
|
| 338 |
+
sk, ak, tk = (results[a] for a in ("sigma_key", "addr_key", "te_key"))
|
| 339 |
+
results["verdict"] = {
|
| 340 |
+
"P1_te_vs_sigma": "te" if tk["val"] <= sk["val"] else "sigma",
|
| 341 |
+
"P2_router_signature": {
|
| 342 |
+
"te_var": tk["usage_var_by_prompt"],
|
| 343 |
+
"te_null": tk["usage_var_shuffled_null"],
|
| 344 |
+
"hit_3x": tk["usage_var_by_prompt"]
|
| 345 |
+
> 3 * max(tk["usage_var_shuffled_null"], 1e-12)},
|
| 346 |
+
"P4_text_rep_ordering": {
|
| 347 |
+
"addr_key_val": ak["val"], "te_key_val": tk["val"],
|
| 348 |
+
"addr_key_var": ak["usage_var_by_prompt"],
|
| 349 |
+
"te_key_var": tk["usage_var_by_prompt"]},
|
| 350 |
+
"common": {a: results[a]["val"] for a in ARMS},
|
| 351 |
+
"note": "router-solidifier v1; 1-seed CANDIDATE",
|
| 352 |
+
}
|
| 353 |
+
with open(os.path.join(DATA_DIR, "results.json" if SEED == 0
|
| 354 |
+
else f"results_s{SEED}.json"), "w") as f:
|
| 355 |
+
json.dump(results, f, indent=2)
|
| 356 |
+
note(f"dexp014: {json.dumps(results['verdict']['P2_router_signature'])}")
|
| 357 |
+
print(json.dumps(results["verdict"], indent=2))
|
| 358 |
+
burn_down()
|
| 359 |
+
return results
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def smoke():
|
| 363 |
+
b = TeDispatchBank(320, txt_dim=768)
|
| 364 |
+
b.assert_zero_init()
|
| 365 |
+
x = torch.randn(2, 9, 320)
|
| 366 |
+
sf = fourier_sigma(torch.tensor([0.3, 0.8]))
|
| 367 |
+
tx = torch.randn(2, 768)
|
| 368 |
+
assert torch.equal(b(x, sf, tx), x), "zero-init must be exact"
|
| 369 |
+
w = b.dispatch(x, sf, tx)
|
| 370 |
+
w2 = b.dispatch(x, sf, torch.randn(2, 768))
|
| 371 |
+
assert w.shape == (2, 9, 4) and not torch.equal(w, w2), \
|
| 372 |
+
"text key must move the dispatch"
|
| 373 |
+
b0 = TeDispatchBank(320, txt_dim=0)
|
| 374 |
+
assert torch.equal(b0(x, sf, None), x)
|
| 375 |
+
print("dexp014 smoke PASSED (zero-init, text-sensitive dispatch, "
|
| 376 |
+
"no-text arm)")
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
if __name__ == "__main__":
|
| 380 |
+
if "--run" in sys.argv:
|
| 381 |
+
run()
|
| 382 |
+
else:
|
| 383 |
+
smoke()
|
exp014_te_dispatch/results.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"config": {
|
| 3 |
+
"steps": 3000,
|
| 4 |
+
"batch": 16,
|
| 5 |
+
"seed": 0,
|
| 6 |
+
"trunk": "base_lune flow",
|
| 7 |
+
"A": 4,
|
| 8 |
+
"r": 8
|
| 9 |
+
},
|
| 10 |
+
"frozen": {
|
| 11 |
+
"val": 0.6298933834768832,
|
| 12 |
+
"blob_high": 0.184471
|
| 13 |
+
},
|
| 14 |
+
"sigma_key": {
|
| 15 |
+
"val": 0.5737131804926321,
|
| 16 |
+
"blob_high": 0.127068,
|
| 17 |
+
"usage_var_by_prompt": 0.02356817,
|
| 18 |
+
"usage_var_shuffled_null": 0,
|
| 19 |
+
"val_toggled_off": 0.6298933834768832
|
| 20 |
+
},
|
| 21 |
+
"addr_key": {
|
| 22 |
+
"val": 0.5775512405671179,
|
| 23 |
+
"blob_high": 0.127947,
|
| 24 |
+
"usage_var_by_prompt": 1.403e-05,
|
| 25 |
+
"usage_var_shuffled_null": 1.4e-05,
|
| 26 |
+
"val_toggled_off": 0.6298933834768832
|
| 27 |
+
},
|
| 28 |
+
"te_key": {
|
| 29 |
+
"val": 0.5742165236733854,
|
| 30 |
+
"blob_high": 0.12704,
|
| 31 |
+
"usage_var_by_prompt": 0.02597812,
|
| 32 |
+
"usage_var_shuffled_null": 0.02707456,
|
| 33 |
+
"val_toggled_off": 0.6298933834768832
|
| 34 |
+
},
|
| 35 |
+
"verdict": {
|
| 36 |
+
"P1_te_vs_sigma": "sigma",
|
| 37 |
+
"P2_router_signature": {
|
| 38 |
+
"te_var": 0.02597812,
|
| 39 |
+
"te_null": 0.02707456,
|
| 40 |
+
"hit_3x": false
|
| 41 |
+
},
|
| 42 |
+
"P4_text_rep_ordering": {
|
| 43 |
+
"addr_key_val": 0.5775512405671179,
|
| 44 |
+
"te_key_val": 0.5742165236733854,
|
| 45 |
+
"addr_key_var": 1.403e-05,
|
| 46 |
+
"te_key_var": 0.02597812
|
| 47 |
+
},
|
| 48 |
+
"common": {
|
| 49 |
+
"sigma_key": 0.5737131804926321,
|
| 50 |
+
"addr_key": 0.5775512405671179,
|
| 51 |
+
"te_key": 0.5742165236733854
|
| 52 |
+
},
|
| 53 |
+
"note": "router-solidifier v1; 1-seed CANDIDATE"
|
| 54 |
+
}
|
| 55 |
+
}
|