ashen-navigator commited on
Commit
b295f1c
·
verified ·
1 Parent(s): 3dd73f2

Add Universal-Eve trainer (covcollab-eve-mtl) + TRAINING.md with NVIDIA/A100 guide

Browse files
README.md CHANGED
@@ -172,6 +172,31 @@ x = features_from_Y(d["Y"][:64]) # model input [Re, Im, |Y|^2] -> (64, 4,
172
  The model input `x = [Re(Y), Im(Y), |Y|²]` is a deterministic function of `Y` (a per-minibatch
173
  energy scale), so features are **not** stored — recompute them with `features_from_Y`.
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  ## Schema
176
 
177
  Every sample carries `y_real`, `y_imag`, `label`, and a rich metadata row: `split`, `format`,
@@ -182,12 +207,14 @@ Every sample carries `y_real`, `y_imag`, `label`, and a rich metadata row: `spli
182
 
183
  ## Bundled source (self-contained code + data)
184
 
185
- This repo ships a **minimal generator subset** of the `covcollab` package under
186
- [`src/covcollab/`](src/covcollab) — only the **29 modules** the build / verify / load path actually
187
- imports (the exact transitive closure; the wider research pipeline — policy-design CLIs, learned-Eve
188
- zoo, GA, evaluators, trainers — is dropped). See [`src/SUBSET_NOTES.md`](src/SUBSET_NOTES.md). The
189
- snapshot corresponds to the git SHA in `manifest.json`, so the dataset can be **regenerated,
190
- verified, and extended from the repo itself**, with no external checkout:
 
 
191
 
192
  ```bash
193
  pip install ".[hf]" # installs numpy + torch + pyarrow
 
172
  The model input `x = [Re(Y), Im(Y), |Y|²]` is a deterministic function of `Y` (a per-minibatch
173
  energy scale), so features are **not** stored — recompute them with `features_from_Y`.
174
 
175
+ ## Training the Universal Eve warden
176
+
177
+ The repo also ships the **trainer that consumes this dataset** — a multi-task warden that jointly
178
+ detects (H0/H1) and fingerprints (format, `M`, `K`, `d`, channel, policy-arm) — as
179
+ `covcollab-eve-mtl`
180
+ ([`src/covcollab/universaleve/multitask.py`](src/covcollab/universaleve/multitask.py)):
181
+
182
+ ```bash
183
+ pip install -e ".[hf]" # numpy + torch + pyarrow
184
+ covcollab-eve-mtl --data . --regime both --out runs/mtl # auto-selects cuda>mps>cpu
185
+ ```
186
+
187
+ On an NVIDIA GPU, put the **whole step** (network *and* the complex FFT / covariance-eigenvalue
188
+ feature extraction) on the card in `complex64`:
189
+
190
+ ```bash
191
+ covcollab-eve-mtl --data . --regime both --device cuda --feat-device auto \
192
+ --width 96 --batch 512 --steps 6000 --out runs/mtl_a100
193
+ ```
194
+
195
+ **See [`TRAINING.md`](TRAINING.md)** for the full guide: the model, every CLI flag, the three
196
+ training regimes (joint / detection-probe / multi-look), reproducing the fingerprinting map, and a
197
+ detailed section on **training on A100s and other NVIDIA GPUs** (CUDA install, per-GPU batch/width
198
+ settings, memory, multi-GPU, and expected wall-clock).
199
+
200
  ## Schema
201
 
202
  Every sample carries `y_real`, `y_imag`, `label`, and a rich metadata row: `split`, `format`,
 
207
 
208
  ## Bundled source (self-contained code + data)
209
 
210
+ This repo ships a **self-contained subset** of the `covcollab` package under
211
+ [`src/covcollab/`](src/covcollab) — the build / verify / load transitive closure **plus** the
212
+ Universal-Eve trainer (`universaleve/multitask.py` and a trimmed, NumPy-only `design/audit.py`);
213
+ the wider research pipeline (policy-design CLIs, learned-Eve zoo, GA, evaluators, the on-the-fly
214
+ streaming trainer) is dropped. See [`src/SUBSET_NOTES.md`](src/SUBSET_NOTES.md) and
215
+ [`TRAINING.md`](TRAINING.md). The snapshot corresponds to the git SHA in `manifest.json`, so the
216
+ dataset can be **regenerated, verified, trained on, and extended from the repo itself**, with no
217
+ external checkout:
218
 
