File size: 43,280 Bytes
0edf333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
"""Independent CPU audit of the matched 20-epoch scratch positional campaign.

This campaign is deliberately distinct from the earlier one-epoch conversion
proof. It validates scratch initialization, every accumulated MLM update/mask,
ten complete history epochs, fifteen classifier epochs, and all 54 held-out
account predictions with and without history. No original report is modified.
"""

from __future__ import annotations

import hashlib
import importlib.util
import json
import math
import time
from datetime import UTC, datetime
from pathlib import Path

import click
import numpy as np
import torch
from datasets import load_from_disk
from omegaconf import OmegaConf

from evm_bert.history_data import (
    build_account_examples, build_block_sequences, load_history_source,
    validate_account_source_binding, validate_block_source_binding,
)
from evm_bert.history_model import HierarchicalTransactionModel
from evm_bert.history_train import evaluate_accounts, stable_seed, tokenize_transactions
from evm_bert.model import build_model, load_mlm_model
from evm_bert.tokenizer import load_tokenizer
from evm_bert.train import _epoch_batches, _masked_batch_digest, _windows, mask_batch


SPEC = importlib.util.spec_from_file_location("scratch_shared_audit_helpers",
    Path(__file__).with_name("audit_position_comparison.py"))
H = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(H)

PROFILES = ("absolute", "rotary")
ARCHITECTURES = ("separate", "shared")
EXPECTED = {"seed": 17, "epochs": 20, "steps": 200, "physical_batch_size": 512,
    "gradient_accumulation_steps": 8, "effective_batch_size": 4096,
    "drop_last": True, "forward_backward_calls": 1600, "available_windows_per_epoch": 41013,
    "used_windows_per_epoch": 40960, "omitted_windows_per_epoch": 53,
    "history_epochs": 10, "history_steps": 1790, "fine_epochs": 15, "fine_steps": 225}


def tensor_digest(values):
    digest = hashlib.sha256()
    for name, value in values.items():
        digest.update(name.encode())
        digest.update(value.detach().cpu().contiguous().numpy().tobytes())
    return digest.hexdigest()


def validate_bert_config(config, profile):
    for name, value in {"vocab_size": 8192, "hidden_size": 48, "num_hidden_layers": 3,
            "num_attention_heads": 4, "intermediate_size": 128,
            "hidden_dropout_prob": .1, "attention_probs_dropout_prob": .1}.items():
        H.require(config[name] == value, f"Scratch BERT {name} differs")
    H.require(config["position_embedding_type"] == ("absolute" if profile == "absolute" else "evm_rotary"),
              "Scratch positional encoding differs")
    H.require(config["max_position_embeddings"] == (512 if profile == "absolute" else 2048),
              "Scratch positional capacity differs")
    if profile == "rotary":
        H.require(config["evm_rope"] == H.EXPECTED_ROPE, "Scratch rotary schedule differs")
    else:
        H.require(not config.get("evm_rope"), "Absolute scratch model contains a rotary schedule")
    H.require(config.get("evm_attention_backend") == "eager", "Scratch attention backend is not matched eager attention")
    initialization = config.get("evm_initialization", {})
    H.require(initialization.get("kind") == "paired random common weights; no trained checkpoint"
              and initialization.get("seed") == 17 and initialization.get("reference_absolute_capacity") == 512,
              "Scratch saved configuration does not declare paired fresh random initialization")


def audit_mps_runtime(runtime):
    H.require(torch.device(runtime["requested_device"]).type == "mps" and
        torch.device(runtime["actual_root_device"]).type == "mps" and
        bool(runtime["actual_parameter_devices"]) and
        all(torch.device(value).type == "mps" for value in runtime["actual_parameter_devices"]) and
        runtime["all_parameters_on_requested_accelerator"] is True and
        runtime["accelerator_class"].endswith(".MPSAccelerator"),
        "Neural training did not run entirely on the requested MPS accelerator")


def replay_mlm_masks(windows, tokenizer):
    """Regenerate actual CPU inputs/targets independently of either model."""
    order_generator = torch.Generator().manual_seed(19)
    mask_generator = torch.Generator().manual_seed(18)
    records, epochs, exposed = [], [], 0
    for epoch in range(1, 21):
        all_batches = _epoch_batches(len(windows), 4096, order_generator)
        flattened = [index for batch in all_batches for index in batch]
        batches = [batch for batch in all_batches if len(batch) == 4096]
        retained = [index for batch in batches for index in batch]
        omitted = flattened[len(retained):]

        def digest(values):
            return hashlib.sha256(torch.tensor(values, dtype=torch.int64).numpy().tobytes()).hexdigest()

        order_sha = digest(flattened)
        epoch_targets = 0
        for selected in batches:
            batch = mask_batch([windows[index] for index in selected], tokenizer, .15, mask_generator)
            targets = int((batch["labels"] != -100).sum())
            exposed += len(selected)
            epoch_targets += targets
            records.append({"step": len(records) + 1, "epoch": epoch,
                "train/effective_batch_size": len(selected), "train/windows_seen": exposed,
                "train/masked_tokens": targets, "train/physical_batch_size": min(512, len(selected)),
                "train/micro_batch_size": min(512, len(selected)),
                "train/physical_batches": math.ceil(len(selected) / 512),
                "train/backward_calls": math.ceil(len(selected) / 512),
                "train/gradient_accumulation_steps": 8,
                "train/partial_accumulation_group": int(len(selected) < 4096),
                "train/masked_batch_sha256": _masked_batch_digest(batch)})
        epochs.append({"epoch": epoch, "order_sha256": order_sha, "full_order_sha256": order_sha,
            "used_window_indices_sha256": digest(retained), "omitted_window_indices_sha256": digest(omitted),
            "omitted_window_indices": omitted, "available_windows": len(flattened),
            "omitted_windows": len(omitted), "drop_last": True, "masked_tokens": epoch_targets})
    return records, epochs


