File size: 12,079 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
#!/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())