ashen-navigator's picture
Add Universal-Eve trainer (covcollab-eve-mtl) + TRAINING.md with NVIDIA/A100 guide
b295f1c verified
Raw
History Blame Contribute Delete
30.7 kB
"""Multi-task Universal Eve: detect covert comms AND fingerprint the structure.
Motivation (architecture research): the covert-trained detector is a PRESENCE
detector that is BLIND to format/channel/M in the deep-covert regime -- the
structure information is genuinely buried (SNR walls). So a dual-capability warden
is really a detector + a *conditional* fingerprinter, and the headline is the
**structure-recovery frontier**: at what adversary advantage (regime / SNR) does
the warden graduate from "something is transmitting" to "it's OFDM, M=16, covert
policy on".
Model: the validated UniversalEve backbone (multi-scale Conv1d -> SSM -> masked
antenna pool + 7-dim spatial eigen-branch) produces a detection embedding ``e``; a
**spectral/pilot branch** (PSD + cyclic-autocorrelation, where format identity
lives) is concatenated for the structure heads. Heads: detection (BCE, all
samples) + format / M / K / d / channel / policy-arm (CE, H1 only), combined with a
**masked, uncertainty-weighted** (Kendall-Gal) multi-task loss so an unlearnable
format gradient in deep-covert doesn't inject negative transfer onto detection.
Regimes:
A joint multi-task from scratch.
C detection-only pretrain -> freeze backbone -> probe structure off the frozen
detection embedding (isolates the representational content; the probing
question with a proper head, stratified by regime).
"""
from __future__ import annotations
import argparse
import json
import math
import os
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..formats import FORMAT_IDS
from .dataset import to_real_iq
from .device import pick_device
from .model import N_SPATIAL, AntennaEncoder, spatial_features
def _auc(score: np.ndarray, lab: np.ndarray) -> float:
"""ROC-AUC via the Mann-Whitney statistic (ties counted at 1/2). Self-contained so the
trainer needs no part of the generation-only audit stack."""
s1, s0 = score[lab == 1], score[lab == 0]
return float(np.mean(s1[:, None] > s0[None, :]) + 0.5 * np.mean(s1[:, None] == s0[None, :]))
# --------------------------------------------------------------------------
# label vocabularies (match the controlled dataset)
# --------------------------------------------------------------------------
FMT_VOCAB = list(FORMAT_IDS) # sc,ofdm,dfts_ofdm,otfs,afdm,ofdm_comb
M_VOCAB = [8, 12, 16, 25]
K_VOCAB = [2, 4]
D_VOCAB = [1, 2, 4]
CHAN_VOCAB = ["flat", "multipath", "doppler"]
ARM_VOCAB = ["none", "random", "optimized"]
REGIMES = ["covert", "comparable", "detectable"]
# structure tasks: (name, vocab)
STRUCT_TASKS = [("format", FMT_VOCAB), ("M", M_VOCAB), ("K", K_VOCAB),
("d", D_VOCAB), ("chan", CHAN_VOCAB), ("arm", ARM_VOCAB)]
TASKS = ["det"] + [t for t, _ in STRUCT_TASKS]
def _idx(vocab):
return {str(v): i for i, v in enumerate(vocab)}
_MAPS = {"format": _idx(FMT_VOCAB), "M": _idx(M_VOCAB), "K": _idx(K_VOCAB),
"d": _idx(D_VOCAB), "chan": _idx(CHAN_VOCAB), "arm": _idx(ARM_VOCAB)}
SPEC_LAGS = (16, 32, 48, 64, 80, 160, 240) # cyclic-autocorr lags (CP/frame cues)
SPEC_PSD_BINS = 64
SPEC_DIM = SPEC_PSD_BINS + len(SPEC_LAGS)
# Device on which per-batch feature extraction (complex FFT + spatial eigvalsh) runs.
# None -> CPU (default; MPS has no complex support, so features must stay on CPU there).
# main() sets this to 'cuda' when training on an NVIDIA GPU, so the whole step runs on-device.
_FEAT_DEVICE: "str | None" = None
# --------------------------------------------------------------------------
# feature extraction (complex ops -> stay on CPU; the net is real-valued)
# --------------------------------------------------------------------------
def spectral_feats(Yb: torch.Tensor) -> torch.Tensor:
"""(n,R,T) complex -> (n, SPEC_DIM) real: antenna-mean log-PSD (64 bins) +
normalized cyclic-autocorrelation magnitudes at frame-relevant lags."""
n, r, t = Yb.shape
Yf = torch.fft.fft(Yb, dim=-1)
psd = torch.log1p((Yf.abs() ** 2).mean(1)) # (n,T)
k = t // SPEC_PSD_BINS
psd = F.avg_pool1d(psd.unsqueeze(1), kernel_size=k, stride=k).squeeze(1)[:, :SPEC_PSD_BINS]
psd = (psd - psd.mean(1, keepdim=True)) / (psd.std(1, keepdim=True) + 1e-6)
energy = (Yb.abs() ** 2).mean((1, 2)).clamp_min(1e-9) # (n,)
acs = []
for L in SPEC_LAGS:
ac = (Yb[..., :-L] * Yb[..., L:].conj()).mean(-1) # (n,R) complex
acs.append(ac.abs().mean(1) / energy) # (n,)
return torch.cat([psd, torch.stack(acs, 1)], 1).float() # (n, SPEC_DIM)
def batch_feats(Yb: torch.Tensor):
"""(n,R,T) complex64 -> (x (n,R,3,T), sp (n,7), mask (n,R) bool, spec (n,SPEC_DIM)).
Runs on ``_FEAT_DEVICE`` when set (CUDA path: complex64 FFT + eigvalsh on the GPU);
callers move the returned float32 features to the net device afterwards."""
if _FEAT_DEVICE is not None:
Yb = Yb.to(_FEAT_DEVICE)
n, r, _ = Yb.shape
x = to_real_iq(Yb) # (n,R,3,T) float32
mask = torch.ones(n, r, dtype=torch.bool, device=Yb.device)
sp = spatial_features(Yb, mask) # (n,7)
spec = spectral_feats(Yb) # (n,SPEC_DIM)
return x, sp, mask, spec
# --------------------------------------------------------------------------
# model
# --------------------------------------------------------------------------
class SpectralMLP(nn.Module):
def __init__(self, in_dim=SPEC_DIM, d=48, drop=0.2):
super().__init__()
self.net = nn.Sequential(nn.Linear(in_dim, d), nn.GELU(), nn.Dropout(drop),
nn.Linear(d, d), nn.GELU())
self.d = d
def forward(self, s):
return self.net(s)
class MultiTaskUniversalEve(nn.Module):
"""Shared detection backbone -> embedding ``e``; spectral branch -> ``spec_emb``;
detection head off ``e``; structure heads off ``[e, spec_emb]``."""
def __init__(self, width=96, drop=0.3, spec_d=48):
super().__init__()
self.ant = AntennaEncoder(3, width, drop=drop)
self.D = self.ant.d
self.attn = nn.Linear(self.D, 1)
self.spatial_norm = nn.LayerNorm(N_SPATIAL)
self.block = nn.Sequential(nn.Linear(2 * self.D + N_SPATIAL, self.D), nn.GELU(), nn.Dropout(drop))
self.det_head = nn.Linear(self.D, 1) # detection off e
self.spec = SpectralMLP(SPEC_DIM, spec_d, drop=min(0.3, drop))
sd = self.D + spec_d
self.struct_heads = nn.ModuleDict(
{name: nn.Sequential(nn.Linear(sd, self.D), nn.GELU(), nn.Dropout(drop),
nn.Linear(self.D, len(vocab)))
for name, vocab in STRUCT_TASKS})
def embed(self, x, sp, mask):
"""x:(N,R,3,T) real, sp:(N,7), mask:(N,R) -> detection embedding e:(N,D)."""
n, r = x.shape[:2]
z = self.ant(x.reshape(n * r, *x.shape[2:])).reshape(n, r, self.D)
m = mask.unsqueeze(-1)
a = torch.softmax(self.attn(z).masked_fill(~m, float("-inf")), dim=1)
attn_pool = (a * z).sum(1)
mean_pool = (z * m).sum(1) / m.sum(1).clamp_min(1)
return self.block(torch.cat([attn_pool, mean_pool, self.spatial_norm(sp)], dim=1))
def forward(self, x, sp, mask, spec):
e = self.embed(x, sp, mask)
se = torch.cat([e, self.spec(spec)], dim=1)
out = {"det": self.det_head(e).squeeze(-1)}
for name in self.struct_heads:
out[name] = self.struct_heads[name](se)
return out
class LinearProbes(nn.Module):
"""Structure probes on a FROZEN detection embedding (regime C). MLP probes so
the comparison to A is about the representation, not head capacity."""
def __init__(self, d, drop=0.2):
super().__init__()
self.heads = nn.ModuleDict(
{name: nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Dropout(drop),
nn.Linear(d, len(vocab)))
for name, vocab in STRUCT_TASKS})
def forward(self, e):
return {name: self.heads[name](e) for name in self.heads}
# --------------------------------------------------------------------------
# masked, uncertainty-weighted multi-task loss (Kendall-Gal)
# --------------------------------------------------------------------------
class MTLoss(nn.Module):
def __init__(self, tasks=TASKS):
super().__init__()
self.tasks = list(tasks)
self.log_sigma = nn.Parameter(torch.zeros(len(self.tasks))) # learnable uncertainty
self.bce = nn.BCEWithLogitsLoss()
self.ce = nn.CrossEntropyLoss()
def forward(self, out, labels, h1):
"""out: head logits; labels: dict of index tensors (+ 'det' float01); h1: bool mask.
Structure losses are computed on H1 only. Returns (total, raw{task:loss})."""
raw = {}
raw["det"] = self.bce(out["det"], labels["det"])
h1 = h1.bool()
for name, _ in STRUCT_TASKS:
if name in self.tasks and h1.any():
raw[name] = self.ce(out[name][h1], labels[name][h1])
elif name in self.tasks:
raw[name] = out[name].sum() * 0.0
total = 0.0
for i, tsk in enumerate(self.tasks):
s = self.log_sigma[i]
total = total + torch.exp(-s) * raw[tsk] + 0.5 * s
return total, {k: float(v.detach()) for k, v in raw.items()}
# --------------------------------------------------------------------------
# data
# --------------------------------------------------------------------------
def load_arrays(data_dir: str, split: str, max_n: int | None = None, seed: int = 0) -> dict:
"""Load one split's Y + encoded multi-task labels as torch tensors (Y on CPU)."""
from .controlled import load_split
d = load_split(data_dir, split)
Y = torch.from_numpy(d["Y"]) # (n,R,T) complex64
n = Y.shape[0]
if max_n and max_n < n:
rng = np.random.default_rng(seed)
keep = np.sort(rng.choice(n, size=max_n, replace=False))
Y = Y[keep]
d = {k: (v[keep] if hasattr(v, "__len__") and len(v) == n else v) for k, v in d.items()}
n = max_n
out = {"Y": Y, "n": n}
out["det"] = torch.from_numpy(d["label"].astype(np.float32))
out["format"] = torch.tensor([_MAPS["format"][str(v)] for v in d["format"]], dtype=torch.long)
out["M"] = torch.tensor([_MAPS["M"][str(int(v))] for v in d["n_tx"]], dtype=torch.long)
out["K"] = torch.tensor([_MAPS["K"][str(int(v))] for v in d["n_msg_users"]], dtype=torch.long)
out["d"] = torch.tensor([_MAPS["d"][str(int(v))] for v in d["msg_dim"]], dtype=torch.long)
out["chan"] = torch.tensor([_MAPS["chan"][str(v)] for v in d["channel_family"]], dtype=torch.long)
out["arm"] = torch.tensor([_MAPS["arm"][str(v)] for v in d["policy_arm"]], dtype=torch.long)
out["regime"] = np.array([str(v) for v in d["regime"]])
out["arm_str"] = np.array([str(v) for v in d["policy_arm"]])
out["fmt_str"] = np.array([str(v) for v in d["format"]])
out["eve_snr"] = np.asarray(d["eve_snr_db"], dtype=np.float32)
out["cell_id"] = np.asarray(d["cell_id"], dtype=np.int64) # same-emitter grouping (multi-look)
return out
def _to_dev(t, dev):
return {k: (v.to(dev) if torch.is_tensor(v) else v) for k, v in t.items()}
# --------------------------------------------------------------------------
# evaluation: the structure-recovery frontier
# --------------------------------------------------------------------------
@torch.no_grad()
def evaluate(model, arr, device, *, batch=512, probes=None, embed_only=False) -> dict:
"""Per-regime detection AUC + per-attribute H1 accuracy (overall, per regime,
per arm for 'format'). ``probes`` (regime C) reads the frozen embedding."""
model.eval()
if probes is not None:
probes.eval()
n = arr["n"]
det_logits = np.empty(n, np.float32)
preds = {name: np.empty(n, np.int64) for name, _ in STRUCT_TASKS}
for lo in range(0, n, batch):
hi = min(lo + batch, n)
Yb = arr["Y"][lo:hi]
x, sp, mask, spec = batch_feats(Yb)
x, sp, mask, spec = x.to(device), sp.to(device), mask.to(device), spec.to(device)
if probes is not None:
e = model.embed(x, sp, mask)
det_logits[lo:hi] = model.det_head(e).squeeze(-1).cpu().numpy()
ph = probes(e)
for name, _ in STRUCT_TASKS:
preds[name][lo:hi] = ph[name].argmax(1).cpu().numpy()
else:
out = model(x, sp, mask, spec)
det_logits[lo:hi] = out["det"].cpu().numpy()
for name, _ in STRUCT_TASKS:
preds[name][lo:hi] = out[name].argmax(1).cpu().numpy()
labels = {name: arr[name].numpy() for name, _ in STRUCT_TASKS}
det = arr["det"].numpy()
reg = arr["regime"]
h1 = det == 1
res = {"n": int(n), "detection_auc": {}, "structure_acc": {}, "format_acc_by_arm": {}}
# detection AUC overall + per regime
res["detection_auc"]["overall"] = round(float(_auc(det_logits, det)), 4) if 0 < det.sum() < n else None
for rg in REGIMES:
m = reg == rg
if m.sum() > 1 and 0 < det[m].sum() < m.sum():
res["detection_auc"][rg] = round(float(_auc(det_logits[m], det[m])), 4)
# structure accuracy (H1 only): overall + per regime
for name, vocab in STRUCT_TASKS:
acc = {"chance": round(1.0 / len(vocab), 3)}
mm = h1
acc["overall"] = round(float((preds[name][mm] == labels[name][mm]).mean()), 4) if mm.sum() else None
for rg in REGIMES:
m = h1 & (reg == rg)
if m.sum():
acc[rg] = round(float((preds[name][m] == labels[name][m]).mean()), 4)
res["structure_acc"][name] = acc
# format accuracy per arm x regime (is the covert 'optimized' arm the hardest to fingerprint?)
for arm in ARM_VOCAB:
row = {}
for rg in REGIMES:
m = h1 & (arr["arm_str"] == arm) & (reg == rg)
if m.sum():
row[rg] = round(float((preds["format"][m] == labels["format"][m]).mean()), 4)
res["format_acc_by_arm"][arm] = row
return res
# --------------------------------------------------------------------------
# training
# --------------------------------------------------------------------------
def _lr_factor(frac, warm=0.03, min_frac=0.05):
if frac < warm:
return frac / warm
p = (frac - warm) / max(1e-9, 1 - warm)
return min_frac + 0.5 * (1 - min_frac) * (1 + math.cos(math.pi * min(1.0, p)))
def _sample_batch(arr, idx, dev):
Yb = arr["Y"][idx]
x, sp, mask, spec = batch_feats(Yb)
labels = {"det": arr["det"][idx]}
for name, _ in STRUCT_TASKS:
labels[name] = arr[name][idx]
x, sp, mask, spec = x.to(dev), sp.to(dev), mask.to(dev), spec.to(dev)
labels = {k: v.to(dev) for k, v in labels.items()}
return x, sp, mask, spec, labels
def train_joint(train, val, *, device, steps=4000, width=96, batch=256, lr=1e-3,
tasks=TASKS, run_dir="runs/mtl_A", log_every=200, seed=0, verbose=True) -> dict:
"""Regime A: joint multi-task from scratch."""
os.makedirs(run_dir, exist_ok=True)
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
model = MultiTaskUniversalEve(width=width).to(device)
mtl = MTLoss(tasks).to(device)
opt = torch.optim.AdamW(list(model.parameters()) + list(mtl.parameters()), lr=lr, weight_decay=1e-4)
hist = []
t0 = time.perf_counter()
n = train["n"]
for it in range(steps):
for g in opt.param_groups:
g["lr"] = lr * _lr_factor(it / max(1, steps))
idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
x, sp, mask, spec, labels = _sample_batch(train, idx, device)
model.train()
out = model(x, sp, mask, spec)
loss, raw = mtl(out, labels, labels["det"])
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(mtl.parameters()), 1.0)
opt.step()
if verbose and (it % log_every == 0 or it == steps - 1):
lv = float(loss.detach())
sps = (it + 1) / (time.perf_counter() - t0)
print(f" [A it={it:5d}] loss={lv:.3f} "
+ " ".join(f"{k}={v:.3f}" for k, v in raw.items())
+ f" {sps:.1f} it/s", flush=True)
hist.append({"it": it, "loss": round(lv, 4), "raw": {k: round(v, 4) for k, v in raw.items()}})
torch.save({"model": model.state_dict(), "mtl": mtl.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
va = evaluate(model, val, device)
if verbose:
print(f" [A] val det_auc={va['detection_auc']} "
f"format_acc={ {r: va['structure_acc']['format'].get(r) for r in REGIMES} }", flush=True)
return {"model": model, "history": hist, "val": va, "wall_s": round(time.perf_counter() - t0, 1)}
def train_detonly_then_probe(train, val, *, device, det_steps=4000, probe_steps=2500,
width=96, batch=256, lr=1e-3, run_dir="runs/mtl_C",
log_every=200, seed=1, verbose=True) -> dict:
"""Regime C: detection-only pretrain -> freeze backbone -> MLP structure probes
on the frozen detection embedding."""
os.makedirs(run_dir, exist_ok=True)
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
model = MultiTaskUniversalEve(width=width).to(device)
bce = nn.BCEWithLogitsLoss()
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
t0 = time.perf_counter()
n = train["n"]
# -- detection-only pretrain --
for it in range(det_steps):
for g in opt.param_groups:
g["lr"] = lr * _lr_factor(it / max(1, det_steps))
idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
x, sp, mask, spec, labels = _sample_batch(train, idx, device)
model.train()
logit = model.det_head(model.embed(x, sp, mask)).squeeze(-1)
loss = bce(logit, labels["det"])
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
if verbose and (it % log_every == 0 or it == det_steps - 1):
print(f" [C-det it={it:5d}] bce={float(loss):.3f} {(it+1)/(time.perf_counter()-t0):.1f} it/s", flush=True)
# -- freeze backbone, train probes on frozen embedding --
for p in model.parameters():
p.requires_grad_(False)
probes = LinearProbes(model.D).to(device)
popt = torch.optim.AdamW(probes.parameters(), lr=1e-3, weight_decay=1e-4)
ce = nn.CrossEntropyLoss()
tp = time.perf_counter()
for it in range(probe_steps):
idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
x, sp, mask, spec, labels = _sample_batch(train, idx, device)
with torch.no_grad():
e = model.embed(x, sp, mask)
h1 = labels["det"].bool()
if h1.sum() < 2:
continue
ph = probes(e[h1])
loss = sum(ce(ph[name], labels[name][h1]) for name, _ in STRUCT_TASKS)
popt.zero_grad(); loss.backward(); popt.step()
if verbose and (it % log_every == 0 or it == probe_steps - 1):
print(f" [C-probe it={it:5d}] ce_sum={float(loss):.3f} {(it+1)/(time.perf_counter()-tp):.1f} it/s", flush=True)
torch.save({"model": model.state_dict(), "probes": probes.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
va = evaluate(model, val, device, probes=probes)
if verbose:
print(f" [C] val det_auc={va['detection_auc']} "
f"format_acc={ {r: va['structure_acc']['format'].get(r) for r in REGIMES} }", flush=True)
return {"model": model, "probes": probes, "val": va, "wall_s": round(time.perf_counter() - t0, 1)}
# --------------------------------------------------------------------------
# regime B: multi-look aggregation (lift the fingerprinting frontier)
# --------------------------------------------------------------------------
# A warden watching a persistent emitter collects many blocks; pooling L looks of
# the SAME emitter (same factorial cell -> same format/M/arm/channel) averages out
# per-block noise and raises the fingerprint SNR ~sqrt(L) without any new data.
def _h1_by_cell(arr) -> dict:
cid = arr["cell_id"]
det = arr["det"].numpy()
cells = {}
for c in np.unique(cid[det == 1]):
cells[int(c)] = np.where((cid == c) & (det == 1))[0]
return cells
def _sample_look_idx(cells, keys, n_looks, L, rng) -> torch.Tensor:
"""(n_looks*L,) flat indices, ordered look-major (each look = L blocks of one cell)."""
out = []
for _ in range(n_looks):
pool = cells[int(keys[rng.integers(len(keys))])]
out.append(pool[rng.integers(len(pool), size=L)])
return torch.from_numpy(np.concatenate(out))
def _look_feats(arr, idx):
return batch_feats(arr["Y"][idx])
def _pool_struct(model, x, sp, mask, spec, n_looks, L):
"""Encode L blocks/look, mean-pool e and spec_emb over the look -> structure logits."""
e = model.embed(x, sp, mask).view(n_looks, L, -1).mean(1)
se = model.spec(spec).view(n_looks, L, -1).mean(1)
sfeat = torch.cat([e, se], 1)
return {name: model.struct_heads[name](sfeat) for name, _ in STRUCT_TASKS}
def train_multilook(train, val, *, device, steps=4500, width=96, det_batch=256,
n_looks=32, look_sizes=(1, 2, 4, 8), lr=1e-3, run_dir="runs/mtl_B",
log_every=250, seed=2, verbose=True) -> dict:
"""Joint multi-task with MULTI-LOOK structure heads (random L per step)."""
os.makedirs(run_dir, exist_ok=True)
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
model = MultiTaskUniversalEve(width=width).to(device)
log_sigma = torch.nn.Parameter(torch.zeros(len(TASKS), device=device))
bce, ce = nn.BCEWithLogitsLoss(), nn.CrossEntropyLoss()
opt = torch.optim.AdamW(list(model.parameters()) + [log_sigma], lr=lr, weight_decay=1e-4)
cells = _h1_by_cell(train)
keys = np.array(list(cells))
n = train["n"]
t0 = time.perf_counter()
for it in range(steps):
for g in opt.param_groups:
g["lr"] = lr * _lr_factor(it / max(1, steps))
L = int(rng.choice(look_sizes))
idxd = torch.from_numpy(rng.choice(n, det_batch, replace=False))
xd, spd, maskd, specd, labd = _sample_batch(train, idxd, device)
lidx = _sample_look_idx(cells, keys, n_looks, L, rng)
xs, sps, masks, specs = _look_feats(train, lidx)
xs, sps, masks, specs = xs.to(device), sps.to(device), masks.to(device), specs.to(device)
rep = lidx.view(n_looks, L)[:, 0]
slab = {name: train[name][rep].to(device) for name, _ in STRUCT_TASKS}
model.train()
det_logit = model.det_head(model.embed(xd, spd, maskd)).squeeze(-1)
slog = _pool_struct(model, xs, sps, masks, specs, n_looks, L)
raw = {"det": bce(det_logit, labd["det"])}
for name, _ in STRUCT_TASKS:
raw[name] = ce(slog[name], slab[name])
total = sum(torch.exp(-log_sigma[i]) * raw[t] + 0.5 * log_sigma[i] for i, t in enumerate(TASKS))
opt.zero_grad(); total.backward()
torch.nn.utils.clip_grad_norm_(list(model.parameters()) + [log_sigma], 1.0); opt.step()
if verbose and (it % log_every == 0 or it == steps - 1):
print(f" [B it={it:5d} L={L}] loss={float(total.detach()):.3f} "
f"det={raw['det']:.3f} format={raw['format']:.3f} chan={raw['chan']:.3f} M={raw['M']:.3f}"
f" {(it+1)/(time.perf_counter()-t0):.1f} it/s", flush=True)
torch.save({"model": model.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
sweep = {int(L): evaluate_multilook(model, val, device, int(L)) for L in look_sizes}
if verbose:
fmt = {L: sweep[L]["structure_acc"]["format"]["overall"] for L in sweep}
print(f" [B] val format-acc vs L: {fmt}", flush=True)
return {"model": model, "L_sweep_val": sweep, "wall_s": round(time.perf_counter() - t0, 1)}
@torch.no_grad()
def evaluate_multilook(model, arr, device, L, *, batch_looks=256) -> dict:
"""Partition each cell's H1 blocks into looks of L, pool, predict structure.
Per-attribute accuracy overall / per regime, and format accuracy per arm."""
model.eval()
cells = _h1_by_cell(arr)
rows, labs = [], {name: [] for name, _ in STRUCT_TASKS}
reg, armv = [], []
for pool in cells.values():
m = len(pool) // L
if m == 0:
continue
for row in pool[:m * L].reshape(m, L):
rows.append(row)
for name, _ in STRUCT_TASKS:
labs[name].append(int(arr[name][row[0]]))
reg.append(arr["regime"][row[0]])
armv.append(arr["arm_str"][row[0]])
if not rows:
return {"L": L, "n_looks": 0, "structure_acc": {}}
look_idx = np.stack(rows) # (Nl, L)
Nl = look_idx.shape[0]
preds = {name: np.empty(Nl, np.int64) for name, _ in STRUCT_TASKS}
for lo in range(0, Nl, batch_looks):
hi = min(lo + batch_looks, Nl)
flat = torch.from_numpy(look_idx[lo:hi].reshape(-1))
x, sp, mask, spec = _look_feats(arr, flat)
x, sp, mask, spec = x.to(device), sp.to(device), mask.to(device), spec.to(device)
slog = _pool_struct(model, x, sp, mask, spec, hi - lo, L)
for name, _ in STRUCT_TASKS:
preds[name][lo:hi] = slog[name].argmax(1).cpu().numpy()
reg, armv = np.array(reg), np.array(armv)
res = {"L": L, "n_looks": int(Nl), "structure_acc": {}, "format_acc_by_arm": {}}
for name, _ in STRUCT_TASKS:
lab = np.array(labs[name])
acc = {"overall": round(float((preds[name] == lab).mean()), 4)}
for rg in REGIMES:
mm = reg == rg
if mm.sum():
acc[rg] = round(float((preds[name][mm] == lab[mm]).mean()), 4)
res["structure_acc"][name] = acc
flab = np.array(labs["format"])
for arm in ARM_VOCAB:
mm = armv == arm
if mm.sum():
res["format_acc_by_arm"][arm] = round(float((preds["format"][mm] == flab[mm]).mean()), 4)
return res
# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def main(argv=None) -> int:
ap = argparse.ArgumentParser(prog="covcollab-eve-mtl",
description="Train + evaluate the multi-task Universal Eve (detect + fingerprint).")
ap.add_argument("--data", default="huggingface/covcollab-eve-detection")
ap.add_argument("--regime", choices=("A", "C", "B", "both"), default="both",
help="A=joint, C=det-rep probe, B=multi-look (lift the fingerprint frontier)")
ap.add_argument("--steps", type=int, default=4000)
ap.add_argument("--probe-steps", type=int, default=2500)
ap.add_argument("--look-sizes", type=int, nargs="*", default=[1, 2, 4, 8], help="regime B L-sweep")
ap.add_argument("--n-looks", type=int, default=32, help="regime B looks per step")
ap.add_argument("--width", type=int, default=96)
ap.add_argument("--batch", type=int, default=256)
ap.add_argument("--max-train", type=int, default=None, help="subsample train (default: all)")
ap.add_argument("--device", default="auto")
ap.add_argument("--feat-device", default="auto",
help="where per-batch feature extraction runs: 'auto'=net device on CUDA "
"(complex64 FFT+eigvalsh on-GPU), else CPU (MPS lacks complex); or cpu/cuda")
ap.add_argument("--out", default="runs/mtl")
ap.add_argument("--eval-splits", nargs="*", default=["test_iid", "test_ood"])
ap.add_argument("--smoke", action="store_true")
args = ap.parse_args(argv)
if args.smoke:
args.steps, args.probe_steps, args.max_train, args.width = 60, 40, 1500, 48
dev = pick_device(args.device)
global _FEAT_DEVICE
if args.feat_device == "auto":
_FEAT_DEVICE = "cuda" if dev == "cuda" else None # CUDA-only; MPS/CPU keep CPU features
elif args.feat_device in ("cpu", "none"):
_FEAT_DEVICE = None
else:
_FEAT_DEVICE = args.feat_device
os.makedirs(args.out, exist_ok=True)
print(f"device={dev} feat_device={_FEAT_DEVICE or 'cpu'} data={args.data} regime={args.regime} "
f"steps={args.steps} width={args.width} max_train={args.max_train}", flush=True)
train = load_arrays(args.data, "train", max_n=args.max_train)
val = load_arrays(args.data, "val")
print(f"loaded train n={train['n']} val n={val['n']}", flush=True)
results = {"config": {"regime": args.regime, "steps": args.steps, "width": args.width,
"batch": args.batch, "max_train": args.max_train, "device": dev}}
tests = {sp: load_arrays(args.data, sp) for sp in args.eval_splits}
if args.regime in ("A", "both"):
r = train_joint(train, val, device=dev, steps=args.steps, width=args.width,
batch=args.batch, run_dir=os.path.join(args.out, "A"))
results["A"] = {"val": r["val"], "wall_s": r["wall_s"],
"test": {sp: evaluate(r["model"], tests[sp], dev) for sp in tests}}
if args.regime in ("C", "both"):
r = train_detonly_then_probe(train, val, device=dev, det_steps=args.steps,
probe_steps=args.probe_steps, width=args.width,
batch=args.batch, run_dir=os.path.join(args.out, "C"))
results["C"] = {"val": r["val"], "wall_s": r["wall_s"],
"test": {sp: evaluate(r["model"], tests[sp], dev, probes=r["probes"]) for sp in tests}}
if args.regime == "B":
ls = tuple(args.look_sizes)
r = train_multilook(train, val, device=dev, steps=args.steps, width=args.width,
det_batch=args.batch, n_looks=args.n_looks, look_sizes=ls,
run_dir=os.path.join(args.out, "B"))
results["B"] = {"wall_s": r["wall_s"], "look_sizes": list(ls),
"L_sweep": {sp: {int(L): evaluate_multilook(r["model"], tests[sp], dev, int(L))
for L in ls} for sp in tests}}
with open(os.path.join(args.out, "results.json"), "w") as f:
json.dump(results, f, indent=2)
print(f"\nresults -> {args.out}/results.json", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())