def replay_test_targets(windows, tokenizer):
    generator = torch.Generator().manual_seed(20017)
    order = torch.randperm(len(windows), generator=torch.Generator().manual_seed(20017)).tolist()
    targets = 0
    digest = hashlib.sha256()
    for start in range(0, len(order), 32):
        batch = mask_batch([windows[index] for index in order[start:start + 32]], tokenizer, .15, generator)
        targets += int((batch["labels"] != -100).sum())
        digest.update(_masked_batch_digest(batch).encode())
    return {"masked_tokens": targets, "mask_seed": 20017, "windows": len(windows),
        "evaluation_batch_size": 32, "replayed_test_batches_sha256": digest.hexdigest()}


def replay_history_targets(groups, windows, tokenizer, *, epochs=10):
    targets, digest = {}, hashlib.sha256()
    for epoch in range(1, epochs + 1):
        for group in groups:
            sequences = [sequence for transaction in group.transactions
                         for sequence in windows[transaction.tx_hash]]
            batch = mask_batch(sequences, tokenizer, .15,
                torch.Generator().manual_seed(stable_seed(17, epoch, group.group_id)))
            targets[epoch, group.group_id] = int((batch["labels"] != -100).sum())
            digest.update(f"{epoch}:{group.group_id}:".encode())
            digest.update(_masked_batch_digest(batch).encode())
    return targets, digest.hexdigest()


