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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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/env python3
"""Audit the exact-code, eight-GPU strict-resume smoke for E4 launches."""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
import re
import sys
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import torch
import yaml

SCRIPT_PATH = Path(__file__).resolve()
JOURNAL_ROOT = SCRIPT_PATH.parents[1]
DEFAULT_ROOT = Path("/tmp/gmnet_runs/e4_alignment_smoke")
DEFAULT_OUTPUT = Path(
    "/nfs/ywang29/GmNet/depoly/e4_alignment_20260716/smoke_evidence.json"
)
DEFAULT_MANIFEST = JOURNAL_ROOT / "configs/code_manifests/e4_alignment_20260716.json"
PROTOCOL_ID = "imagenet-e4-alignment-single-seed-20260716"
INTERVENTION_SEED = 41_041
BLOCK_SEED_STRIDE = 10_007
WORLD_SIZE = 8
SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
TASKS = {
    "e4a_s3_stop_gradient_seed0": {
        "mode": "stop_gradient",
        "directory": "stop_gradient",
        "config_path": "configs/smoke/imagenet5_gmnet_s1_e4_stop_gradient.yaml",
    },
    "e4a_s3_channel_derangement_seed0": {
        "mode": "channel_derangement",
        "directory": "channel_derangement",
        "config_path": ("configs/smoke/imagenet5_gmnet_s1_e4_channel_derangement.yaml"),
    },
}
REQUIRED_RUN_FILES = (
    "checkpoint_epoch0.pt",
    "checkpoint_last.pt",
    "config_source.yaml",
    "config_resolved.yaml",
    "data_manifest.json",
    "metrics.jsonl",
)


def file_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def stable_sha256(value: Any) -> str:
    payload = json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def load_json(path: Path) -> dict[str, Any]:
    loaded = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(loaded, dict):
        raise ValueError(f"expected JSON object: {path}")
    return loaded


def load_yaml(path: Path) -> dict[str, Any]:
    loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
    if not isinstance(loaded, dict):
        raise ValueError(f"expected YAML mapping: {path}")
    return loaded


def require_sha256(value: Any, location: str) -> str:
    if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None:
        raise ValueError(f"invalid SHA-256 at {location}: {value!r}")
    return value


def assert_finite(value: Any, location: str) -> None:
    if isinstance(value, float) and not math.isfinite(value):
        raise ValueError(f"non-finite value at {location}")
    if isinstance(value, dict):
        for key, child in value.items():
            assert_finite(child, f"{location}.{key}")
    elif isinstance(value, list):
        for index, child in enumerate(value):
            assert_finite(child, f"{location}[{index}]")


def resolve_manifest(path: Path) -> Path:
    return path if path.is_absolute() else JOURNAL_ROOT / path


def verify_code_manifest(path: Path) -> tuple[dict[str, Any], str]:
    resolved = resolve_manifest(path).resolve()
    manifest = load_json(resolved)
    if str(JOURNAL_ROOT) not in sys.path:
        sys.path.insert(0, str(JOURNAL_ROOT))
    from scripts.code_fingerprint import build_manifest

    actual = build_manifest(JOURNAL_ROOT)
    if manifest != actual:
        raise ValueError(
            "E4 code manifest does not match current source: "
            f"expected={manifest.get('code_sha256')} "
            f"actual={actual.get('code_sha256')}"
        )
    require_sha256(manifest.get("code_sha256"), "manifest.code_sha256")
    return manifest, file_sha256(resolved)


def load_checkpoint(path: Path) -> dict[str, Any]:
    checkpoint = torch.load(path, map_location="cpu", weights_only=False)
    if not isinstance(checkpoint, dict):
        raise ValueError(f"checkpoint is not a mapping: {path}")
    return checkpoint


