File size: 16,193 Bytes
12c2325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
"""Run E2 controlled spectral experiments and write auditable reports."""

from __future__ import annotations

import argparse
import csv
import json
import math
import platform
import subprocess
import sys
import zlib
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import numpy as np
import torch

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from gmnet.synthetic import SyntheticExperiment, load_synthetic_config
from gmnet.synthetic.metrics import bootstrap_mean_ci


IDENTITY_COLUMNS = ("protocol", "gate", "seed", "condition")
METRIC_DEFINITIONS = {
    "harmonic_generation": "Fraction of output FFT power outside the exact input-tone bins.",
    "band_transfer": "Fraction of output FFT power outside the input tone support or radial band.",
    "fundamental_gain": "Output/input power ratio on the exact input-frequency support.",
    "alias_fraction": "Output power at wrapped harmonic bins attributable to orders above Nyquist.",
    "dc_fraction": "Fraction of output power at DC.",
    "frequency_response": "Output/input power gain inside a random field's source band.",
    "frequency_auc": "AUC of source-band gain normalized by the lowest-band gain.",
    "fundamental_fraction": "Fraction of output power retained at the input fundamental.",
    "phase_sensitivity": "Coefficient of variation across translations/phases at fixed amplitude.",
    "high_frequency_preference": "High-cue power divided by low-plus-high power at original cue bins.",
    "phase_cross_modulation": "Relative high-cue power change caused only by a pi low-cue phase flip.",
    "high_readout_phase_shift": "Absolute high-cue coefficient phase change after a pi low-cue flip.",
    "cue_preference_auc": "AUC of high-frequency preference over log2 low/high amplitude ratio.",
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="configs/e2_synthetic/full.yaml")
    parser.add_argument("--output-dir", default=None)
    return parser.parse_args()


def metric_columns(rows: list[dict[str, Any]]) -> list[str]:
    return sorted(set().union(*(row.keys() for row in rows)) - set(IDENTITY_COLUMNS))


def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None:
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(rows)


def summarize(
    rows: list[dict[str, Any]],
    metrics: list[str],
    config: dict[str, Any],
    *,
    by_condition: bool,
) -> list[dict[str, Any]]:
    keys = ["protocol", "gate"] + (["condition"] if by_condition else [])
    groups: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        groups[tuple(row[key] for key in keys)].append(row)
    result: list[dict[str, Any]] = []
    statistics = config["statistics"]
    for group_key, group_rows in sorted(groups.items()):
        for metric in metrics:
            seed_values: dict[int, list[float]] = defaultdict(list)
            raw_count = 0
            for row in group_rows:
                if metric not in row or not math.isfinite(float(row[metric])):
                    continue
                seed_values[int(row["seed"])].append(float(row[metric]))
                raw_count += 1
            # Fixed frequencies, amplitudes, and phases are experimental
            # conditions, not independent replicates. Macro-average them per
            # seed before bootstrapping to avoid pseudo-replication.
            values = [float(np.mean(items)) for items in seed_values.values() if items]
            if not values:
                continue
            stable_seed = int(statistics["bootstrap_seed"]) + zlib.crc32(
                repr((group_key, metric)).encode()
            )
            mean, low, high, count = bootstrap_mean_ci(
                values,
                samples=int(statistics["bootstrap_samples"]),
                confidence=float(statistics["confidence"]),
                seed=stable_seed,
            )
            item = dict(zip(keys, group_key, strict=True))
            item.update(
                metric=metric,
                mean=mean,
                ci_low=low,
                ci_high=high,
                n=count,
                observations=raw_count,
            )
            result.append(item)
    return result


def lookup(
    summaries: list[dict[str, Any]], protocol: str, gate: str, metric: str
) -> dict[str, Any] | None:
    return next(
        (
            row
            for row in summaries
            if row["protocol"] == protocol
            and row["gate"] == gate
            and row["metric"] == metric
        ),
        None,
    )


def format_estimate(item: dict[str, Any] | None) -> str:
    if item is None:
        return "NA"
    return f'{item["mean"]:.4f} [{item["ci_low"]:.4f}, {item["ci_high"]:.4f}]'


def raw_mean(
    rows: list[dict[str, Any]],
    protocol: str,
    gate: str,
    metric: str,
    condition_fragment: str,
) -> float:
    values = [
        float(row[metric])
        for row in rows
        if row["protocol"] == protocol
        and row["gate"] == gate
        and condition_fragment in row["condition"]
        and metric in row
        and math.isfinite(float(row[metric]))
    ]
    return float(np.mean(values)) if values else math.nan