219
  ```bash
220
  pip install ".[hf]" # installs numpy + torch + pyarrow
TRAINING.md ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training the Universal Eve warden
2
+
3
+ This dataset ships with the trainer that consumes it: **Universal Eve**, a multi-task warden
4
+ that, from a single `N_E × T` block of Eve's received signal, jointly (a) **detects** whether
5
+ a covert distributed virtual-MIMO collaboration is present (H0 vs H1) and (b) **fingerprints**
6
+ its structure — waveform format, system size `M`, message shape `(K, d)`, channel family, and
7
+ the collaboration-policy arm. The script is
8
+ [`src/covcollab/universaleve/multitask.py`](src/covcollab/universaleve/multitask.py),
9
+ exposed as the `covcollab-eve-mtl` command.
10
+
11
+ The scientific point of the model is the **presence ≠ structure** dichotomy: detection is
12
+ recoverable (regime-flat AUC ≈ 0.88), waveform/channel partially recover and lift with more
13
+ antennas/looks, but system size and policy identity stay at chance on the payload. Training it
14
+ reproduces that map.
15
+
16
+ ---
17
+
18
+ ## What it trains on
19
+
20
+ The trainer reads the dataset splits directly (no re-generation):
21
+
22
+ | split | role |
23
+ |---|---|
24
+ | `train` | fit the backbone + heads |
25
+ | `val` (`validation`) | monitoring |
26
+ | `test_iid` | in-distribution evaluation |
27
+ | `test_ood` | held-out strong-Doppler shift |
28
+
29
+ Two configs are available and interchangeable via `--data`:
30
+
31
+ - **`default`** — `N_E = 4` receive antennas (the main config).
32
+ - **`multi_ne`** — `N_E ∈ {1,2,4,8}` swept, zero-padded to `N_E^max = 8` with a validity mask;
33
+ use it to study the antenna-count frontier.
34
+
35
+ Each sample is a complex `(N_E, T=320)` block plus a 26-field metadata row (detection label,
36
+ `format`, `n_tx=M`, `n_msg_users=K`, `msg_dim=d`, `channel_family`, `policy_arm`, per-sample Eve
37
+ and Bob SNRs, a `regime` tag ∈ {covert, comparable, detectable}, and a `cell_id` for
38
+ same-emitter multi-look grouping).
39
+
40
+ ## The model
41
+
42
+ One shared encoder feeds all tasks (≈ 2.1 × 10⁵ parameters):
43
+
44
+ ```
45
+ per-antenna multi-scale Conv1d → state-space long-conv temporal block
46
+ → masked attention+mean antenna pool (variable N_E)
47
+ → concat a 7-dim spatial-covariance eigen-branch (non-sphericity, log-MME,
48
+ log-energy, top eigenvalue ratios) ⇒ embedding e
49
+ a spectral/pilot branch (log-PSD + cyclic-autocorrelation) ⇒ spec_emb
50
+ heads: detection (BCE, off e, all samples)
51
+ format / M / K / d / channel / policy-arm (CE, off [e, spec_emb], H1 only)
52
+ loss: masked, uncertainty-weighted (homoscedastic Kendall–Gal) multi-task loss
53
+ ```
54
+
55
+ Optimizer: AdamW (`wd=1e-4`) + warmup/cosine LR + grad clipping — the combination that keeps
56
+ the deep-covert run from the weight-collapse failure mode of plain Adam with large L2.
57
+
58
+ ---
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ # from the dataset repo root
64
+ pip install -e ".[hf]" # installs numpy, torch, pyarrow (parquet)
65
+ ```
66
+
67
+ `torch` from PyPI is the CPU/Apple-MPS build. For NVIDIA GPUs install a CUDA build first (see
68
+ the GPU section), then `pip install -e ".[hf]"` will keep it.
69
+
70
+ ## Quickstart
71
+
72
+ ```bash
73
+ # joint detect+fingerprint (regime A) + a detection-representation probe (regime C),
74
+ # evaluated on test_iid and test_ood; auto-selects CUDA > MPS > CPU
75
+ covcollab-eve-mtl --data . --regime both --out runs/mtl
76
+ ```
77
+
78
+ A fast end-to-end sanity run (tiny, ~1–2 min including the parquet load):
79
+
80
+ ```bash
81
+ covcollab-eve-mtl --data . --smoke --regime A --out runs/mtl_smoke
82
+ ```
83
+
84
+ Outputs land in `--out`: a per-regime `A/ckpt.pt`, `C/ckpt.pt`, … and a `results.json` with
85
+ per-split detection AUC and per-attribute accuracy (each scored against its majority-class
86
+ baseline — only lift above it is genuine recovery).
87
+
88
+ ## CLI
89
+
90
+ | flag | default | meaning |
91
+ |---|---|---|
92
+ | `--data` | `huggingface/covcollab-eve-detection` | dataset dir (`.` from this repo), or a HF path |
93
+ | `--regime` | `both` | `A` joint · `C` detection-rep probe · `B` multi-look sweep · `both` (A+C) |
94
+ | `--steps` | `4000` | training steps (per regime) |
95
+ | `--probe-steps` | `2500` | regime-C probe steps |
96
+ | `--width` | `96` | backbone width |
97
+ | `--batch` | `256` | minibatch size |
98
+ | `--look-sizes` | `1 2 4 8` | regime-B: L values in the multi-look sweep |
99
+ | `--n-looks` | `32` | regime-B: looks pooled per step |
100
+ | `--max-train` | all | subsample the train split (fit smaller machines / faster) |
101
+ | `--device` | `auto` | `auto` (cuda>mps>cpu), or `cuda` / `mps` / `cpu` |
102
+ | `--feat-device` | `auto` | where feature extraction runs (see GPU section) |
103
+ | `--eval-splits` | `test_iid test_ood` | splits to evaluate |
104
+ | `--out` | `runs/mtl` | output dir |
105
+ | `--smoke` | off | tiny config for a quick end-to-end check |
106
+
107
+ **Regimes.** `A` trains the joint multi-task model. `C` trains detection only, then fits MLP
108
+ probes on the *frozen* detection embedding — the A-vs-C gap shows whether structure lives in
109
+ the detector's representation (it does not) or only in the spectral branch. `B` sweeps temporal
110
+ looks `L` to lift the fingerprint frontier (format rises ∝ √L; policy stays flat).
111
+
112
+ ---
113
+
114
+ ## Training on NVIDIA GPUs (A100 and others)
115
+
116
+ Unlike the on-the-fly adversarial warden (which *synthesizes* signals every step and is
117
+ data-generation-bound), this trainer reads **pre-generated** blocks, so a GPU accelerates the
118
+ actual work with no synthesis overhead. Two device knobs matter.
119
+
120
+ ### 1. Install a CUDA build of PyTorch
121
+
122
+ The single most common mistake is training on a CPU `torch` wheel. Install the CUDA build that
123
+ matches your driver (CUDA 12.1 shown):
124
+
125
+ ```bash
126
+ pip install torch --index-url https://download.pytorch.org/whl/cu121
127
+ python -c "import torch; print(torch.__version__, torch.cuda.is_available(), torch.cuda.get_device_name(0))"
128
+ pip install -e ".[hf]" # add numpy + pyarrow without touching torch
129
+ ```
130
+
131
+ ### 2. Put the whole step on the GPU: `--device cuda --feat-device auto`
132
+
133
+ - `--device cuda` runs the network (forward/backward) on the GPU.
134
+ - `--feat-device auto` runs the **feature extraction** — the complex-valued FFT (spectral
135
+ branch) and the spatial-covariance `eigvalsh` (eigen-branch) — on the GPU too, in
136
+ `complex64`. This is CUDA-only: Apple MPS has no complex-tensor support, so on MPS/CPU
137
+ features stay on CPU automatically (`auto` resolves to CPU there). Force it with
138
+ `--feat-device cuda` / `cpu` if needed.
139
+
140
+ With both on CUDA, the only host-side cost is loading the parquet split into memory once.
141
+
142
+ ```bash
143
+ covcollab-eve-mtl --data . --regime both \
144
+ --device cuda --feat-device auto \
145
+ --width 96 --batch 512 --steps 6000 --out runs/mtl_a100
146
+ ```
147
+
148
+ ### Recommended settings by GPU
149
+
150
+ The backbone is small (~0.2 M params), so training is fast and fits comfortably on any modern
151
+ NVIDIA card; larger GPUs mainly let you scale `--width`/`--batch` and run more steps.
152
+
153
+ | GPU | `--batch` | `--width` | notes |
154
+ |---|---|---|---|
155
+ | A100 40/80 GB, H100 | `512–1024` | `96–192` | ample headroom; whole step on-GPU; `--steps 6000+` |
156
+ | L40S / A6000 (48 GB) | `512` | `96–128` | same profile as A100 at smaller width |
157
+ | RTX 4090 / 3090 (24 GB) | `256–512` | `96` | keep the default config |
158
+ | T4 / RTX 2080 (≤16 GB) | `128–256` | `64–96` | `--max-train 40000` if host RAM is tight |
159
+
160
+ The full `train` split is ~1 GB in host memory; feature tensors are built per-batch, so VRAM
161
+ use is modest even at `--width 192`. If host RAM is the constraint, `--max-train N` subsamples
162
+ the split.
163
+
164
+ ### Throughput and expectations
165
+
166
+ The network is tiny relative to an A100, so a run is dominated by the one-time data load, not
167
+ compute: the default 4000-step regime-A fit completes in a few minutes on an A100, and the full
168
+ `--regime both` in well under ~15 minutes. (For reference, the same run takes ~1–2 hours on an
169
+ Apple-MPS laptop, most of it CPU feature extraction — which `--feat-device auto` removes on
170
+ CUDA.) A single A100 is more than enough; there is no need for multi-GPU.
171
+
172
+ ### Using multiple GPUs
173
+
174
+ The trainer is single-GPU by design. To use several A100s productively, run independent jobs
175
+ in parallel — one device each — rather than sharding one small model:
176
+
177
+ ```bash
178
+ # regimes in parallel, one GPU each
179
+ CUDA_VISIBLE_DEVICES=0 covcollab-eve-mtl --data . --regime A --device cuda --out runs/A &
180
+ CUDA_VISIBLE_DEVICES=1 covcollab-eve-mtl --data . --regime C --device cuda --out runs/C &
181
+ CUDA_VISIBLE_DEVICES=2 covcollab-eve-mtl --data . --regime B --device cuda --out runs/B &
182
+ wait
183
+ ```
184
+
185
+ or sweep seeds / `--width` / the `multi_ne` config across cards the same way.
186
+
187
+ ### Sanity gates before a long or metered run
188
+
189
+ - Always dry-run `--smoke` on the target machine first; it exercises the full load → train →
190
+ evaluate path in ~1–2 min.
191
+ - The AdamW + LR-schedule recipe here is the one that avoids the deep-covert weight-collapse
192
+ seen with plain Adam + large weight decay; if you change the optimizer, verify the training
193
+ loss decreases and the detection AUC on `val` is non-degenerate (≠ 0.5) on a short run before
194
+ committing GPU time.
195
+
196
+ ---
197
+
198
+ ## The synthesis-based warden (optional, different tool)
199
+
200
+ If instead of training on this fixed dataset you want the **on-the-fly, distributionally-robust**
201
+ warden that synthesizes fresh domains every step (randomizing policy/waveform/channel/SNR/`N_E`),
202
+ that is a separate entry point in the full research package
203
+ (`covcollab.universaleve.run.train_and_eval`, with a Modal/Colab cloud path). It is
204
+ generation-bound rather than compute-bound, so its GPU story centers on running the *complex
205
+ simulator* on CUDA (`sim_device="cuda"`), not just the net. This dataset and `covcollab-eve-mtl`
206
+ do not require it.
207
+
208
+ ---
209
+
210
+ ## Reproducing the fingerprinting map
211
+
212
+ ```bash
213
+ covcollab-eve-mtl --data . --regime both --steps 4000 --width 96 --out runs/map
214
+ ```
215
+
216
+ Read `runs/map/results.json`: detection AUC is high and regime-flat; **format** (+0.14) and
217
+ **channel** (+0.11) clear their baselines in the joint model (A) but not from the frozen
218
+ detection probe (C); **M**, **K**, **d**, and **policy-arm** sit at their class priors — the
219
+ central null. Add `--regime B` to see format lift with looks while the policy-arm stays flat.
UPLOAD.md CHANGED
@@ -1,9 +1,12 @@
1
  # Uploading to the Hugging Face Hub
2
 
3
  This folder is a self-contained, upload-ready HF dataset repo: `README.md` (dataset card with
4
- YAML front-matter), `data/*.parquet` (the four splits), `manifest.json` (provenance), a standalone
5
- loader, the generation notebook, and a **minimal snapshot of the generator source** (`src/covcollab/` —
6
- 29 modules + a trimmed `pyproject.toml`) so the repo is a complete code + data bundle.
 
 
 
7
 
8
  > If you are uploading from a fresh checkout, first materialize the two regenerable pieces:
9
  > `covcollab-eve-controlled --out .` (builds `data/*.parquet`) and
 
1
  # Uploading to the Hugging Face Hub
2
 
3
  This folder is a self-contained, upload-ready HF dataset repo: `README.md` (dataset card with
4
+ YAML front-matter), `TRAINING.md` (the Universal-Eve training guide, incl. NVIDIA/A100),
5
+ `data/*.parquet` (the four splits), `manifest.json` (provenance), a standalone loader, the
6
+ generation notebook, and a **snapshot of the dataset source** (`src/covcollab/` the
7
+ build/verify/load closure **plus the `covcollab-eve-mtl` trainer** — + a trimmed
8
+ `pyproject.toml`) so the repo is a complete code + data bundle you can regenerate, verify, and
9
+ train on with no external checkout.
10
 