def check_progress(
    checkpoint: dict[str, Any],
    *,
    epoch: int,
    global_step: int,
    training_complete: bool,
    location: str,
) -> None:
    expected = {
        "epoch": epoch,
        "global_step": global_step,
        "epoch_complete": True,
        "steps_in_epoch": 1,
        "expected_steps_per_epoch": 1,
        "training_complete": training_complete,
        "seed": 0,
        "world_size": WORLD_SIZE,
    }
    for key, value in expected.items():
        if checkpoint.get(key) != value:
            raise ValueError(
                f"{location}.{key}={checkpoint.get(key)!r}, expected {value!r}"
            )
    states = checkpoint.get("rng_state_by_rank")
    if not isinstance(states, list) or len(states) != WORLD_SIZE:
        raise ValueError(f"{location} lacks {WORLD_SIZE} per-rank RNG states")


def checkpoint_config(
    checkpoint: dict[str, Any], *, mode: str, code_sha256: str, location: str
) -> dict[str, Any]:
    config = checkpoint.get("config")
    if not isinstance(config, dict):
        raise ValueError(f"{location}.config is missing")
    model = config.get("model")
    train = config.get("train")
    data = config.get("data")
    protocol = config.get("protocol")
    if not all(isinstance(item, dict) for item in (model, train, data, protocol)):
        raise ValueError(f"{location} has incomplete config sections")
    expected = {
        "model.variant": model.get("variant"),
        "model.num_classes": model.get("num_classes"),
        "model.gate_type": model.get("gate_type"),
        "model.gate_intervention": model.get("gate_intervention"),
        "model.gate_intervention_seed": model.get("gate_intervention_seed"),
        "data.batch_size": data.get("batch_size"),
        "train.epochs": train.get("epochs"),
        "train.strict_resume": train.get("strict_resume"),
        "train.fail_on_nonfinite": train.get("fail_on_nonfinite"),
        "protocol.code_sha256": protocol.get("code_sha256"),
    }
    required = {
        "model.variant": "s1",
        "model.num_classes": 5,
        "model.gate_type": "relu6_self",
        "model.gate_intervention": mode,
        "model.gate_intervention_seed": INTERVENTION_SEED,
        "data.batch_size": 1,
        "train.epochs": 2,
        "train.strict_resume": True,
        "train.fail_on_nonfinite": True,
        "protocol.code_sha256": code_sha256,
    }
    for key, value in required.items():
        if expected[key] != value:
            raise ValueError(f"{location}.{key}={expected[key]!r}, expected {value!r}")
    return config


def model_identity(
    checkpoint: dict[str, Any], *, mode: str, location: str
) -> dict[str, Any]:
    if str(JOURNAL_ROOT) not in sys.path:
        sys.path.insert(0, str(JOURNAL_ROOT))
    from gmnet.engine import state_dict_schema_sha256
    from gmnet.models import create_gmnet

    state = checkpoint.get("model")
    config = checkpoint["config"]
    if not isinstance(state, dict):
        raise ValueError(f"{location}.model is missing")
    model_config = dict(config["model"])
    variant = str(model_config.pop("variant"))
    num_classes = int(model_config.pop("num_classes"))
    model = create_gmnet(variant, num_classes=num_classes, **model_config)
    model.load_state_dict(state, strict=True)
    parameter_count = sum(parameter.numel() for parameter in model.parameters())
    schema_sha256 = state_dict_schema_sha256(model.state_dict())
    if checkpoint.get("parameter_count") != parameter_count:
        raise ValueError(f"{location} parameter_count is inconsistent")
    if checkpoint.get("model_state_schema_sha256") != schema_sha256:
        raise ValueError(f"{location} state schema is inconsistent")

    rows = model.gate_intervention_metadata()
    if len(rows) != 16:
        raise ValueError(f"{location} expected 16 S1 blocks, got {len(rows)}")
    for index, row in enumerate(rows):
        expected_seed = INTERVENTION_SEED + index * BLOCK_SEED_STRIDE
        if (
            row.get("global_block_index") != index
            or row.get("mode") != mode
            or row.get("seed") != expected_seed
        ):
            raise ValueError(
                f"{location} intervention metadata drifted at block {index}"
            )
        if mode == "channel_derangement":
            require_sha256(
                row.get("permutation_sha256"),
                f"{location}.block[{index}].permutation_sha256",
            )
            if (
                row.get("permutation_hash_encoding") != "little_endian_int64_c_order"
                or row.get("is_bijection") is not True
                or row.get("fixed_points") != 0
            ):
                raise ValueError(
                    f"{location} invalid channel derangement at block {index}"
                )
        elif any(
            row.get(key) is not None
            for key in (
                "permutation_sha256",
                "permutation_hash_encoding",
                "is_bijection",
                "fixed_points",
            )
        ):
            raise ValueError(f"{location} unexpectedly has a permutation")
    return {
        "parameter_count": parameter_count,
        "state_tensor_count": len(model.state_dict()),
        "model_state_schema_sha256": schema_sha256,
        "block_count": len(rows),
        "block_seed_stride": BLOCK_SEED_STRIDE,
        "intervention_manifest_sha256": stable_sha256(rows),
        "blocks": rows,
    }