def audit_scratch_gradients(report, records, replayed, replay_epochs, coverage):
    """Reject old budgets, mistaken physical/effective batches, and mask drift."""
    H.require(report["initialization"] == "random", "Scratch MLM did not start from random initialization")
    H.require(report["device"] == "mps" and report["seed"] == 17, "Scratch device/seed differs")
    for name, expected in {"epochs": 20, "requested_epochs": 20, "steps": 200,
            "batch_size": 512, "physical_batch_size": 512, "micro_batch_size": 512,
            "gradient_accumulation_steps": 8, "effective_batch_size": 4096,
            "forward_backward_calls": 1600, "forward_calls": 1600,
            "physical_batches_seen": 1600, "optimizer_updates_per_epoch": 10,
            "physical_batches_per_epoch": 80, "forward_backward_calls_per_epoch": 80,
            "last_effective_batch_size": 4096, "last_batch_size": 512,
            "last_accumulation_group_physical_batches": 8,
            "last_accumulation_group_backward_calls": 8,
            "available_windows_per_epoch": 41013, "used_windows_per_epoch": 40960,
            "omitted_windows_per_epoch": 53, "omitted_window_exposures": 1060,
            "drop_last": True, "windows_seen": 819200}.items():
        H.require(report[name] == expected, f"Scratch report {name} differs from the declared 20-epoch accumulation budget")
    H.require(report["optimizer"] == "AdamW" and report["learning_rate"] == 1e-4
              and report["weight_decay"] == .01, "Scratch AdamW settings differ")
    H.require(report["all_epochs_complete_no_dropped_windows"] is False and
              report["all_epochs_complete_under_drop_last_policy"] is True and
              report["last_accumulation_group_partial"] is False and
              report["drop_last_unit"] == "incomplete effective optimizer accumulation group",
              "Scratch training did not follow the declared constant-batch drop_last policy")
    H.close(report["coverage"], coverage, "Scratch window/source coverage")
    runtime = report["lightning_runtime"]
    audit_mps_runtime(runtime)
    for name, value in {"framework": "lightning.pytorch", "trainer": "lightning.pytorch.Trainer",
            "optimizer_class": "torch.optim.adamw.AdamW", "optimizer_updates": 200,
            "trainer_global_step": 200, "backward_calls": 1600, "gradient_clip_max_norm": 1.}.items():
        H.require(runtime[name] == value, f"Scratch Lightning {name} differs")
    H.require(len(records) == len(replayed) == 200, "Scratch gradient/update coverage differs")
    positives = ["embeddings", "mlm_head", "layer_0", "layer_1", "layer_2"]
    for row, expected in zip(records, replayed, strict=True):
        for key, value in expected.items():
            H.require(row.get(key) == value, f"Scratch masked batch/order/accumulation differs at {row.get('step')}: {key}")
        H.require(row["train/learning_rate"] == 1e-4, "Scratch per-update learning rate differs")
        for key, value in row.items():
            if isinstance(value, (int, float)):
                H.require(math.isfinite(value), f"Nonfinite scratch scalar: {key}")
        H.require(all(row.get(f"gradients/{name}_l2", 0) > 0 for name in positives),
                  "A scratch encoder layer, embedding, or MLM head received no gradient")
        pre, post = row["gradients/pre_clip_global_l2"], row["gradients/post_clip_global_l2"]
        H.require(0 < post <= 1.00001 and pre > 0 and row["gradients/clip_max_norm"] == 1.,
                  "Scratch global gradient clipping did not bound the norm")
        H.close(pre, row["gradients/global_l2"], "Scratch preclip global norm", 1e-6)
        H.close(post, min(pre, 1.), "Scratch clipped norm", 1e-5)
        H.require(row["gradients/clipping_applied"] == int(pre > 1.), "Scratch clipping decision differs")
    H.require([item["epoch"] for item in report["epoch_history"]] == list(range(1, 21)),
              "Scratch epoch history is incomplete")
    for epoch, replay in zip(report["epoch_history"], replay_epochs, strict=True):
        selected = [row for row in records if row["epoch"] == epoch["epoch"]]
        for name, value in {**replay, "optimizer_steps": 10, "windows": 40960,
                "physical_batches": 80, "forward_backward_calls": 80,
                "last_effective_batch_size": 4096, "last_group_physical_batches": 8,
                "last_group_backward_calls": 8}.items():
            H.require(epoch[name] == value, f"Scratch epoch coverage/order differs: {name}")
        H.close(epoch["train_loss"], sum(row["train/loss"] * row["train/masked_tokens"] for row in selected)
                / sum(row["train/masked_tokens"] for row in selected), "Scratch token-weighted epoch loss")
    H.require(report["masked_tokens_seen"] == sum(row["train/masked_tokens"] for row in replayed),
              "Scratch masked target total differs")
    H.close(report["validation_after"], report["epoch_history"][-1]["validation"], "Scratch final validation")
    clipped = sum(row["gradients/clipping_applied"] for row in records)
    H.require(runtime["clipped_updates"] == clipped, "Scratch runtime clipping count differs")
    H.close(runtime["maximum_pre_clip_global_l2"], max(row["gradients/pre_clip_global_l2"] for row in records), "Scratch maximum preclip")
    H.close(runtime["maximum_post_clip_global_l2"], max(row["gradients/post_clip_global_l2"] for row in records), "Scratch maximum postclip")
    never_used = set.intersection(*(set(epoch["omitted_window_indices"]) for epoch in replay_epochs))
    return {"optimizer_updates": 200, "forward_backward_calls": 1600, "physical_batches": 1600,
        "windows_seen": 819200, "available_windows_per_epoch": 41013, "omitted_windows_per_epoch": 53,
        "omitted_window_exposures": 1060, "all_20_epochs_complete_under_drop_last_policy": True,
        "unique_available_windows_used_across_20_epochs": 41013 - len(never_used),
        "all_available_windows_ever_seen": not never_used,
        "all_200_corrupted_batches_independently_replayed": True,
        "last_effective_batch_size": 4096, "clipped_updates": clipped,
        "maximum_pre_clip_global_l2": runtime["maximum_pre_clip_global_l2"],
        "maximum_post_clip_global_l2": runtime["maximum_post_clip_global_l2"]}


def validate_initial_parameters(absolute, rotary, expected):
    key = "bert.embeddings.position_embeddings.weight"
    H.require(key in absolute and key not in rotary, "Initial learned position tables do not match the profiles")
    H.require(set(absolute) == set(expected), "Absolute initial parameter names differ from fresh random BERT")
    H.require(set(rotary) == set(absolute) - {key}, "Scratch profiles do not share exactly the common parameters")
    for name, value in absolute.items():
        H.require(torch.isfinite(value).all() and torch.equal(value, expected[name]),
                  f"Absolute initialization is not the declared fresh random reference: {name}")
        if name != key:
            H.require(torch.equal(value, rotary[name]), f"Scratch random common initial weights differ: {name}")
    return {"reference": "fresh absolute BERT constructed on CPU with seed17; rotary common weights match exactly",
        "all_absolute_initial_weights_match_fresh_random": True,
        "all_common_random_initial_tensors_identical": True,
        "common_parameter_tensors": len(rotary), "absolute_initial_sha256": tensor_digest(absolute),
        "rotary_initial_sha256": tensor_digest(rotary),
        "removed_absolute_position_parameters": absolute[key].numel()}


