Backup / gmnet /spectral_audit /scripts /reconstruct_alignment_snapshot.py
YFanwang's picture
Add files using upload-large-folder tool
12c2325 verified
Raw History Blame Contribute Delete
12.1 kB
#!/usr/bin/env python3
"""Recover the exact E4 alignment model source from the recorded forward patch."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
JOURNAL_ROOT = Path("/nfs/ywang29/GmNet/journal_exp")
DEFAULT_OUTPUT = Path(
"/nfs/ywang29/GmNet/e4_spectral_audit/source_snapshots/alignment_4a62"
)
SESSION_PATH = Path(
"/root/.codex/sessions/2026/07/12/"
"rollout-2026-07-12T19-12-35-019f57be-e49b-77b3-9198-0721b55f06ff.jsonl"
)
ALIGNMENT_CODE_SHA256 = (
"4a62bc48370247d882196cd9afc1a0f1629a5bbfd522c3f599ffaf0c1187641f"
)
MECHANISM_CODE_SHA256 = (
"f6bd434a2ac86c772f2e23683431f3bb7ccb06f539558682a3bea6464bacebf9"
)
SOURCE_SPECS = {
"gmnet/models/gmnet.py": {
"current_sha256": (
"8446a0ed7d6863f81e88929f3277d363c961372210279de7d0e770f636852f3c"
),
"recovered_sha256": (
"5291156084aaf72936d1f8896057e7e606f74ef05aed856df4940e4838dbe3ac"
),
"recovered_size": 28103,
"session_events": [
{
"timestamp": "2026-07-17T21:00:58.920Z",
"jsonl_line": 6665,
},
{
"timestamp": "2026-07-17T21:01:05.385Z",
"jsonl_line": 6670,
},
{
"timestamp": "2026-07-17T21:03:01.840Z",
"jsonl_line": 6723,
},
],
},
"gmnet/models/__init__.py": {
"current_sha256": (
"68a705c94c1223305f2d5ab18cc41faf36c35d90748fde5a32f4474222e4ef29"
),
"recovered_sha256": (
"9227138f9cd0e0110f57bad21b9302d8b5daa51cd63246e37c8ff2878eb2715e"
),
"recovered_size": 722,
"session_events": [
{
"timestamp": "2026-07-17T21:03:01.840Z",
"jsonl_line": 6723,
}
],
},
}
GMNET_REVERSE_REPLACEMENTS = (
(
'''SUPPORTED_GATE_INTERVENTIONS: Final[tuple[str, ...]] = (\n'''
''' "baseline",\n'''
''' "stop_gradient",\n'''
''' "channel_derangement",\n'''
''' "batch_derangement",\n'''
''' "stop_gradient_channel_derangement",\n'''
''')\n'''
'''CHANNEL_DERANGEMENT_INTERVENTIONS: Final[frozenset[str]] = frozenset(\n'''
''' {"channel_derangement", "stop_gradient_channel_derangement"}\n'''
''')\n'''
'''STOP_GRADIENT_INTERVENTIONS: Final[frozenset[str]] = frozenset(\n'''
''' {"stop_gradient", "stop_gradient_channel_derangement"}\n'''
''')\n''',
'''SUPPORTED_GATE_INTERVENTIONS: Final[tuple[str, ...]] = (\n'''
''' "baseline",\n'''
''' "stop_gradient",\n'''
''' "channel_derangement",\n'''
''')\n''',
),
(
''' permutation = (\n'''
''' _channel_derangement(channels, seed)\n'''
''' if intervention in CHANNEL_DERANGEMENT_INTERVENTIONS\n'''
''' else None\n'''
''' )\n''',
''' permutation = (\n'''
''' _channel_derangement(channels, seed)\n'''
''' if intervention == "channel_derangement"\n'''
''' else None\n'''
''' )\n''',
),
(
''' value = x\n'''
''' if self.gate_intervention == "batch_derangement":\n'''
''' if x.ndim < 1 or x.shape[0] < 2:\n'''
''' raise ValueError(\n'''
''' "batch_derangement requires at least two samples per local "\n'''
''' f"batch, got shape {tuple(x.shape)}"\n'''
''' )\n'''
''' shift = self.batch_derangement_shift(int(x.shape[0]))\n'''
''' value = x.roll(shifts=-shift, dims=0)\n'''
''' elif self.gate_intervention in CHANNEL_DERANGEMENT_INTERVENTIONS:\n'''
''' if x.ndim < 2 or x.shape[1] != self._gate_channels:\n'''
''' raise ValueError(\n'''
''' "channel derangement expected channel dimension "\n'''
''' f"{self._gate_channels}, got shape {tuple(x.shape)}"\n'''
''' )\n'''
''' assert self.gate_permutation is not None\n'''
''' value = x.index_select(1, self.gate_permutation)\n'''
''' if self.gate_intervention in STOP_GRADIENT_INTERVENTIONS:\n'''
''' value = value.detach()\n'''
''' return value\n'''
'''\n'''
''' def batch_derangement_shift(self, batch_size: int) -> int:\n'''
''' """Return the seeded cyclic shift used for a local batch derangement."""\n'''
'''\n'''
''' if isinstance(batch_size, bool) or not isinstance(batch_size, int):\n'''
''' raise TypeError("batch_size must be an integer")\n'''
''' if batch_size < 2:\n'''
''' raise ValueError("batch derangement requires batch_size >= 2")\n'''
''' return 1 + self.gate_intervention_seed % (batch_size - 1)\n''',
''' if self.gate_intervention == "baseline":\n'''
''' return x\n'''
''' if self.gate_intervention == "stop_gradient":\n'''
''' return x.detach()\n'''
''' if x.ndim < 2 or x.shape[1] != self._gate_channels:\n'''
''' raise ValueError(\n'''
''' "channel_derangement expected channel dimension "\n'''
''' f"{self._gate_channels}, got shape {tuple(x.shape)}"\n'''
''' )\n'''
''' assert self.gate_permutation is not None\n'''
''' return x.index_select(1, self.gate_permutation)\n''',
),
(
''' "is_bijection": is_bijection,\n'''
''' "stops_gate_gradient": (\n'''
''' module.gate_intervention\n'''
''' in STOP_GRADIENT_INTERVENTIONS\n'''
''' ),\n'''
''' "channel_derangement": (\n'''
''' module.gate_intervention\n'''
''' in CHANNEL_DERANGEMENT_INTERVENTIONS\n'''
''' ),\n'''
''' "batch_derangement": (\n'''
''' module.gate_intervention == "batch_derangement"\n'''
''' ),\n'''
''' "batch_shift_rule": (\n'''
''' "1 + seed % (local_batch_size - 1)"\n'''
''' if module.gate_intervention == "batch_derangement"\n'''
''' else None\n'''
''' ),\n''',
''' "is_bijection": is_bijection,\n''',
),
(
'''__all__ = [\n "CHANNEL_DERANGEMENT_INTERVENTIONS",\n''',
'''__all__ = [\n''',
),
(
''' "SmoothClippedSelfGate",\n "STOP_GRADIENT_INTERVENTIONS",\n''',
''' "SmoothClippedSelfGate",\n''',
),
)
INIT_REVERSE_REPLACEMENTS = (
(
'''from .gmnet import (\n CHANNEL_DERANGEMENT_INTERVENTIONS,\n''',
'''from .gmnet import (\n''',
),
(
''' SmoothClippedSelfGate,\n STOP_GRADIENT_INTERVENTIONS,\n''',
''' SmoothClippedSelfGate,\n''',
),
(
'''__all__ = [\n "CHANNEL_DERANGEMENT_INTERVENTIONS",\n''',
'''__all__ = [\n''',
),
(
''' "SmoothClippedSelfGate",\n "STOP_GRADIENT_INTERVENTIONS",\n''',
''' "SmoothClippedSelfGate",\n''',
),
)
def sha256_bytes(value: bytes) -> str:
return hashlib.sha256(value).hexdigest()
def recover(relative_path: str, replacements: tuple[tuple[str, str], ...]) -> bytes:
spec = SOURCE_SPECS[relative_path]
source = (JOURNAL_ROOT / relative_path).read_bytes()
actual = sha256_bytes(source)
if actual != spec["current_sha256"]:
raise RuntimeError(
f"current {relative_path} SHA256 mismatch: {actual} != "
f"{spec['current_sha256']}"
)
text = source.decode("utf-8")
for index, (postimage, preimage) in enumerate(replacements):
count = text.count(postimage)
if count != 1:
raise RuntimeError(
f"reverse replacement {index} for {relative_path} matched {count} times"
)
text = text.replace(postimage, preimage)
recovered = text.encode("utf-8")
if len(recovered) != spec["recovered_size"]:
raise RuntimeError(
f"recovered {relative_path} size mismatch: {len(recovered)} != "
f"{spec['recovered_size']}"
)
digest = sha256_bytes(recovered)
if digest != spec["recovered_sha256"]:
raise RuntimeError(
f"recovered {relative_path} SHA256 mismatch: {digest} != "
f"{spec['recovered_sha256']}"
)
return recovered
def build_manifest(files: dict[str, bytes]) -> dict[str, object]:
return {
"schema_version": 1,
"snapshot_id": "alignment_4a62_model_source",
"alignment_code_sha256": ALIGNMENT_CODE_SHA256,
"source_postimage_code_sha256": MECHANISM_CODE_SHA256,
"recovery_method": "exact_reverse_of_recorded_forward_apply_patch",
"session_path": str(SESSION_PATH),
"files": [
{
"path": path,
"size": len(content),
"sha256": sha256_bytes(content),
"alignment_manifest_sha256": SOURCE_SPECS[path][
"recovered_sha256"
],
"session_events": SOURCE_SPECS[path]["session_events"],
}
for path, content in sorted(files.items())
],
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
# The original session is required once, at recovery time. Formal launch
# containers only validate the already frozen snapshot against the encoded
# reverse patch and hashes, so they do not depend on /root session storage.
if not args.check and not SESSION_PATH.is_file():
raise FileNotFoundError(f"recorded Codex session is missing: {SESSION_PATH}")
files = {
"gmnet/models/gmnet.py": recover(
"gmnet/models/gmnet.py", GMNET_REVERSE_REPLACEMENTS
),
"gmnet/models/__init__.py": recover(
"gmnet/models/__init__.py", INIT_REVERSE_REPLACEMENTS
),
}
manifest = build_manifest(files)
manifest_bytes = (
json.dumps(manifest, indent=2, sort_keys=True) + "\n"
).encode("utf-8")
if args.check:
for relative_path, expected in files.items():
path = args.output / relative_path
if not path.is_file() or path.read_bytes() != expected:
raise RuntimeError(f"snapshot mismatch: {path}")
manifest_path = args.output / "source_manifest.json"
if not manifest_path.is_file() or manifest_path.read_bytes() != manifest_bytes:
raise RuntimeError(f"snapshot manifest mismatch: {manifest_path}")
print(f"Validated exact alignment model snapshot at {args.output}")
return 0
for relative_path, content in files.items():
destination = args.output / relative_path
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(content)
(args.output / "source_manifest.json").write_bytes(manifest_bytes)
print(f"Recovered exact alignment model snapshot at {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())