def make_report(
    config: dict[str, Any],
    rows: list[dict[str, Any]],
    summaries: list[dict[str, Any]],
    metadata: dict[str, Any],
) -> str:
    gates = config["gates"]
    lines = [
        "# E2 Controlled Spectral Mechanism Results",
        "",
        "This is an operator-level causal experiment. No classifier was trained, and no",
        "classification accuracy claim is made. Intervals are 95% percentile bootstrap",
        "confidence intervals over seed-level macro averages of the fixed conditions.",
        "",
        "## Run",
        "",
        f'- UTC: {metadata["finished_at_utc"]}',
        f'- Device: {metadata["device"]}',
        f'- Grid: {config["grid_size"]} x {config["grid_size"]}',
        f'- Seeds: {config["seeds"]}',
        f'- Raw observations: {len(rows)}',
        "",
        "## Main estimates",
        "",
        "All table cells are mean [95% CI].",
        "",
        "| Gate | Single-tone generated | Dual-tone generated | Random-field transfer | Frequency AUC | Alias power |",
        "|---|---:|---:|---:|---:|---:|",
    ]
    for gate in gates:
        values = [
            lookup(summaries, "single_tone", gate, "harmonic_generation"),
            lookup(summaries, "dual_tone", gate, "harmonic_generation"),
            lookup(summaries, "random_field", gate, "band_transfer"),
            lookup(summaries, "frequency_auc", gate, "frequency_auc"),
            lookup(summaries, "single_tone", gate, "alias_fraction"),
        ]
        lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")

    amplitudes = [float(value) for value in config["single_tone"]["amplitudes"]]
    lines.extend(
        [
            "",
            "## Controlled sweeps",
            "",
            "### Single-tone out-of-support power by amplitude",
            "",
            "| Gate | " + " | ".join(f"A={value:g}" for value in amplitudes) + " |",
            "|---|" + "---:|" * len(amplitudes),
        ]
    )
    for gate in gates:
        values = [
            raw_mean(rows, "single_tone", gate, "harmonic_generation", f"_a={amplitude:g}_")
            for amplitude in amplitudes
        ]
        lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")

    bands = [tuple(map(float, value)) for value in config["random_field"]["bands"]]
    lines.extend(
        [
            "",
            "### Random-field out-of-band transfer by source band",
            "",
            "| Gate | " + " | ".join(f"{low:g}-{high:g}" for low, high in bands) + " |",
            "|---|" + "---:|" * len(bands),
        ]
    )
    for gate in gates:
        values = [
            raw_mean(rows, "random_field", gate, "band_transfer", f"band={low:g}-{high:g}")
            for low, high in bands
        ]
        lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |")

    ratios = [float(value) for value in config["cue_conflict"]["low_to_high_ratios"]]
    lines.extend(
        [
            "",
            "### Causal high-cue modulation by low/high amplitude ratio",
            "",
            "| Gate | " + " | ".join(f"{ratio:g}" for ratio in ratios) + " |",
            "|---|" + "---:|" * len(ratios),
        ]
    )
    for gate in gates:
        values = [
            raw_mean(
                rows,
                "cue_conflict",
                gate,
                "phase_cross_modulation",
                f"low_high={ratio:g}",
            )
            for ratio in ratios
        ]
        lines.append(
            f'| {gate} | '
            + " | ".join("NA" if math.isnan(value) else f"{value:.4f}" for value in values)
            + " |"
        )
    lines.extend(
        [
            "",
            "| Gate | Phase sensitivity | High-frequency cue AUC | Low-phase causal modulation |",
            "|---|---:|---:|---:|",
        ]
    )
    for gate in gates:
        values = [
            lookup(summaries, "phase_sensitivity", gate, "phase_sensitivity"),
            lookup(summaries, "cue_conflict_auc", gate, "cue_preference_auc"),
            lookup(summaries, "cue_conflict", gate, "phase_cross_modulation"),
        ]
        lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |")

    no_gate_harmonic = lookup(summaries, "single_tone", "no_gate", "harmonic_generation")
    nonlinear = []
    for gate in gates:
        item = lookup(summaries, "single_tone", gate, "harmonic_generation")
        if item and gate not in {"no_gate", "identity"}:
            nonlinear.append((float(item["mean"]), gate))
    nonlinear.sort(reverse=True)
    cue_rank = []
    for gate in gates:
        item = lookup(summaries, "cue_conflict", gate, "phase_cross_modulation")
        if item:
            cue_rank.append((float(item["mean"]), gate))
    cue_rank.sort(reverse=True)
    relu6_high = raw_mean(rows, "single_tone", "relu6_self", "harmonic_generation", "_a=9_")
    relu_high = raw_mean(rows, "single_tone", "relu_self", "harmonic_generation", "_a=9_")
    smooth_high = raw_mean(
        rows, "single_tone", "smooth_clipped_self", "harmonic_generation", "_a=9_"
    )
    lines.extend(
        [
            "",
            "## Conclusions",
            "",
            f'1. The linear no_gate control generated {no_gate_harmonic["mean"]:.3e} mean out-of-support power, validating the FFT protocol against its zero-generation prediction.'
            if no_gate_harmonic
            else "1. The no_gate validation estimate was unavailable.",
            f"2. Among the composite gates, the largest average single-tone redistribution was produced by {nonlinear[0][1]} ({nonlinear[0][0]:.4f}). The x*x identity self-gate gives the analytic extreme of 1.0000 because it removes the original fundamental and creates DC plus the second harmonic."
            if nonlinear
            else "2. No nonlinear-gate estimate was available.",
            f"3. At amplitude 9, ReLU6 generated {relu6_high:.4f} out-of-support power versus {relu_high:.4f} for unclipped ReLU; smooth-clipped gave {smooth_high:.4f}. Thus the smooth static approximation tracks the clipping regime, while GELU's strongest difference occurs at small amplitude (see sweep).",
            f"4. In cue conflict, {cue_rank[0][1]} had the largest causal high-cue modulation under a low-cue phase flip ({cue_rank[0][0]:.4f}). A nonzero value demonstrates cross-frequency coupling introduced by the gate."
            if cue_rank
            else "4. No identifiable cue-conflict modulation estimate was available.",
            "5. Identity means the self-gate x*x, whereas no_gate is the pass-through control. For x*x, original cue bins disappear exactly in this cue setup; undefined cue-preference observations are excluded rather than converted to zeros.",
            "6. Phase sensitivity is numerically zero for every gate, as expected for a pointwise translation-equivariant operator on exact periodic tones. The nonzero cue result therefore comes from interaction between cues, not absolute signal translation.",
            "7. Frequency AUC near one means stationary band-limited fields receive comparable in-band gain across tested bands. It does not imply that the output remains in-band; band transfer reports that separately.",
            "",
            "## Metric definitions",
            "",
        ]
    )
    lines.extend(f'- **{name}**: {definition}' for name, definition in METRIC_DEFINITIONS.items())
    lines.extend(
        [
            "",
            "## Scope",
            "",
            "These results identify mechanisms of the isolated static gate under exact sampled",
            "signals. They should be paired with trained-network E1/E3 measurements before making",
            "claims about ImageNet features, robustness, or accuracy.",
            "",
        ]
    )
    return "\n".join(lines)