def audit_history_epochs(pre, fine, pre_rows, fine_rows, groups, examples, replayed_targets):
    H.require(pre["epochs"] == 10 and pre["optimizer_steps"] == 1790
              and fine["epochs"] == 15 and fine["optimizer_steps"] == 225,
              "Scratch hierarchy requires ten pretraining and fifteen classifier epochs")
    H.require(fine["classification_drop_last"] is True and fine["classification_batch_size"] == 16,
              "Scratch classifier did not use its declared drop_last full-batch policy")
    H.require(pre["seed"] == fine["seed"] == 17 and pre["contract"]["device"] == "mps",
              "Scratch hierarchy seed/device differs")
    for key, value in {"auxiliary_mlm_weight": .2, "learning_rate": 1e-4,
            "weight_decay": .01, "max_length": 256, "encoder_batch_size": 64,
            "epochs": 10, "mlm_probability": .15}.items():
        H.require(pre["contract"][key] == value, f"History scientific training contract differs: {key}")
    H.require([value["epoch"] for value in pre["epoch_history"]] == list(range(1, 11)),
              "History epoch coverage is incomplete")
    for epoch in pre["epoch_history"]:
        selected = [row for row in pre_rows if row["epoch"] == epoch["epoch"]]
        expected_order = torch.randperm(len(groups["train"]), generator=torch.Generator().manual_seed(
            stable_seed(17, epoch["epoch"], "order"))).tolist()
        expected_ids = [groups["train"][index].group_id for index in expected_order]
        H.require([row["group_id"] for row in selected] == expected_ids and len(selected) == 179,
                  "History epoch order repeats, drops, or reorders a source block")
        H.require(all(row["masked_tokens"] == replayed_targets[epoch["epoch"], row["group_id"]]
                      for row in selected), "History masked target counts differ from independent source replay")
        H.require(sum(row["transactions"] for row in selected) == epoch["transactions"] == 32414,
                  "History epoch transaction coverage differs")
        H.require(epoch["order_sha256"] == hashlib.sha256(json.dumps(expected_order).encode()).hexdigest(),
                  "History epoch order fingerprint differs")
        H.close(epoch["train_loss"], sum(row["conditional_mlm_loss"] * row["masked_tokens"] for row in selected)
            / sum(row["masked_tokens"] for row in selected), "History token-weighted epoch loss")
    H.require([value["epoch"] for value in fine["epoch_history"]] == list(range(1, 16)),
              "Classifier epoch coverage is incomplete")
    seen_accounts = set()
    for epoch in range(1, 16):
        selected = [row for row in fine_rows if row["epoch"] == epoch]
        H.require(len(examples["train"]) == 251 and len(selected) == 15 and
                  all(row["accounts"] == 16 for row in selected) and sum(row["accounts"] for row in selected) == 240,
                  "Classifier epoch dropped or repeated account exposure")
        order = torch.randperm(251, generator=torch.Generator().manual_seed(stable_seed(17, epoch, "fine-order"))).tolist()
        used, omitted = order[:240], order[240:]
        used_ids = [examples["train"][index].group_id for index in used]
        seen_accounts.update(used_ids)

        def digest(values):
            return hashlib.sha256(json.dumps(values).encode()).hexdigest()

        expected = {"available_accounts": 251, "used_accounts": 240, "omitted_accounts": 11,
            "drop_last": True, "full_order_sha256": digest(order), "used_order_sha256": digest(used),
            "omitted_order_sha256": digest(omitted),
            "full_account_order_sha256": digest([examples["train"][index].group_id for index in order]),
            "used_account_order_sha256": digest(used_ids),
            "omitted_account_order_sha256": digest([examples["train"][index].group_id for index in omitted])}
        H.require(fine["epoch_history"][epoch - 1]["account_exposure"] == expected,
                  "Classifier shuffled/used/omitted account identities differ from independent replay")
    H.require(fine["training_account_coverage"] == {"available_accounts": 251,
        "accounts_used_per_epoch": 240, "accounts_omitted_per_epoch": 11,
        "total_account_exposures": 3600, "total_omitted_account_exposures": 165,
        "unique_accounts_seen": len(seen_accounts), "all_train_accounts_ever_seen": len(seen_accounts) == 251,
        "seen_accounts_sha256": hashlib.sha256(json.dumps(sorted(seen_accounts)).encode()).hexdigest()},
        "Classifier cumulative account exposure or all-ever-seen assertion differs")
    selected_pre = min(pre["epoch_history"], key=lambda item: item["validation"]["loss"])
    selected_fine = max(fine["epoch_history"], key=lambda item: (item["validation"]["roc_auc"], -item["validation"]["loss"]))
    H.require(pre["selected_epoch"] == selected_pre["epoch"] and fine["selected_epoch"] == selected_fine["epoch"],
              "Checkpoint selection differs from the validation-only rule")
    H.close(pre["selected_validation"], selected_pre["validation"], "Selected history validation", 1e-6)
    H.close(fine["validation_selected"], selected_fine["validation"], "Selected classifier validation", 1e-6)


def verify_files_unchanged(snapshot):
    H.require(all(H.sha(path) == digest for path, digest in snapshot.items()),
              "An immutable source, report, or checkpoint changed during the scratch audit")