11
  > If you are uploading from a fresh checkout, first materialize the two regenerable pieces:
12
  > `covcollab-eve-controlled --out .` (builds `data/*.parquet`) and
pyproject.toml CHANGED
@@ -14,6 +14,7 @@ viz = ["matplotlib>=3.8"] # only for the generation notebook's plots
14
 
15
  [project.scripts]
16
  covcollab-eve-controlled = "covcollab.universaleve.controlled:main"
 
17
 
18
  [tool.hatch.build.targets.wheel]
19
  packages = ["src/covcollab"]
 
14
 
15
  [project.scripts]
16
  covcollab-eve-controlled = "covcollab.universaleve.controlled:main"
17
+ covcollab-eve-mtl = "covcollab.universaleve.multitask:main" # train + evaluate the Universal Eve
18
 
19
  [tool.hatch.build.targets.wheel]
20
  packages = ["src/covcollab"]
src/SUBSET_NOTES.md CHANGED
@@ -1,15 +1,18 @@
1
- # covcollab -- generator subset
2
 
3
- This is a **minimal subset** of the `covcollab` research package: only the 29 modules the
4
- covert-collaboration Eve-detection dataset generator imports (traced as the exact transitive
5
- closure of build / verify / load). Dropped: the policy-design CLIs, learned-Eve architecture
6
- zoo, GA subset-selection, OOD evaluators, trainers, `materialize`, and the coordination model.
 
 
7
 
8
  Install and use it standalone:
9
 
10
  ```bash
11
- pip install . # or: pip install ".[hf]" for parquet
12
- covcollab-eve-controlled --verify --out .. # regenerate + assert bit-identity
 
13
  ```
14
 