def json_safe(value: Any) -> Any:
    if isinstance(value, float) and not math.isfinite(value):
        return None
    if isinstance(value, dict):
        return {key: json_safe(item) for key, item in value.items()}
    if isinstance(value, list):
        return [json_safe(item) for item in value]
    return value


def main() -> None:
    args = parse_args()
    config_path = Path(args.config).resolve()
    config = load_synthetic_config(config_path)
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    output_dir = Path(args.output_dir or f"/tmp/gmnet_runs/e2_synthetic_{stamp}")
    output_dir.mkdir(parents=True, exist_ok=False)
    started = datetime.now(timezone.utc)
    experiment = SyntheticExperiment(config)
    rows = experiment.run()
    metrics = metric_columns(rows)
    summaries = summarize(rows, metrics, config, by_condition=False)
    condition_summaries = summarize(rows, metrics, config, by_condition=True)
    finished = datetime.now(timezone.utc)
    try:
        revision = subprocess.check_output(
            ["git", "rev-parse", "HEAD"],
            cwd=config_path.parents[2],
            text=True,
            stderr=subprocess.DEVNULL,
        ).strip()
    except (subprocess.CalledProcessError, FileNotFoundError):
        revision = "unknown"
    metadata = {
        "started_at_utc": started.isoformat(),
        "finished_at_utc": finished.isoformat(),
        "duration_seconds": (finished - started).total_seconds(),
        "device": str(experiment.device),
        "torch_version": torch.__version__,
        "python_version": platform.python_version(),
        "git_revision": revision,
        "config_path": str(config_path),
    }
    write_csv(output_dir / "raw_metrics.csv", rows, list(IDENTITY_COLUMNS) + metrics)
    write_csv(
        output_dir / "summary.csv",
        summaries,
        ["protocol", "gate", "metric", "mean", "ci_low", "ci_high", "n", "observations"],
    )
    write_csv(
        output_dir / "summary_by_condition.csv",
        condition_summaries,
        ["protocol", "gate", "condition", "metric", "mean", "ci_low", "ci_high", "n", "observations"],
    )
    payload = {
        "metadata": metadata,
        "config": config,
        "metric_definitions": METRIC_DEFINITIONS,
        "summaries": summaries,
    }
    (output_dir / "results.json").write_text(
        json.dumps(json_safe(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    report = make_report(config, rows, summaries, metadata)
    (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8")
    print(output_dir)


if __name__ == "__main__":
    main()