def audit(root, output=None):
    root = Path(root).resolve()
    output = Path(output).resolve() if output else root / "audit.json"
    H.require(not output.exists(), "Scratch audit output exists; choose a new --output")
    comparison, contract = H.load(root / "comparison.json"), H.load(root / "predeclared.json")
    H.require(comparison["contract"] == contract, "Scratch comparison differs from its predeclared contract")
    H.require(comparison.get("status") == "completed", "Scratch campaign is not completed")
    for key, value in {"seed": 17, "device": "mps", "mps_cpu_fallback": False,
            "scratch_epochs": 20, "physical_batch_size": 512, "gradient_accumulation_steps": 8,
            "effective_batch_size": 4096, "learning_rate": 1e-4, "weight_decay": .01,
            "drop_last": True, "history_epochs": 10, "classification_epochs": 15,
            "classification_drop_last": True, "rope": H.EXPECTED_ROPE,
            "initialization": "paired fresh random common weights; no trained checkpoint",
            "attention_backend": "eager for both"}.items():
        H.require(contract[key] == value, f"Scratch declared protocol differs: {key}")
    H.require(set(comparison["pretraining"]) == set(PROFILES), "Scratch pretraining profiles are incomplete")
    preserved = {Path(path): digest for path, digest in contract["source_sha256"].items()}
    H.require(len(preserved) >= 8, "Scratch protocol has no complete original-input preservation binding")
    verify_files_unchanged(preserved)
    results = comparison["results"]
    H.require(len(results) == 4 and {(item["profile"], item["architecture"]) for item in results} == H.EXPECTED_PAIRS,
              "Scratch comparison must contain exactly all four completed configurations")
    scratch = output.parent / f"{output.stem}-cpu"
    H.require(not scratch.exists(), "Scratch CPU inference audit directory already exists")
    scratch.mkdir(parents=True)
    torch.set_num_threads(4)
    started = time.monotonic()
    # Snapshot before loading checkpoints or running inference. Logs and W&B's
    # live transport files are outside the immutable scientific artifact set.
    extensions = {".json", ".jsonl", ".yaml", ".yml", ".pt", ".safetensors", ".md", ".txt"}
    tracked = {path: H.sha(path) for path in root.rglob("*")
               if path.is_file() and path.suffix in extensions and "wandb" not in path.parts
               and path != output and scratch not in path.parents}
    source = Path("data/transactions")
    tokenizer_dir = Path("artifacts/tokenizer")
    for directory in (source / "dataset", Path("data/kaggle/history-transactions/dataset"), tokenizer_dir):
        for path in directory.rglob("*"):
            if path.is_file():
                tracked[path] = H.sha(path)
    block_rows, block_audit = load_history_source(source / "dataset", block_disjoint=True)
    block_binding = validate_block_source_binding(source / "dataset", block_rows, tokenizer_dir=tokenizer_dir)
    H.require(block_audit["transactions"] == 40000, "Expected unchanged 40,000-transaction corpus")
    groups = build_block_sequences(block_rows, source_manifest=H.load(source / "manifest.json"))
    account_source = Path("data/kaggle/history-transactions")
    account_rows, account_audit = load_history_source(account_source / "dataset", account_disjoint=True)
    account_binding = validate_account_source_binding(account_source / "dataset", account_rows)
    H.require(account_audit["transactions"] == 1935, "Expected unchanged 1,935 signed benchmark transactions")
    examples, contexts = build_account_examples(account_rows, max_history_transactions=7, require_history=True)
    H.require(len(examples["test"]) == 54, "Expected unchanged 54-account primary test cohort")
    tokenizer = load_tokenizer(tokenizer_dir)
    dataset = load_from_disk(str(source / "dataset"))
    windows, coverage = {}, {}
    for split in ("train", "validation", "test"):
        windows[split], coverage[split] = _windows(tokenizer, dataset[split], 256)
    H.require(len(windows["train"]) == 41013, "Scratch training windows differ from the authenticated source")
    replayed, replay_epochs = replay_mlm_masks(windows["train"], tokenizer)
    replayed_test = replay_test_targets(windows["test"], tokenizer)
    sources = [source / name for name in ("manifest.json", "transactions.jsonl")]
    sources += [account_source / name for name in ("audit.json", "transactions.jsonl")]
    sources += [tokenizer_dir / name for name in ("tokenizer.json", "byte_encoding.json")]
    for path in [root / "comparison.json", root / "predeclared.json", *sources]:
        if path not in tracked:
            tracked[path] = H.sha(path)
    tracked.update(preserved)
    initial, mlm_table, pretraining_rows = {}, {}, {}
    for profile in PROFILES:
        directory = root / "pretraining" / profile
        report = H.load(directory / "training/report.json")
        config = OmegaConf.load(directory / "training/resolved_config.yaml")
        model_dir = directory / "model"
        declared = comparison["pretraining"][profile]
        for key, path in {"report_path": directory / "training/report.json", "model_path": model_dir,
                "test_report_path": directory / "training/evaluation.json"}.items():
            H.require(Path(declared[key]).resolve() == path.resolve(), "Scratch pretraining manifest points to a different artifact")
        saved_config = H.load(model_dir / "config.json")
        validate_bert_config(saved_config, profile)
        H.require(config.training.device == "mps" and config.model.max_length == 256,
                  "Scratch resolved config device/window differs")
        H.require(config.training.drop_last is True, "Scratch MLM resolved drop_last policy differs")
        H.require(report["train_corpus_sha256"] == block_binding["tokenizer_train_corpus_sha256"]
                  and report["dataset_manifest_sha256"] == H.sha(source / "manifest.json"),
                  "Scratch corpus/tokenizer source hashes differ")
        gradient_rows = H.rows(directory / "training/metrics.jsonl")
        checked = audit_scratch_gradients(report, gradient_rows, replayed, replay_epochs, coverage)
        first = torch.load(directory / "training/checkpoints/epoch-001.pt", map_location="cpu", weights_only=False)
        H.require(first["binding_sha256"] == report["training_binding_sha256"] and
            first["binding_sha256"] == hashlib.sha256(json.dumps(first["binding"], sort_keys=True).encode()).hexdigest(),
            "Scratch checkpoint binding differs from the report")
        H.require(first["binding"]["device"] == "mps" and first["completed_epochs"] == 1,
                  "Scratch initialization checkpoint device/epoch differs")
        for key, value in {"batch_size": 512, "micro_batch_size": 512,
                "gradient_accumulation_steps": 8, "effective_batch_size": 4096,
                "drop_last": True, "seed": 17}.items():
            H.require(first["binding"][key] == value, f"Scratch checkpoint scientific binding differs: {key}")
        H.require(first["global_step"] == 10 and first["windows_seen"] == 40960 and
                  first["forward_backward_calls_seen"] == 80 and first["physical_batches_seen"] == 80,
                  "Scratch first checkpoint counters differ from its complete drop_last epoch")
        initial[profile] = first["initial_parameters"]
        H.require(tensor_digest(initial[profile]) == report["initial_parameter_sha256"] == first["initial_parameter_sha256"],
                  "Scratch initial parameter fingerprint differs")
        final = load_mlm_model(model_dir, local_files_only=True).eval()
        H.require(sum(parameter.numel() for parameter in final.parameters()) == report["parameters"] ==
                  (494816 if profile == "absolute" else 470240), "Actual scratch MLM parameter count differs")
        H.require(final.config._attn_implementation == "eager", "Actual reloaded scratch attention backend differs")
        H.require(tensor_digest(dict(final.named_parameters())) == report["final_parameter_sha256"],
                  "Scratch final MLM parameters differ from the report")
        expected_checkpoints = {f"epoch-{epoch:03d}.pt" for epoch in range(1, 21)}
        H.require({path.name for path in (directory / "training/checkpoints").glob("epoch-*.pt")} == expected_checkpoints,
                  "Scratch epoch checkpoints are missing or exceed the requested budget")
        last = torch.load(directory / "training/checkpoints/epoch-020.pt", map_location="cpu", weights_only=False)
        H.require(last["global_step"] == 200 and last["completed_epochs"] == 20 and
                  last["windows_seen"] == 819200 and last["forward_backward_calls_seen"] == 1600 and
                  last["physical_batches_seen"] == 1600, "Scratch final optimizer checkpoint counters differ")
        H.require(set(last["model"]) == set(final.state_dict()) and all(torch.equal(value, final.state_dict()[name])
            for name, value in last["model"].items()), "Scratch final exported model differs from its epoch20 optimizer checkpoint")
        H.require(bool(last["optimizer"]["state"]) and all(float(state["step"]) == 200
            for state in last["optimizer"]["state"].values()), "Scratch AdamW parameter state counters differ")
        for name, digest in report["artifact_sha256"].items():
            H.require(H.sha(model_dir / name) == digest, f"Scratch MLM artifact differs: {name}")
        evaluation = H.load(directory / "training/evaluation.json")
        H.require(evaluation["split"] == "test" and evaluation["checkpoint_sha256"] == H.sha(model_dir / "model.safetensors")
                  and evaluation["mask_seed"] == 20017 and evaluation["windows"] == len(windows["test"]),
                  "Scratch MLM test report uses a different checkpoint, mask, or partial cohort")
        H.close(evaluation["coverage"], coverage["test"], "Scratch MLM test source coverage")
        H.require(evaluation["masked_tokens"] == replayed_test["masked_tokens"],
                  "Scratch MLM test masked targets differ from an independent replay")
        H.require(math.isfinite(evaluation["loss"]) and evaluation["masked_tokens"] > 0,
                  "Scratch MLM held-out metrics are invalid")
        mlm_table[profile] = {"parameters": report["parameters"], "clipping_and_coverage": checked,
            "validation_before": report["validation_before"], "validation_after": report["validation_after"],
            "test": evaluation, "weights_sha256": H.sha(model_dir / "model.safetensors"),
            "config_sha256": H.sha(model_dir / "config.json"),
            "independent_test_mask_replay": replayed_test,
            "test_loss_verification_scope": "Final checkpoint/test coverage and masks bound; GPU-reported test loss is not recomputed on CPU."}
        pretraining_rows[profile] = gradient_rows
        for path in directory.rglob("*"):
            if path.is_file() and "wandb" not in path.parts and path not in tracked:
                tracked[path] = H.sha(path)
        del first, last, final
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(17)
        reference = build_model({"tokenizer": {"vocab_size": 8192}, "model": {
            "hidden_size": 48, "num_hidden_layers": 3, "num_attention_heads": 4,
            "intermediate_size": 128, "max_position_embeddings": 512, "dropout": .1,
            "paired_random_initialization": True, "attn_implementation": "eager"}})
    initialization = validate_initial_parameters(initial["absolute"], initial["rotary"], dict(reference.named_parameters()))
    del initial, reference
    H.require([row["train/masked_batch_sha256"] for row in pretraining_rows["absolute"]]
              == [row["train/masked_batch_sha256"] for row in pretraining_rows["rotary"]],
              "Scratch profiles saw different corrupted training inputs")
    H.require(mlm_table["absolute"]["test"]["masked_tokens"] == mlm_table["rotary"]["test"]["masked_tokens"],
              "Scratch MLM test target masks differ between profiles")
    table, predictions, matched_history, matched_account_exposure = [], {}, None, None
    history_windows = tokenize_transactions(account_rows, tokenizer, 256)
    block_windows = tokenize_transactions(block_rows, tokenizer, 256)
    replayed_history_targets, history_mask_digest = replay_history_targets(groups["train"], block_windows, tokenizer)
    del block_windows
    labels = np.array([example.label for example in examples["test"]])
    for item in results:
        profile, architecture = item["profile"], item["architecture"]
        name, directory = f"{profile}-{architecture}-s17", root / f"{profile}-{architecture}-s17"
        pre, fine = H.load(directory / "report.json"), H.load(directory / "finetune/report.json")
        H.require(pre == item["pretraining"] and fine == item["finetuning"], "Scratch comparison embedded reports differ")
        H.require(pre["architecture"] == fine["architecture"] == architecture, "Scratch hierarchy architecture differs")
        H.require(pre["input"]["sha256"] == block_audit["sha256"] and pre["input"]["source_binding"] == block_binding,
                  "Scratch history corpus binding differs")
        H.require(fine["input"]["sha256"] == account_audit["sha256"] and fine["input"]["source_binding"] == account_binding
                  and fine["contexts"] == contexts, "Scratch account/source/context binding differs")
        source_model = root / "pretraining" / profile / "model"
        H.require(pre["contract"]["source_sha256"] == H.sha(source_model / "model.safetensors") and
                  pre["contract"]["tokenizer_sha256"] == H.sha(source_model / "tokenizer.json"),
                  "History model does not start from the matching new scratch profile")
        config = OmegaConf.load(directory / "resolved_config.yaml")
        for key, value in {"epochs": 10, "classification_epochs": 15, "classification_batch_size": 16,
                "learning_rate": 1e-4, "classification_learning_rate": 1e-4, "weight_decay": .01,
                "max_history_transactions": 7, "max_length": 256, "device": "mps",
                "classification_drop_last": True}.items():
            H.require(config.history[key] == value, f"Scratch hierarchy resolved setting differs: {key}")
        pre_rows, fine_rows = H.rows(directory / "gradients.jsonl"), H.rows(directory / "finetune/gradients.jsonl")
        for report in (pre, fine):
            H.require(report["lightning"]["optimizer_class"] == "torch.optim.adamw.AdamW", "Scratch history optimizer class differs")
            audit_mps_runtime(report["lightning"])
        pre_clip, fine_clip = H.audit_gradients(pre, pre_rows, architecture), H.audit_gradients(fine, fine_rows, architecture, classification=True)
        audit_history_epochs(pre, fine, pre_rows, fine_rows, groups, examples, replayed_history_targets)
        descriptor = [(row["epoch"], row["group_id"], row["masked_tokens"], row["transactions"]) for row in pre_rows]
        if matched_history is None:
            matched_history = descriptor
        H.require(descriptor == matched_history, "History order/mask target counts differ between positional/architecture variants")
        exposure = [row["account_exposure"] for row in fine["epoch_history"]]
        if matched_account_exposure is None:
            matched_account_exposure = exposure
        H.require(exposure == matched_account_exposure,
                  "Classifier full/used/omitted account orders differ between the four matched variants")
        H.audit_mlm_rows(directory, pre)
        for stage_dir, report, source_config in ((directory, pre, source_model / "config.json"),
                (directory / "finetune", fine, directory / "model/history_config.json")):
            metadata = H.load(stage_dir / "model/history_config.json")
            H.validate_model_config(metadata, profile, architecture)
            validate_bert_config(metadata["bert_config"], profile)
            H.require(H.sha(stage_dir / "model/model.safetensors") == report["model_sha256"]
                and H.sha(stage_dir / "model/history_config.json") == report["model_config_sha256"]
                and H.sha(source_config) == report["source_config_sha256"], "Scratch selected model/config/source fingerprint differs")
        model = HierarchicalTransactionModel.from_pretrained(directory / "finetune/model", device="cpu").eval()
        H.require(model.parameter_counts() == pre["parameters"] and
            (model.transaction_encoder is model.context_encoder) == (architecture == "shared"),
            "Actual scratch model capacity or weight sharing differs")
        views = {}
        for erased, view, filename, report_key in ((False, "causal", "test-predictions.jsonl", "test"),
                (True, "erased", "test-erased-predictions.jsonl", "test_erased_history")):
            saved = H.rows(directory / "finetune" / filename)
            truth = H.saved_classification(saved, examples["test"])
            H.close(fine[report_key], {key: value for key, value in truth.items() if key != "loss"}, f"Scratch saved {view} metrics")
            H.close(fine[report_key]["loss"], truth["loss"], f"Scratch saved {view} loss", 1e-6)
            generated = scratch / f"{name}-{view}.jsonl"
            evaluate_accounts(model, examples["test"], history_windows, tokenizer, torch.device("cpu"),
                batch_size=16, erase_history=erased, output=generated)
            observed = H.rows(generated)
            errors = []
            for old, new in zip(saved, observed, strict=True):
                H.require({key: value for key, value in old.items() if key != "probability"} ==
                          {key: value for key, value in new.items() if key != "probability"}, "Scratch CPU prediction identities differ")
                errors.append(abs(old["probability"] - new["probability"]))
            H.require(max(errors) <= 1e-5, "Scratch CPU probabilities differ from saved MPS predictions")
            views[view] = {"metrics_from_saved_probabilities": truth,
                "cpu_reload_max_probability_error": max(errors), "cpu_predictions": str(generated),
                "saved_prediction_sha256": H.sha(directory / "finetune" / filename), "cpu_prediction_sha256": H.sha(generated)}
            predictions[profile, architecture, view] = np.array([row["probability"] for row in saved])
            tracked[generated] = H.sha(generated)
        table.append({"profile": profile, "architecture": architecture, "seed": 17,
            "parameters": pre["parameters"], "pretraining_clipping": pre_clip, "finetuning_clipping": fine_clip,
            "history_pretraining_epochs": 10, "finetuning_epochs": 15,
            "classification_drop_last": True, "training_account_coverage": fine["training_account_coverage"],
            "account_views": views, "history_auc_gain": H.paired_auc_delta(labels,
                predictions[profile, architecture, "causal"], predictions[profile, architecture, "erased"]),
            "block_mlm_test": pre["test"], "selected_history_epoch": pre["selected_epoch"],
            "selected_classifier_epoch": fine["selected_epoch"]})
        for path in directory.rglob("*"):
            if path.is_file() and "wandb" not in path.parts and path not in tracked:
                tracked[path] = H.sha(path)
        del model
        print(json.dumps({"audited": name, "history_updates": 1790, "classifier_updates": 225,
                          "cpu_prediction_views": 2, "test_accounts": 54}), flush=True)
    contrasts = {}
    for profile in PROFILES:
        for view in ("causal", "erased"):
            contrasts[f"{profile}_{view}_shared_minus_separate"] = H.paired_auc_delta(labels,
                predictions[profile, "shared", view], predictions[profile, "separate", view])
    for architecture in ARCHITECTURES:
        for view in ("causal", "erased"):
            contrasts[f"{architecture}_{view}_rotary_minus_absolute"] = H.paired_auc_delta(labels,
                predictions["rotary", architecture, view], predictions["absolute", architecture, view])
    verify_files_unchanged(tracked)
    report = {"status": "passed", "completed_at": datetime.now(UTC).isoformat(), "device": "cpu",
        "scope": "Independent scratch initialization, source, every accumulated mask/update, hierarchy coverage, selected checkpoint and full CPU probability audit; no training or W&B server query",
        "comparison_contract": contract, "expected_budget": EXPECTED,
        "block_source_binding": block_binding, "account_source_binding": account_binding,
        "scratch_initialization": initialization, "scratch_pretraining": mlm_table,
        "scratch_mlm_test_rotary_minus_absolute_loss": mlm_table["rotary"]["test"]["loss"] - mlm_table["absolute"]["test"]["loss"],
        "all_scratch_masked_inputs_and_history_target_counts_matched": True,
        "all_1790_history_mask_target_counts_independently_replayed": True,
        "expected_history_mask_replay_sha256": history_mask_digest,
        "runs": table, "paired_auc_contrasts": contrasts,
        "optimizer_updates": 2 * 200 + 4 * (1790 + 225),
        "backward_calls": 2 * 1600 + 4 * (1790 + 225),
        "cpu_predictions_verified": 432, "probability_absolute_tolerance": 1e-5,
        "all_file_sha256": {str(path): digest for path, digest in sorted(tracked.items())},
        "elapsed_seconds": time.monotonic() - started,
        "limits": ["One seed and 54 historical account FLAG proxies; paired bootstrap intervals condition on fitted models, not training-seed variation.",
            "An account FLAG is not a verified transaction fraud label or a prospective deployment outcome.",
            "Dense rotary BERT adapts the released positional rule; it does not reproduce DeepSeek compressed/sparse attention or the full model."]}
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
    return report


@click.command()
@click.option("--root", type=click.Path(path_type=Path), default=Path("artifacts/positions-scratch-20ep"), show_default=True)
@click.option("--output", type=click.Path(path_type=Path), default=None)
def main(root, output):
    """Audit the completed matched scratch campaign using CPU inference only."""
    report = audit(root, output)
    click.echo(json.dumps({key: report[key] for key in ("status", "optimizer_updates", "backward_calls", "cpu_predictions_verified")}))


if __name__ == "__main__":
    main()