def parse_metrics(path: Path) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    for line_number, line in enumerate(
        path.read_text(encoding="utf-8").splitlines(), 1
    ):
        if not line.strip():
            continue
        record = json.loads(line)
        if not isinstance(record, dict):
            raise ValueError(f"metrics line {line_number} is not an object: {path}")
        assert_finite(record, f"{path}[{line_number}]")
        records.append(record)
    epochs = [record for record in records if record.get("kind") == "epoch"]
    expected = ((0, 1, False), (1, 2, True))
    if len(epochs) != len(expected):
        raise ValueError(f"{path} must contain exactly two epoch records")
    for record, (epoch, step, complete) in zip(epochs, expected, strict=True):
        required = {
            "epoch": epoch,
            "global_step": step,
            "epoch_complete": True,
            "steps_in_epoch": 1,
            "expected_steps_per_epoch": 1,
            "training_complete": complete,
        }
        for key, value in required.items():
            if record.get(key) != value:
                raise ValueError(f"{path} epoch {epoch} field {key} drifted")
    return records


def audit_task(
    task_id: str,
    specification: dict[str, str],
    *,
    root: Path,
    code_sha256: str,
) -> tuple[dict[str, Any], dict[str, Any]]:
    mode = specification["mode"]
    run_dir = (root / specification["directory"]).resolve()
    for name in REQUIRED_RUN_FILES:
        if not (run_dir / name).is_file():
            raise FileNotFoundError(f"missing E4 smoke artifact: {run_dir / name}")
    first_path = run_dir / "checkpoint_epoch0.pt"
    final_path = run_dir / "checkpoint_last.pt"
    first = load_checkpoint(first_path)
    final = load_checkpoint(final_path)
    check_progress(
        first,
        epoch=0,
        global_step=1,
        training_complete=False,
        location=f"{task_id}.epoch0",
    )
    check_progress(
        final,
        epoch=1,
        global_step=2,
        training_complete=True,
        location=f"{task_id}.final",
    )
    first_config = checkpoint_config(
        first, mode=mode, code_sha256=code_sha256, location=f"{task_id}.epoch0"
    )
    final_config = checkpoint_config(
        final, mode=mode, code_sha256=code_sha256, location=f"{task_id}.final"
    )
    identity_fields = ("config_fingerprint", "run_name", "seed", "world_size")
    for field in identity_fields:
        if first.get(field) != final.get(field):
            raise ValueError(f"{task_id} strict-resume identity drifted: {field}")
    if first_config != final_config:
        raise ValueError(f"{task_id} checkpoint config changed across resume")
    if first.get("data_manifest") != final.get("data_manifest"):
        raise ValueError(f"{task_id} data manifest changed across resume")
    if first.get("global_step", 0) >= final.get("global_step", 0):
        raise ValueError(f"{task_id} did not advance after resume")

    resolved = load_yaml(run_dir / "config_resolved.yaml")
    runtime = resolved.get("runtime", {})
    if not isinstance(runtime, dict):
        raise ValueError(f"{task_id} resolved runtime is missing")
    runtime_expected = {
        "run_name": final["run_name"],
        "seed": 0,
        "world_size": WORLD_SIZE,
        "config_fingerprint": final["config_fingerprint"],
        "data_manifest_sha256": final["data_manifest"]["manifest_sha256"],
    }
    for key, value in runtime_expected.items():
        if runtime.get(key) != value:
            raise ValueError(f"{task_id} resolved runtime drifted: {key}")
    disk_manifest = load_json(run_dir / "data_manifest.json")
    if disk_manifest != final["data_manifest"]:
        raise ValueError(f"{task_id} disk/checkpoint data manifests differ")

    records = parse_metrics(run_dir / "metrics.jsonl")
    first_model = model_identity(first, mode=mode, location=f"{task_id}.epoch0")
    final_model = model_identity(final, mode=mode, location=f"{task_id}.final")
    if first_model != final_model:
        raise ValueError(f"{task_id} model intervention identity changed across resume")
    artifact_hashes = {name: file_sha256(run_dir / name) for name in REQUIRED_RUN_FILES}
    first_sha = artifact_hashes["checkpoint_epoch0.pt"]
    final_sha = artifact_hashes["checkpoint_last.pt"]
    if first_sha == final_sha:
        raise ValueError(f"{task_id} final checkpoint did not change")
    return (
        {
            "gate_intervention": mode,
            "gate_intervention_seed": INTERVENTION_SEED,
            "smoke_config_path": specification["config_path"],
            "smoke_run_dir": str(run_dir),
            "run_name": final["run_name"],
            "checkpoint_epoch0_sha256": first_sha,
            "checkpoint_last_sha256": final_sha,
            "resume_verified": True,
            "training_complete": True,
            "epoch0": {"epoch": 0, "global_step": 1, "training_complete": False},
            "final": {"epoch": 1, "global_step": 2, "training_complete": True},
            "config_fingerprint": final["config_fingerprint"],
            "data_manifest_sha256": final["data_manifest"]["manifest_sha256"],
            "metric_record_count": len(records),
            "model_identity": final_model,
            "artifacts_sha256": artifact_hashes,
        },
        final_model,
    )