15
  Verified with Python 3.14 / numpy 2.5.1 / torch 2.13.0 (exact versions recorded in
 
1
+ # covcollab -- dataset subset
2
 
3
+ This is a **self-contained subset** of the `covcollab` research package: the 30 modules that
4
+ are the exact build / verify / load transitive closure of the covert-collaboration
5
+ Eve-detection dataset, **plus the Universal-Eve trainer** (`universaleve/multitask.py`,
6
+ `covcollab-eve-mtl`). Dropped: the policy-design CLIs, learned-Eve architecture zoo, GA
7
+ subset-selection, OOD evaluators, the on-the-fly streaming trainer, `materialize`, and the
8
+ coordination model.
9
 
10
  Install and use it standalone:
11
 
12
  ```bash
13
+ pip install ".[hf]" # numpy + torch + pyarrow
14
+ covcollab-eve-controlled --verify --out .. # regenerate + assert bit-identity
15
+ covcollab-eve-mtl --data .. --regime both # train the warden (see ../TRAINING.md)
16
  ```
17
 
18
  Verified with Python 3.14 / numpy 2.5.1 / torch 2.13.0 (exact versions recorded in
src/covcollab/__init__.py CHANGED
@@ -1,7 +1,8 @@
1
- """covcollab -- GENERATOR SUBSET.
2
 
3
- A trimmed copy of the covert-collaboration package: only the modules needed to
4
- build / verify / load the Eve-detection dataset. The full research pipeline
5
- (policy-design CLIs, learned-Eve zoo, GA, evaluators, trainers) is not here.
6
- Submodules use explicit imports, so this package init is intentionally empty.
 
7
  """
 
1
+ """covcollab -- DATASET SUBSET.
2
 
3
+ A trimmed copy of the covert-collaboration package: the modules needed to build /
4
+ verify / load the Eve-detection dataset, plus the Universal-Eve trainer
5
+ (universaleve/multitask.py, `covcollab-eve-mtl`). The wider research pipeline
6
+ (policy-design CLIs, learned-Eve zoo, GA, evaluators, streaming trainer) is not
7
+ here. Submodules use explicit imports, so this package init is intentionally empty.
8
  """
src/covcollab/universaleve/__init__.py CHANGED
@@ -1,3 +1,4 @@
1
- """covcollab.universaleve (generator subset): controlled / dataset / domains /
2
- samplers / model / impairments / device / contracts.
 
3
  """
 
1
+ """covcollab.universaleve (dataset subset): controlled / dataset / domains /
2
+ samplers / model / impairments / device / contracts, plus multitask
3
+ (the Universal-Eve trainer, `covcollab-eve-mtl`).
4
  """
src/covcollab/universaleve/controlled.py CHANGED
@@ -229,7 +229,9 @@ class _SplitWriter:
229
  self._cur_path = os.path.join(self.data_dir, fname)
230
  self.writer = pq.ParquetWriter(self._cur_path, self.schema, compression="zstd")
231
  self.rows_in_shard = 0
232
- self.files.append({"file": os.path.join("data", fname), "split": self.split, "rows": 0})
 
 
233
 
234
  def add(self, cols: dict):
235
  self.buf.append(cols)
@@ -608,10 +610,11 @@ def verify(out_dir: str, *, sim_device="cpu", verbose=True) -> dict:
608
  # -------------------------------------------------------------------------
609
  # bundle the (minimal) package source into the artifact
610
  # -------------------------------------------------------------------------
611
- # The exact modules the build / verify / load path imports (transitive closure,
612
- # verified by tracing sys.modules). Everything else in covcollab (policy-design
613
- # CLIs, learned-Eve zoo, GA, evaluators, trainers, materialize, coordination) is
614
- # NOT needed to generate this dataset and is dropped.
 
615
  GEN_MODULES: tuple[str, ...] = (
616
  "__init__.py", "config.py", "channel.py", "constellations.py", "pilots.py",
617
  "affine.py", "policy.py",
@@ -622,6 +625,7 @@ GEN_MODULES: tuple[str, ...] = (
622
  "universaleve/__init__.py", "universaleve/controlled.py", "universaleve/dataset.py",
623
  "universaleve/domains.py", "universaleve/samplers.py", "universaleve/model.py",
624
  "universaleve/impairments.py", "universaleve/device.py", "universaleve/contracts.py",
 
625
  )
626
  # __init__ files replaced by an empty stub: the generation modules use only explicit
627
  # submodule imports, so these package inits (which re-export the research pipeline)
@@ -629,14 +633,16 @@ GEN_MODULES: tuple[str, ...] = (
629
  # because it genuinely defines build/FORMAT_IDS.)
630
  _TRIMMED_INITS = {"__init__.py", "design/__init__.py", "universaleve/__init__.py"}
631
  _INIT_STUB = {
632
- "__init__.py": ('"""covcollab -- GENERATOR SUBSET.\n\nA trimmed copy of the covert-collaboration package: only the modules needed to\n'
633
- "build / verify / load the Eve-detection dataset. The full research pipeline\n"
634
- "(policy-design CLIs, learned-Eve zoo, GA, evaluators, trainers) is not here.\n"
635
- 'Submodules use explicit imports, so this package init is intentionally empty.\n"""\n'),
 
636
  "design/__init__.py": ('"""covcollab.design (generator subset): psgd / waveform / utility / surrogates /\n'
637
  'architectures -- the design pieces the dataset generator needs.\n"""\n'),
638
- "universaleve/__init__.py": ('"""covcollab.universaleve (generator subset): controlled / dataset / domains /\n'
639
- 'samplers / model / impairments / device / contracts.\n"""\n'),
 
640
  }
641
 
642
  _MIN_PYPROJECT = """\
@@ -656,6 +662,7 @@ viz = ["matplotlib>=3.8"] # only for the generation notebook's plots
656
 
657
  [project.scripts]
658
  covcollab-eve-controlled = "covcollab.universaleve.controlled:main"
 
659
 
660
  [tool.hatch.build.targets.wheel]
661
  packages = ["src/covcollab"]
@@ -666,18 +673,21 @@ build-backend = "hatchling.build"
666
  """
667
 
668
  _SUBSET_NOTE = """\
669
- # covcollab -- generator subset
670
 
671
- This is a **minimal subset** of the `covcollab` research package: only the {n} modules the
672
- covert-collaboration Eve-detection dataset generator imports (traced as the exact transitive
673
- closure of build / verify / load). Dropped: the policy-design CLIs, learned-Eve architecture
674
- zoo, GA subset-selection, OOD evaluators, trainers, `materialize`, and the coordination model.
 
 
675
 
676
  Install and use it standalone:
677
 
678
  ```bash
679
- pip install . # or: pip install ".[hf]" for parquet
680
- covcollab-eve-controlled --verify --out .. # regenerate + assert bit-identity
 
681
  ```
682
 
683
  Verified with Python 3.14 / numpy 2.5.1 / torch 2.13.0 (exact versions recorded in
@@ -737,13 +747,17 @@ def bundle_source(out_dir: str, *, minimal: bool = True, verbose: bool = True) -
737
  # -------------------------------------------------------------------------
738
  # loader helpers
739
  # -------------------------------------------------------------------------
740
- def load_split(out_dir: str, split: str) -> dict:
741
  """Load one split's parquet shards into a dict of numpy arrays.
742
 
743
- Returns ``Y`` (n, R, T) complex64 plus every metadata column. Requires pyarrow.
 
 
 
 
744
  """
745
  import pyarrow.parquet as pq
746
- with open(os.path.join(out_dir, "manifest.json")) as f:
747
  man = json.load(f)
748
  files = [os.path.join(out_dir, r["file"]) for r in man["files"] if r["split"] == split]
749
  if not files:
@@ -751,9 +765,12 @@ def load_split(out_dir: str, split: str) -> dict:
751
  tbl = pq.ParquetDataset(files).read()
752
  d = tbl.to_pydict()
753
  n = len(d["label"])
754
- r = int(d["n_rx_eve"][0]); t = int(d["n_samples_t"][0])
755
- yr = np.asarray(d.pop("y_real"), dtype=np.float32).reshape(n, r, t)
756
- yi = np.asarray(d.pop("y_imag"), dtype=np.float32).reshape(n, r, t)
 
 
 
757
  out = {"Y": (yr + 1j * yi).astype(np.complex64)}
758
  for k, v in d.items():
759
  out[k] = np.asarray(v)
 
229
  self._cur_path = os.path.join(self.data_dir, fname)
230
  self.writer = pq.ParquetWriter(self._cur_path, self.schema, compression="zstd")
231
  self.rows_in_shard = 0
232
+ # record path relative to the artifact root (data/ default, data_multi_ne/ for the multi_ne config)
233
+ self.files.append({"file": os.path.join(os.path.basename(self.data_dir), fname),
234
+ "split": self.split, "rows": 0})
235
 
236
  def add(self, cols: dict):
237
  self.buf.append(cols)
 
610
  # -------------------------------------------------------------------------
611
  # bundle the (minimal) package source into the artifact
612
  # -------------------------------------------------------------------------
613
+ # The build / verify / load transitive closure (verified by tracing sys.modules) PLUS the
614
+ # Universal-Eve trainer (universaleve/multitask.py -- it consumes this dataset and carries a
615
+ # self-contained _auc, so it needs no other new module). Everything else in covcollab
616
+ # (policy-design CLIs, learned-Eve zoo, GA, evaluators, the on-the-fly streaming trainer,
617
+ # materialize, coordination) is NOT needed here and is dropped.
618
  GEN_MODULES: tuple[str, ...] = (
619
  "__init__.py", "config.py", "channel.py", "constellations.py", "pilots.py",
620
  "affine.py", "policy.py",
 
625
  "universaleve/__init__.py", "universaleve/controlled.py", "universaleve/dataset.py",
626
  "universaleve/domains.py", "universaleve/samplers.py", "universaleve/model.py",
627
  "universaleve/impairments.py", "universaleve/device.py", "universaleve/contracts.py",
628
+ "universaleve/multitask.py", # the trainer (covcollab-eve-mtl)
629
  )
630
  # __init__ files replaced by an empty stub: the generation modules use only explicit
631
  # submodule imports, so these package inits (which re-export the research pipeline)
 
633
  # because it genuinely defines build/FORMAT_IDS.)
634
  _TRIMMED_INITS = {"__init__.py", "design/__init__.py", "universaleve/__init__.py"}
635
  _INIT_STUB = {
636
+ "__init__.py": ('"""covcollab -- DATASET SUBSET.\n\nA trimmed copy of the covert-collaboration package: the modules needed to build /\n'
637
+ "verify / load the Eve-detection dataset, plus the Universal-Eve trainer\n"
638
+ "(universaleve/multitask.py, `covcollab-eve-mtl`). The wider research pipeline\n"
639
+ "(policy-design CLIs, learned-Eve zoo, GA, evaluators, streaming trainer) is not\n"
640
+ 'here. Submodules use explicit imports, so this package init is intentionally empty.\n"""\n'),
641
  "design/__init__.py": ('"""covcollab.design (generator subset): psgd / waveform / utility / surrogates /\n'
642
  'architectures -- the design pieces the dataset generator needs.\n"""\n'),
643
+ "universaleve/__init__.py": ('"""covcollab.universaleve (dataset subset): controlled / dataset / domains /\n'
644
+ 'samplers / model / impairments / device / contracts, plus multitask\n'
645
+ '(the Universal-Eve trainer, `covcollab-eve-mtl`).\n"""\n'),
646
  }
647
 
648
  _MIN_PYPROJECT = """\
 
662
 
663
  [project.scripts]
664
  covcollab-eve-controlled = "covcollab.universaleve.controlled:main"
665
+ covcollab-eve-mtl = "covcollab.universaleve.multitask:main" # train + evaluate the Universal Eve
666
 
667
  [tool.hatch.build.targets.wheel]
668
  packages = ["src/covcollab"]
 
673
  """
674
 
675
  _SUBSET_NOTE = """\
676
+ # covcollab -- dataset subset
677
 
678
+ This is a **self-contained subset** of the `covcollab` research package: the {n} modules that
679
+ are the exact build / verify / load transitive closure of the covert-collaboration
680
+ Eve-detection dataset, **plus the Universal-Eve trainer** (`universaleve/multitask.py`,
681
+ `covcollab-eve-mtl`). Dropped: the policy-design CLIs, learned-Eve architecture zoo, GA
682
+ subset-selection, OOD evaluators, the on-the-fly streaming trainer, `materialize`, and the
683
+ coordination model.
684
 
685
  Install and use it standalone:
686
 
687
  ```bash
688
+ pip install ".[hf]" # numpy + torch + pyarrow
689
+ covcollab-eve-controlled --verify --out .. # regenerate + assert bit-identity
690
+ covcollab-eve-mtl --data .. --regime both # train the warden (see ../TRAINING.md)
691
  ```
692
 
693
  Verified with Python 3.14 / numpy 2.5.1 / torch 2.13.0 (exact versions recorded in
 
747
  # -------------------------------------------------------------------------
748
  # loader helpers
749
  # -------------------------------------------------------------------------
750
+ def load_split(out_dir: str, split: str, *, manifest: str = "manifest.json") -> dict:
751
  """Load one split's parquet shards into a dict of numpy arrays.
752
 
753
+ Returns ``Y`` (n, R, T) complex64 plus every metadata column. ``R`` is the
754
+ STORED antenna count, derived from the fixed_size_list length (``rt // T``), so
755
+ this serves both the fixed-N_E default config and the padded ``multi_ne`` config
756
+ (where ``R`` is R_max=8 and ``n_rx_eve`` gives the valid antennas per row).
757
+ Pass ``manifest="manifest_multi_ne.json"`` for the multi_ne config. Requires pyarrow.
758
  """
759
  import pyarrow.parquet as pq
760
+ with open(os.path.join(out_dir, manifest)) as f:
761
  man = json.load(f)
762
  files = [os.path.join(out_dir, r["file"]) for r in man["files"] if r["split"] == split]
763
  if not files:
 
765
  tbl = pq.ParquetDataset(files).read()
766
  d = tbl.to_pydict()
767
  n = len(d["label"])
768
+ t = int(d["n_samples_t"][0])
769
+ yr = np.asarray(d.pop("y_real"), dtype=np.float32)
770
+ yi = np.asarray(d.pop("y_imag"), dtype=np.float32)
771
+ r = yr.shape[1] // t # stored R (padded R_max for multi_ne)
772
+ yr = yr.reshape(n, r, t)
773
+ yi = yi.reshape(n, r, t)
774
  out = {"Y": (yr + 1j * yi).astype(np.complex64)}
775
  for k, v in d.items():
776
  out[k] = np.asarray(v)
src/covcollab/universaleve/multitask.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-task Universal Eve: detect covert comms AND fingerprint the structure.
2
+
3
+ Motivation (architecture research): the covert-trained detector is a PRESENCE
4
+ detector that is BLIND to format/channel/M in the deep-covert regime -- the
5
+ structure information is genuinely buried (SNR walls). So a dual-capability warden
6
+ is really a detector + a *conditional* fingerprinter, and the headline is the
7
+ **structure-recovery frontier**: at what adversary advantage (regime / SNR) does
8
+ the warden graduate from "something is transmitting" to "it's OFDM, M=16, covert
9
+ policy on".
10
+
11
+ Model: the validated UniversalEve backbone (multi-scale Conv1d -> SSM -> masked
12
+ antenna pool + 7-dim spatial eigen-branch) produces a detection embedding ``e``; a
13
+ **spectral/pilot branch** (PSD + cyclic-autocorrelation, where format identity
14
+ lives) is concatenated for the structure heads. Heads: detection (BCE, all
15
+ samples) + format / M / K / d / channel / policy-arm (CE, H1 only), combined with a
16
+ **masked, uncertainty-weighted** (Kendall-Gal) multi-task loss so an unlearnable
17
+ format gradient in deep-covert doesn't inject negative transfer onto detection.
18
+
19
+ Regimes:
20
+ A joint multi-task from scratch.
21
+ C detection-only pretrain -> freeze backbone -> probe structure off the frozen
22
+ detection embedding (isolates the representational content; the probing
23
+ question with a proper head, stratified by regime).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import math
31
+ import os
32
+ import sys
33
+ import time
34
+
35
+ import numpy as np
36
+ import torch
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+
40
+ from ..formats import FORMAT_IDS
41
+ from .dataset import to_real_iq
42
+ from .device import pick_device
43
+ from .model import N_SPATIAL, AntennaEncoder, spatial_features
44
+
45
+
46
+ def _auc(score: np.ndarray, lab: np.ndarray) -> float:
47
+ """ROC-AUC via the Mann-Whitney statistic (ties counted at 1/2). Self-contained so the
48
+ trainer needs no part of the generation-only audit stack."""
49
+ s1, s0 = score[lab == 1], score[lab == 0]
50
+ return float(np.mean(s1[:, None] > s0[None, :]) + 0.5 * np.mean(s1[:, None] == s0[None, :]))
51
+
52
+ # --------------------------------------------------------------------------
53
+ # label vocabularies (match the controlled dataset)
54
+ # --------------------------------------------------------------------------
55
+ FMT_VOCAB = list(FORMAT_IDS) # sc,ofdm,dfts_ofdm,otfs,afdm,ofdm_comb
56
+ M_VOCAB = [8, 12, 16, 25]
57
+ K_VOCAB = [2, 4]
58
+ D_VOCAB = [1, 2, 4]
59
+ CHAN_VOCAB = ["flat", "multipath", "doppler"]
60
+ ARM_VOCAB = ["none", "random", "optimized"]
61
+ REGIMES = ["covert", "comparable", "detectable"]
62
+
63
+ # structure tasks: (name, vocab)
64
+ STRUCT_TASKS = [("format", FMT_VOCAB), ("M", M_VOCAB), ("K", K_VOCAB),
65
+ ("d", D_VOCAB), ("chan", CHAN_VOCAB), ("arm", ARM_VOCAB)]
66
+ TASKS = ["det"] + [t for t, _ in STRUCT_TASKS]
67
+
68
+
69
+ def _idx(vocab):
70
+ return {str(v): i for i, v in enumerate(vocab)}
71
+
72
+
73
+ _MAPS = {"format": _idx(FMT_VOCAB), "M": _idx(M_VOCAB), "K": _idx(K_VOCAB),
74
+ "d": _idx(D_VOCAB), "chan": _idx(CHAN_VOCAB), "arm": _idx(ARM_VOCAB)}
75
+
76
+ SPEC_LAGS = (16, 32, 48, 64, 80, 160, 240) # cyclic-autocorr lags (CP/frame cues)
77
+ SPEC_PSD_BINS = 64
78
+ SPEC_DIM = SPEC_PSD_BINS + len(SPEC_LAGS)
79
+
80
+ # Device on which per-batch feature extraction (complex FFT + spatial eigvalsh) runs.
81
+ # None -> CPU (default; MPS has no complex support, so features must stay on CPU there).
82
+ # main() sets this to 'cuda' when training on an NVIDIA GPU, so the whole step runs on-device.
83
+ _FEAT_DEVICE: "str | None" = None
84
+
85
+
86
+ # --------------------------------------------------------------------------
87
+ # feature extraction (complex ops -> stay on CPU; the net is real-valued)
88
+ # --------------------------------------------------------------------------
89
+ def spectral_feats(Yb: torch.Tensor) -> torch.Tensor:
90
+ """(n,R,T) complex -> (n, SPEC_DIM) real: antenna-mean log-PSD (64 bins) +
91
+ normalized cyclic-autocorrelation magnitudes at frame-relevant lags."""
92
+ n, r, t = Yb.shape
93
+ Yf = torch.fft.fft(Yb, dim=-1)
94
+ psd = torch.log1p((Yf.abs() ** 2).mean(1)) # (n,T)
95
+ k = t // SPEC_PSD_BINS
96
+ psd = F.avg_pool1d(psd.unsqueeze(1), kernel_size=k, stride=k).squeeze(1)[:, :SPEC_PSD_BINS]
97
+ psd = (psd - psd.mean(1, keepdim=True)) / (psd.std(1, keepdim=True) + 1e-6)
98
+ energy = (Yb.abs() ** 2).mean((1, 2)).clamp_min(1e-9) # (n,)
99
+ acs = []
100
+ for L in SPEC_LAGS:
101
+ ac = (Yb[..., :-L] * Yb[..., L:].conj()).mean(-1) # (n,R) complex
102
+ acs.append(ac.abs().mean(1) / energy) # (n,)
103
+ return torch.cat([psd, torch.stack(acs, 1)], 1).float() # (n, SPEC_DIM)
104
+
105
+
106
+ def batch_feats(Yb: torch.Tensor):
107
+ """(n,R,T) complex64 -> (x (n,R,3,T), sp (n,7), mask (n,R) bool, spec (n,SPEC_DIM)).
108
+
109
+ Runs on ``_FEAT_DEVICE`` when set (CUDA path: complex64 FFT + eigvalsh on the GPU);
110
+ callers move the returned float32 features to the net device afterwards."""
111
+ if _FEAT_DEVICE is not None:
112
+ Yb = Yb.to(_FEAT_DEVICE)
113
+ n, r, _ = Yb.shape
114
+ x = to_real_iq(Yb) # (n,R,3,T) float32
115
+ mask = torch.ones(n, r, dtype=torch.bool, device=Yb.device)
116
+ sp = spatial_features(Yb, mask) # (n,7)
117
+ spec = spectral_feats(Yb) # (n,SPEC_DIM)
118
+ return x, sp, mask, spec
119
+
120
+
121
+ # --------------------------------------------------------------------------
122
+ # model
123
+ # --------------------------------------------------------------------------
124
+ class SpectralMLP(nn.Module):
125
+ def __init__(self, in_dim=SPEC_DIM, d=48, drop=0.2):
126
+ super().__init__()
127
+ self.net = nn.Sequential(nn.Linear(in_dim, d), nn.GELU(), nn.Dropout(drop),
128
+ nn.Linear(d, d), nn.GELU())
129
+ self.d = d
130
+
131
+ def forward(self, s):
132
+ return self.net(s)
133
+
134
+
135
+ class MultiTaskUniversalEve(nn.Module):
136
+ """Shared detection backbone -> embedding ``e``; spectral branch -> ``spec_emb``;
137
+ detection head off ``e``; structure heads off ``[e, spec_emb]``."""
138
+
139
+ def __init__(self, width=96, drop=0.3, spec_d=48):
140
+ super().__init__()
141
+ self.ant = AntennaEncoder(3, width, drop=drop)
142
+ self.D = self.ant.d
143
+ self.attn = nn.Linear(self.D, 1)
144
+ self.spatial_norm = nn.LayerNorm(N_SPATIAL)
145
+ self.block = nn.Sequential(nn.Linear(2 * self.D + N_SPATIAL, self.D), nn.GELU(), nn.Dropout(drop))
146
+ self.det_head = nn.Linear(self.D, 1) # detection off e
147
+ self.spec = SpectralMLP(SPEC_DIM, spec_d, drop=min(0.3, drop))
148
+ sd = self.D + spec_d
149
+ self.struct_heads = nn.ModuleDict(
150
+ {name: nn.Sequential(nn.Linear(sd, self.D), nn.GELU(), nn.Dropout(drop),
151
+ nn.Linear(self.D, len(vocab)))
152
+ for name, vocab in STRUCT_TASKS})
153
+
154
+ def embed(self, x, sp, mask):
155
+ """x:(N,R,3,T) real, sp:(N,7), mask:(N,R) -> detection embedding e:(N,D)."""
156
+ n, r = x.shape[:2]
157
+ z = self.ant(x.reshape(n * r, *x.shape[2:])).reshape(n, r, self.D)
158
+ m = mask.unsqueeze(-1)
159
+ a = torch.softmax(self.attn(z).masked_fill(~m, float("-inf")), dim=1)
160
+ attn_pool = (a * z).sum(1)
161
+ mean_pool = (z * m).sum(1) / m.sum(1).clamp_min(1)
162
+ return self.block(torch.cat([attn_pool, mean_pool, self.spatial_norm(sp)], dim=1))
163
+
164
+ def forward(self, x, sp, mask, spec):
165
+ e = self.embed(x, sp, mask)
166
+ se = torch.cat([e, self.spec(spec)], dim=1)
167
+ out = {"det": self.det_head(e).squeeze(-1)}
168
+ for name in self.struct_heads:
169
+ out[name] = self.struct_heads[name](se)
170
+ return out
171
+
172
+
173
+ class LinearProbes(nn.Module):
174
+ """Structure probes on a FROZEN detection embedding (regime C). MLP probes so
175
+ the comparison to A is about the representation, not head capacity."""
176
+
177
+ def __init__(self, d, drop=0.2):
178
+ super().__init__()
179
+ self.heads = nn.ModuleDict(
180
+ {name: nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Dropout(drop),
181
+ nn.Linear(d, len(vocab)))
182
+ for name, vocab in STRUCT_TASKS})
183
+
184
+ def forward(self, e):
185
+ return {name: self.heads[name](e) for name in self.heads}
186
+
187
+
188
+ # --------------------------------------------------------------------------
189
+ # masked, uncertainty-weighted multi-task loss (Kendall-Gal)
190
+ # --------------------------------------------------------------------------
191
+ class MTLoss(nn.Module):
192
+ def __init__(self, tasks=TASKS):
193
+ super().__init__()
194
+ self.tasks = list(tasks)
195
+ self.log_sigma = nn.Parameter(torch.zeros(len(self.tasks))) # learnable uncertainty
196
+ self.bce = nn.BCEWithLogitsLoss()
197
+ self.ce = nn.CrossEntropyLoss()
198
+
199
+ def forward(self, out, labels, h1):
200
+ """out: head logits; labels: dict of index tensors (+ 'det' float01); h1: bool mask.
201
+ Structure losses are computed on H1 only. Returns (total, raw{task:loss})."""
202
+ raw = {}
203
+ raw["det"] = self.bce(out["det"], labels["det"])
204
+ h1 = h1.bool()
205
+ for name, _ in STRUCT_TASKS:
206
+ if name in self.tasks and h1.any():
207
+ raw[name] = self.ce(out[name][h1], labels[name][h1])
208
+ elif name in self.tasks:
209
+ raw[name] = out[name].sum() * 0.0
210
+ total = 0.0
211
+ for i, tsk in enumerate(self.tasks):
212
+ s = self.log_sigma[i]
213
+ total = total + torch.exp(-s) * raw[tsk] + 0.5 * s
214
+ return total, {k: float(v.detach()) for k, v in raw.items()}
215
+
216
+
217
+ # --------------------------------------------------------------------------
218
+ # data
219
+ # --------------------------------------------------------------------------
220
+ def load_arrays(data_dir: str, split: str, max_n: int | None = None, seed: int = 0) -> dict:
221
+ """Load one split's Y + encoded multi-task labels as torch tensors (Y on CPU)."""
222
+ from .controlled import load_split
223
+ d = load_split(data_dir, split)
224
+ Y = torch.from_numpy(d["Y"]) # (n,R,T) complex64
225
+ n = Y.shape[0]
226
+ if max_n and max_n < n:
227
+ rng = np.random.default_rng(seed)
228
+ keep = np.sort(rng.choice(n, size=max_n, replace=False))
229
+ Y = Y[keep]
230
+ d = {k: (v[keep] if hasattr(v, "__len__") and len(v) == n else v) for k, v in d.items()}
231
+ n = max_n
232
+ out = {"Y": Y, "n": n}
233
+ out["det"] = torch.from_numpy(d["label"].astype(np.float32))
234
+ out["format"] = torch.tensor([_MAPS["format"][str(v)] for v in d["format"]], dtype=torch.long)
235
+ out["M"] = torch.tensor([_MAPS["M"][str(int(v))] for v in d["n_tx"]], dtype=torch.long)
236
+ out["K"] = torch.tensor([_MAPS["K"][str(int(v))] for v in d["n_msg_users"]], dtype=torch.long)
237
+ out["d"] = torch.tensor([_MAPS["d"][str(int(v))] for v in d["msg_dim"]], dtype=torch.long)
238
+ out["chan"] = torch.tensor([_MAPS["chan"][str(v)] for v in d["channel_family"]], dtype=torch.long)
239
+ out["arm"] = torch.tensor([_MAPS["arm"][str(v)] for v in d["policy_arm"]], dtype=torch.long)
240
+ out["regime"] = np.array([str(v) for v in d["regime"]])
241
+ out["arm_str"] = np.array([str(v) for v in d["policy_arm"]])
242
+ out["fmt_str"] = np.array([str(v) for v in d["format"]])
243
+ out["eve_snr"] = np.asarray(d["eve_snr_db"], dtype=np.float32)
244
+ out["cell_id"] = np.asarray(d["cell_id"], dtype=np.int64) # same-emitter grouping (multi-look)
245
+ return out
246
+
247
+
248
+ def _to_dev(t, dev):
249
+ return {k: (v.to(dev) if torch.is_tensor(v) else v) for k, v in t.items()}
250
+
251
+
252
+ # --------------------------------------------------------------------------
253
+ # evaluation: the structure-recovery frontier
254
+ # --------------------------------------------------------------------------
255
+ @torch.no_grad()
256
+ def evaluate(model, arr, device, *, batch=512, probes=None, embed_only=False) -> dict:
257
+ """Per-regime detection AUC + per-attribute H1 accuracy (overall, per regime,
258
+ per arm for 'format'). ``probes`` (regime C) reads the frozen embedding."""
259
+ model.eval()
260
+ if probes is not None:
261
+ probes.eval()
262
+ n = arr["n"]
263
+ det_logits = np.empty(n, np.float32)
264
+ preds = {name: np.empty(n, np.int64) for name, _ in STRUCT_TASKS}
265
+ for lo in range(0, n, batch):
266
+ hi = min(lo + batch, n)
267
+ Yb = arr["Y"][lo:hi]
268
+ x, sp, mask, spec = batch_feats(Yb)
269
+ x, sp, mask, spec = x.to(device), sp.to(device), mask.to(device), spec.to(device)
270
+ if probes is not None:
271
+ e = model.embed(x, sp, mask)
272
+ det_logits[lo:hi] = model.det_head(e).squeeze(-1).cpu().numpy()
273
+ ph = probes(e)
274
+ for name, _ in STRUCT_TASKS:
275
+ preds[name][lo:hi] = ph[name].argmax(1).cpu().numpy()
276
+ else:
277
+ out = model(x, sp, mask, spec)
278
+ det_logits[lo:hi] = out["det"].cpu().numpy()
279
+ for name, _ in STRUCT_TASKS:
280
+ preds[name][lo:hi] = out[name].argmax(1).cpu().numpy()
281
+
282
+ labels = {name: arr[name].numpy() for name, _ in STRUCT_TASKS}
283
+ det = arr["det"].numpy()
284
+ reg = arr["regime"]
285
+ h1 = det == 1
286
+ res = {"n": int(n), "detection_auc": {}, "structure_acc": {}, "format_acc_by_arm": {}}
287
+
288
+ # detection AUC overall + per regime
289
+ res["detection_auc"]["overall"] = round(float(_auc(det_logits, det)), 4) if 0 < det.sum() < n else None
290
+ for rg in REGIMES:
291
+ m = reg == rg
292
+ if m.sum() > 1 and 0 < det[m].sum() < m.sum():
293
+ res["detection_auc"][rg] = round(float(_auc(det_logits[m], det[m])), 4)
294
+
295
+ # structure accuracy (H1 only): overall + per regime
296
+ for name, vocab in STRUCT_TASKS:
297
+ acc = {"chance": round(1.0 / len(vocab), 3)}
298
+ mm = h1
299
+ acc["overall"] = round(float((preds[name][mm] == labels[name][mm]).mean()), 4) if mm.sum() else None
300
+ for rg in REGIMES:
301
+ m = h1 & (reg == rg)
302
+ if m.sum():
303
+ acc[rg] = round(float((preds[name][m] == labels[name][m]).mean()), 4)
304
+ res["structure_acc"][name] = acc
305
+
306
+ # format accuracy per arm x regime (is the covert 'optimized' arm the hardest to fingerprint?)
307
+ for arm in ARM_VOCAB:
308
+ row = {}
309
+ for rg in REGIMES:
310
+ m = h1 & (arr["arm_str"] == arm) & (reg == rg)
311
+ if m.sum():
312
+ row[rg] = round(float((preds["format"][m] == labels["format"][m]).mean()), 4)
313
+ res["format_acc_by_arm"][arm] = row
314
+ return res
315
+
316
+
317
+ # --------------------------------------------------------------------------
318
+ # training
319
+ # --------------------------------------------------------------------------
320
+ def _lr_factor(frac, warm=0.03, min_frac=0.05):
321
+ if frac < warm:
322
+ return frac / warm
323
+ p = (frac - warm) / max(1e-9, 1 - warm)
324
+ return min_frac + 0.5 * (1 - min_frac) * (1 + math.cos(math.pi * min(1.0, p)))
325
+
326
+
327
+ def _sample_batch(arr, idx, dev):
328
+ Yb = arr["Y"][idx]
329
+ x, sp, mask, spec = batch_feats(Yb)
330
+ labels = {"det": arr["det"][idx]}
331
+ for name, _ in STRUCT_TASKS:
332
+ labels[name] = arr[name][idx]
333
+ x, sp, mask, spec = x.to(dev), sp.to(dev), mask.to(dev), spec.to(dev)
334
+ labels = {k: v.to(dev) for k, v in labels.items()}
335
+ return x, sp, mask, spec, labels
336
+
337
+
338
+ def train_joint(train, val, *, device, steps=4000, width=96, batch=256, lr=1e-3,
339
+ tasks=TASKS, run_dir="runs/mtl_A", log_every=200, seed=0, verbose=True) -> dict:
340
+ """Regime A: joint multi-task from scratch."""
341
+ os.makedirs(run_dir, exist_ok=True)
342
+ torch.manual_seed(seed)
343
+ rng = np.random.default_rng(seed)
344
+ model = MultiTaskUniversalEve(width=width).to(device)
345
+ mtl = MTLoss(tasks).to(device)
346
+ opt = torch.optim.AdamW(list(model.parameters()) + list(mtl.parameters()), lr=lr, weight_decay=1e-4)
347
+ hist = []
348
+ t0 = time.perf_counter()
349
+ n = train["n"]
350
+ for it in range(steps):
351
+ for g in opt.param_groups:
352
+ g["lr"] = lr * _lr_factor(it / max(1, steps))
353
+ idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
354
+ x, sp, mask, spec, labels = _sample_batch(train, idx, device)
355
+ model.train()
356
+ out = model(x, sp, mask, spec)
357
+ loss, raw = mtl(out, labels, labels["det"])
358
+ opt.zero_grad()
359
+ loss.backward()
360
+ torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(mtl.parameters()), 1.0)
361
+ opt.step()
362
+ if verbose and (it % log_every == 0 or it == steps - 1):
363
+ lv = float(loss.detach())
364
+ sps = (it + 1) / (time.perf_counter() - t0)
365
+ print(f" [A it={it:5d}] loss={lv:.3f} "
366
+ + " ".join(f"{k}={v:.3f}" for k, v in raw.items())
367
+ + f" {sps:.1f} it/s", flush=True)
368
+ hist.append({"it": it, "loss": round(lv, 4), "raw": {k: round(v, 4) for k, v in raw.items()}})
369
+ torch.save({"model": model.state_dict(), "mtl": mtl.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
370
+ va = evaluate(model, val, device)
371
+ if verbose:
372
+ print(f" [A] val det_auc={va['detection_auc']} "
373
+ f"format_acc={ {r: va['structure_acc']['format'].get(r) for r in REGIMES} }", flush=True)
374
+ return {"model": model, "history": hist, "val": va, "wall_s": round(time.perf_counter() - t0, 1)}
375
+
376
+
377
+ def train_detonly_then_probe(train, val, *, device, det_steps=4000, probe_steps=2500,
378
+ width=96, batch=256, lr=1e-3, run_dir="runs/mtl_C",
379
+ log_every=200, seed=1, verbose=True) -> dict:
380
+ """Regime C: detection-only pretrain -> freeze backbone -> MLP structure probes
381
+ on the frozen detection embedding."""
382
+ os.makedirs(run_dir, exist_ok=True)
383
+ torch.manual_seed(seed)
384
+ rng = np.random.default_rng(seed)
385
+ model = MultiTaskUniversalEve(width=width).to(device)
386
+ bce = nn.BCEWithLogitsLoss()
387
+ opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
388
+ t0 = time.perf_counter()
389
+ n = train["n"]
390
+ # -- detection-only pretrain --
391
+ for it in range(det_steps):
392
+ for g in opt.param_groups:
393
+ g["lr"] = lr * _lr_factor(it / max(1, det_steps))
394
+ idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
395
+ x, sp, mask, spec, labels = _sample_batch(train, idx, device)
396
+ model.train()
397
+ logit = model.det_head(model.embed(x, sp, mask)).squeeze(-1)
398
+ loss = bce(logit, labels["det"])
399
+ opt.zero_grad(); loss.backward()
400
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
401
+ if verbose and (it % log_every == 0 or it == det_steps - 1):
402
+ print(f" [C-det it={it:5d}] bce={float(loss):.3f} {(it+1)/(time.perf_counter()-t0):.1f} it/s", flush=True)
403
+ # -- freeze backbone, train probes on frozen embedding --
404
+ for p in model.parameters():
405
+ p.requires_grad_(False)
406
+ probes = LinearProbes(model.D).to(device)
407
+ popt = torch.optim.AdamW(probes.parameters(), lr=1e-3, weight_decay=1e-4)
408
+ ce = nn.CrossEntropyLoss()
409
+ tp = time.perf_counter()
410
+ for it in range(probe_steps):
411
+ idx = torch.from_numpy(rng.choice(n, size=batch, replace=False))
412
+ x, sp, mask, spec, labels = _sample_batch(train, idx, device)
413
+ with torch.no_grad():
414
+ e = model.embed(x, sp, mask)
415
+ h1 = labels["det"].bool()
416
+ if h1.sum() < 2:
417
+ continue
418
+ ph = probes(e[h1])
419
+ loss = sum(ce(ph[name], labels[name][h1]) for name, _ in STRUCT_TASKS)
420
+ popt.zero_grad(); loss.backward(); popt.step()
421
+ if verbose and (it % log_every == 0 or it == probe_steps - 1):
422
+ print(f" [C-probe it={it:5d}] ce_sum={float(loss):.3f} {(it+1)/(time.perf_counter()-tp):.1f} it/s", flush=True)
423
+ torch.save({"model": model.state_dict(), "probes": probes.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
424
+ va = evaluate(model, val, device, probes=probes)
425
+ if verbose:
426
+ print(f" [C] val det_auc={va['detection_auc']} "
427
+ f"format_acc={ {r: va['structure_acc']['format'].get(r) for r in REGIMES} }", flush=True)
428
+ return {"model": model, "probes": probes, "val": va, "wall_s": round(time.perf_counter() - t0, 1)}
429
+
430
+
431
+ # --------------------------------------------------------------------------
432
+ # regime B: multi-look aggregation (lift the fingerprinting frontier)
433
+ # --------------------------------------------------------------------------
434
+ # A warden watching a persistent emitter collects many blocks; pooling L looks of
435
+ # the SAME emitter (same factorial cell -> same format/M/arm/channel) averages out
436
+ # per-block noise and raises the fingerprint SNR ~sqrt(L) without any new data.
437
+ def _h1_by_cell(arr) -> dict:
438
+ cid = arr["cell_id"]
439
+ det = arr["det"].numpy()
440
+ cells = {}
441
+ for c in np.unique(cid[det == 1]):
442
+ cells[int(c)] = np.where((cid == c) & (det == 1))[0]
443
+ return cells
444
+
445
+
446
+ def _sample_look_idx(cells, keys, n_looks, L, rng) -> torch.Tensor:
447
+ """(n_looks*L,) flat indices, ordered look-major (each look = L blocks of one cell)."""
448
+ out = []
449
+ for _ in range(n_looks):
450
+ pool = cells[int(keys[rng.integers(len(keys))])]
451
+ out.append(pool[rng.integers(len(pool), size=L)])
452
+ return torch.from_numpy(np.concatenate(out))
453
+
454
+
455
+ def _look_feats(arr, idx):
456
+ return batch_feats(arr["Y"][idx])
457
+
458
+
459
+ def _pool_struct(model, x, sp, mask, spec, n_looks, L):
460
+ """Encode L blocks/look, mean-pool e and spec_emb over the look -> structure logits."""
461
+ e = model.embed(x, sp, mask).view(n_looks, L, -1).mean(1)
462
+ se = model.spec(spec).view(n_looks, L, -1).mean(1)
463
+ sfeat = torch.cat([e, se], 1)
464
+ return {name: model.struct_heads[name](sfeat) for name, _ in STRUCT_TASKS}
465
+
466
+
467
+ def train_multilook(train, val, *, device, steps=4500, width=96, det_batch=256,
468
+ n_looks=32, look_sizes=(1, 2, 4, 8), lr=1e-3, run_dir="runs/mtl_B",
469
+ log_every=250, seed=2, verbose=True) -> dict:
470
+ """Joint multi-task with MULTI-LOOK structure heads (random L per step)."""
471
+ os.makedirs(run_dir, exist_ok=True)
472
+ torch.manual_seed(seed)
473
+ rng = np.random.default_rng(seed)
474
+ model = MultiTaskUniversalEve(width=width).to(device)
475
+ log_sigma = torch.nn.Parameter(torch.zeros(len(TASKS), device=device))
476
+ bce, ce = nn.BCEWithLogitsLoss(), nn.CrossEntropyLoss()
477
+ opt = torch.optim.AdamW(list(model.parameters()) + [log_sigma], lr=lr, weight_decay=1e-4)
478
+ cells = _h1_by_cell(train)
479
+ keys = np.array(list(cells))
480
+ n = train["n"]
481
+ t0 = time.perf_counter()
482
+ for it in range(steps):
483
+ for g in opt.param_groups:
484
+ g["lr"] = lr * _lr_factor(it / max(1, steps))
485
+ L = int(rng.choice(look_sizes))
486
+ idxd = torch.from_numpy(rng.choice(n, det_batch, replace=False))
487
+ xd, spd, maskd, specd, labd = _sample_batch(train, idxd, device)
488
+ lidx = _sample_look_idx(cells, keys, n_looks, L, rng)
489
+ xs, sps, masks, specs = _look_feats(train, lidx)
490
+ xs, sps, masks, specs = xs.to(device), sps.to(device), masks.to(device), specs.to(device)
491
+ rep = lidx.view(n_looks, L)[:, 0]
492
+ slab = {name: train[name][rep].to(device) for name, _ in STRUCT_TASKS}
493
+ model.train()
494
+ det_logit = model.det_head(model.embed(xd, spd, maskd)).squeeze(-1)
495
+ slog = _pool_struct(model, xs, sps, masks, specs, n_looks, L)
496
+ raw = {"det": bce(det_logit, labd["det"])}
497
+ for name, _ in STRUCT_TASKS:
498
+ raw[name] = ce(slog[name], slab[name])
499
+ total = sum(torch.exp(-log_sigma[i]) * raw[t] + 0.5 * log_sigma[i] for i, t in enumerate(TASKS))
500
+ opt.zero_grad(); total.backward()
501
+ torch.nn.utils.clip_grad_norm_(list(model.parameters()) + [log_sigma], 1.0); opt.step()
502
+ if verbose and (it % log_every == 0 or it == steps - 1):
503
+ print(f" [B it={it:5d} L={L}] loss={float(total.detach()):.3f} "
504
+ f"det={raw['det']:.3f} format={raw['format']:.3f} chan={raw['chan']:.3f} M={raw['M']:.3f}"
505
+ f" {(it+1)/(time.perf_counter()-t0):.1f} it/s", flush=True)
506
+ torch.save({"model": model.state_dict()}, os.path.join(run_dir, "ckpt.pt"))
507
+ sweep = {int(L): evaluate_multilook(model, val, device, int(L)) for L in look_sizes}
508
+ if verbose:
509
+ fmt = {L: sweep[L]["structure_acc"]["format"]["overall"] for L in sweep}
510
+ print(f" [B] val format-acc vs L: {fmt}", flush=True)
511
+ return {"model": model, "L_sweep_val": sweep, "wall_s": round(time.perf_counter() - t0, 1)}
512
+
513
+
514
+ @torch.no_grad()
515
+ def evaluate_multilook(model, arr, device, L, *, batch_looks=256) -> dict:
516
+ """Partition each cell's H1 blocks into looks of L, pool, predict structure.
517
+ Per-attribute accuracy overall / per regime, and format accuracy per arm."""
518
+ model.eval()
519
+ cells = _h1_by_cell(arr)
520
+ rows, labs = [], {name: [] for name, _ in STRUCT_TASKS}
521
+ reg, armv = [], []
522
+ for pool in cells.values():
523
+ m = len(pool) // L
524
+ if m == 0:
525
+ continue
526
+ for row in pool[:m * L].reshape(m, L):
527
+ rows.append(row)
528
+ for name, _ in STRUCT_TASKS:
529
+ labs[name].append(int(arr[name][row[0]]))
530
+ reg.append(arr["regime"][row[0]])
531
+ armv.append(arr["arm_str"][row[0]])
532
+ if not rows:
533
+ return {"L": L, "n_looks": 0, "structure_acc": {}}
534
+ look_idx = np.stack(rows) # (Nl, L)
535
+ Nl = look_idx.shape[0]
536
+ preds = {name: np.empty(Nl, np.int64) for name, _ in STRUCT_TASKS}
537
+ for lo in range(0, Nl, batch_looks):
538
+ hi = min(lo + batch_looks, Nl)
539
+ flat = torch.from_numpy(look_idx[lo:hi].reshape(-1))
540
+ x, sp, mask, spec = _look_feats(arr, flat)
541
+ x, sp, mask, spec = x.to(device), sp.to(device), mask.to(device), spec.to(device)
542
+ slog = _pool_struct(model, x, sp, mask, spec, hi - lo, L)
543
+ for name, _ in STRUCT_TASKS:
544
+ preds[name][lo:hi] = slog[name].argmax(1).cpu().numpy()
545
+ reg, armv = np.array(reg), np.array(armv)
546
+ res = {"L": L, "n_looks": int(Nl), "structure_acc": {}, "format_acc_by_arm": {}}
547
+ for name, _ in STRUCT_TASKS:
548
+ lab = np.array(labs[name])
549
+ acc = {"overall": round(float((preds[name] == lab).mean()), 4)}
550
+ for rg in REGIMES:
551
+ mm = reg == rg
552
+ if mm.sum():
553
+ acc[rg] = round(float((preds[name][mm] == lab[mm]).mean()), 4)
554
+ res["structure_acc"][name] = acc
555
+ flab = np.array(labs["format"])
556
+ for arm in ARM_VOCAB:
557
+ mm = armv == arm
558
+ if mm.sum():
559
+ res["format_acc_by_arm"][arm] = round(float((preds["format"][mm] == flab[mm]).mean()), 4)
560
+ return res
561
+
562
+
563
+ # --------------------------------------------------------------------------
564
+ # CLI
565
+ # --------------------------------------------------------------------------
566
+ def main(argv=None) -> int:
567
+ ap = argparse.ArgumentParser(prog="covcollab-eve-mtl",
568
+ description="Train + evaluate the multi-task Universal Eve (detect + fingerprint).")
569
+ ap.add_argument("--data", default="huggingface/covcollab-eve-detection")
570
+ ap.add_argument("--regime", choices=("A", "C", "B", "both"), default="both",
571
+ help="A=joint, C=det-rep probe, B=multi-look (lift the fingerprint frontier)")
572
+ ap.add_argument("--steps", type=int, default=4000)
573
+ ap.add_argument("--probe-steps", type=int, default=2500)
574
+ ap.add_argument("--look-sizes", type=int, nargs="*", default=[1, 2, 4, 8], help="regime B L-sweep")
575
+ ap.add_argument("--n-looks", type=int, default=32, help="regime B looks per step")
576
+ ap.add_argument("--width", type=int, default=96)
577
+ ap.add_argument("--batch", type=int, default=256)
578
+ ap.add_argument("--max-train", type=int, default=None, help="subsample train (default: all)")
579
+ ap.add_argument("--device", default="auto")
580
+ ap.add_argument("--feat-device", default="auto",
581
+ help="where per-batch feature extraction runs: 'auto'=net device on CUDA "
582
+ "(complex64 FFT+eigvalsh on-GPU), else CPU (MPS lacks complex); or cpu/cuda")
583
+ ap.add_argument("--out", default="runs/mtl")
584
+ ap.add_argument("--eval-splits", nargs="*", default=["test_iid", "test_ood"])
585
+ ap.add_argument("--smoke", action="store_true")
586
+ args = ap.parse_args(argv)
587
+
588
+ if args.smoke:
589
+ args.steps, args.probe_steps, args.max_train, args.width = 60, 40, 1500, 48
590
+
591
+ dev = pick_device(args.device)
592
+ global _FEAT_DEVICE
593
+ if args.feat_device == "auto":
594
+ _FEAT_DEVICE = "cuda" if dev == "cuda" else None # CUDA-only; MPS/CPU keep CPU features
595
+ elif args.feat_device in ("cpu", "none"):
596
+ _FEAT_DEVICE = None
597
+ else:
598
+ _FEAT_DEVICE = args.feat_device
599
+ os.makedirs(args.out, exist_ok=True)
600
+ print(f"device={dev} feat_device={_FEAT_DEVICE or 'cpu'} data={args.data} regime={args.regime} "
601
+ f"steps={args.steps} width={args.width} max_train={args.max_train}", flush=True)
602
+
603
+ train = load_arrays(args.data, "train", max_n=args.max_train)
604
+ val = load_arrays(args.data, "val")
605
+ print(f"loaded train n={train['n']} val n={val['n']}", flush=True)
606
+
607
+ results = {"config": {"regime": args.regime, "steps": args.steps, "width": args.width,
608
+ "batch": args.batch, "max_train": args.max_train, "device": dev}}
609
+ tests = {sp: load_arrays(args.data, sp) for sp in args.eval_splits}
610
+
611
+ if args.regime in ("A", "both"):
612
+ r = train_joint(train, val, device=dev, steps=args.steps, width=args.width,
613
+ batch=args.batch, run_dir=os.path.join(args.out, "A"))
614
+ results["A"] = {"val": r["val"], "wall_s": r["wall_s"],
615
+ "test": {sp: evaluate(r["model"], tests[sp], dev) for sp in tests}}
616
+ if args.regime in ("C", "both"):
617
+ r = train_detonly_then_probe(train, val, device=dev, det_steps=args.steps,
618
+ probe_steps=args.probe_steps, width=args.width,
619
+ batch=args.batch, run_dir=os.path.join(args.out, "C"))
620
+ results["C"] = {"val": r["val"], "wall_s": r["wall_s"],
621
+ "test": {sp: evaluate(r["model"], tests[sp], dev, probes=r["probes"]) for sp in tests}}
622
+ if args.regime == "B":
623
+ ls = tuple(args.look_sizes)
624
+ r = train_multilook(train, val, device=dev, steps=args.steps, width=args.width,
625
+ det_batch=args.batch, n_looks=args.n_looks, look_sizes=ls,
626
+ run_dir=os.path.join(args.out, "B"))
627
+ results["B"] = {"wall_s": r["wall_s"], "look_sizes": list(ls),
628
+ "L_sweep": {sp: {int(L): evaluate_multilook(r["model"], tests[sp], dev, int(L))
629
+ for L in ls} for sp in tests}}
630
+
631
+ with open(os.path.join(args.out, "results.json"), "w") as f:
632
+ json.dump(results, f, indent=2)
633
+ print(f"\nresults -> {args.out}/results.json", flush=True)
634
+ return 0
635
+
636
+
637
+ if __name__ == "__main__":
638
+ sys.exit(main())