def audit(root: Path, manifest_path: Path) -> dict[str, Any]:
    manifest, manifest_sha256 = verify_code_manifest(manifest_path)
    task_records: dict[str, Any] = {}
    model_identities: list[dict[str, Any]] = []
    run_names: set[str] = set()
    for task_id, specification in TASKS.items():
        record, model = audit_task(
            task_id,
            specification,
            root=root,
            code_sha256=manifest["code_sha256"],
        )
        if record["run_name"] in run_names:
            raise ValueError("E4 smoke tasks reused a run name")
        run_names.add(record["run_name"])
        task_records[task_id] = record
        model_identities.append(model)

    topology = {
        key: model_identities[0][key]
        for key in (
            "parameter_count",
            "state_tensor_count",
            "model_state_schema_sha256",
            "block_count",
        )
    }
    for model in model_identities[1:]:
        for key, value in topology.items():
            if model[key] != value:
                raise ValueError(f"E4 smoke model topology differs across modes: {key}")
    manifest_resolved = resolve_manifest(manifest_path).resolve()
    return {
        "schema_version": 1,
        "protocol_id": PROTOCOL_ID,
        "status": "passed",
        "audited_at_utc": datetime.now(UTC).isoformat(),
        "code_sha256": manifest["code_sha256"],
        "code_manifest_path": manifest_resolved.relative_to(JOURNAL_ROOT).as_posix(),
        "code_manifest_sha256": manifest_sha256,
        "smoke_root": str(root.resolve()),
        "world_size": WORLD_SIZE,
        "strict_resume": True,
        "shared_topology": topology,
        "tasks": task_records,
    }


def write_atomic(path: Path, value: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
    temporary.write_text(
        json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    temporary.replace(path)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    evidence = audit(args.root, args.manifest)
    write_atomic(args.output, evidence)
    print(f"E4 smoke audit passed for {len(evidence['tasks'])} tasks: {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())