File size: 25,059 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 | """Independent CPU/source/gradient audit of the completed four-run position proof.
No training reports are edited. Missing config fingerprints in older in-flight
reports are bound here by a new sidecar. This audit runs CPU inference only.
"""
from __future__ import annotations
import hashlib
import json
import math
import time
from datetime import UTC, datetime
from pathlib import Path
import click
import numpy as np
import torch
from omegaconf import OmegaConf
from evm_bert.finetune import classification_metrics
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, tokenize_transactions
from evm_bert.tokenizer import load_tokenizer
EXPECTED_ROPE = {"rotary_dim": 8, "local_layers": 2, "local_base": 10000,
"scaled_base": 160000, "original_context": 512, "factor": 4.,
"beta_fast": 32., "beta_slow": 1.}
EXPECTED_PAIRS = {(profile, architecture) for profile in ("absolute", "rotary")
for architecture in ("separate", "shared")}
def load(path):
return json.loads(Path(path).read_text())
def rows(path):
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
def sha(path):
digest = hashlib.sha256()
with Path(path).open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def require(condition, message):
if not condition:
raise ValueError(message)
def close(actual, expected, context, tolerance=1e-10):
if isinstance(expected, dict):
require(isinstance(actual, dict), f"{context}: expected mapping")
for key, value in expected.items():
require(key in actual, f"{context}: missing {key}")
close(actual[key], value, f"{context}.{key}", tolerance)
elif isinstance(expected, (float, int)) and not isinstance(expected, bool):
require(math.isfinite(actual) and math.isclose(actual, expected, abs_tol=tolerance,
rel_tol=tolerance), f"{context}: {actual} != {expected}")
else:
require(actual == expected, f"{context}: values differ")
def validate_model_config(metadata, profile, architecture):
require(metadata["format_version"] == 1, "Unsupported history model format")
require(metadata["architecture"] == architecture, "Saved architecture differs")
require(metadata["auxiliary_mlm_weight"] == .2, "Auxiliary objective differs")
config = metadata["bert_config"]
for key, expected in {"hidden_size": 48, "num_hidden_layers": 3,
"num_attention_heads": 4, "intermediate_size": 128,
"vocab_size": 8192}.items():
require(config[key] == expected, f"Saved model {key} differs")
expected_type = "absolute" if profile == "absolute" else "evm_rotary"
require(config["position_embedding_type"] == expected_type, "Saved positional type differs")
require(config["max_position_embeddings"] == (512 if profile == "absolute" else 2048),
"Saved position capacity differs")
if profile == "rotary":
require(config["evm_rope"] == EXPECTED_ROPE, "Saved RoPE/YaRN schedule differs")
else:
require(not config.get("evm_rope"), "Absolute model unexpectedly contains a RoPE schedule")
return config
def audit_gradients(report, records, architecture, classification=False):
expected_steps = report["optimizer_steps"]
require(len(records) == expected_steps, "Gradient row count differs from optimizer updates")
require([row["step"] for row in records] == list(range(1, expected_steps + 1)),
"Gradient updates are not continuous")
runtime = report["lightning"]
for key, expected in {"framework": "lightning.pytorch", "trainer": "lightning.pytorch.Trainer",
"optimizer_updates": expected_steps, "trainer_global_step": expected_steps,
"backward_calls": expected_steps, "gradient_clip_max_norm": 1.}.items():
require(runtime[key] == expected, f"Lightning runtime {key} differs")
require(report["optimizer"] == "AdamW", "Optimizer differs from AdamW")
require(report["learning_rate"] == 1e-4 and report["weight_decay"] == .01,
"AdamW learning rate or weight decay differs")
prefixes = ["mlm.bert"] + (["history_bert"] if architecture == "separate" else [])
positive = [f"gradients/{prefix}/layer_{layer}_l2" for prefix in prefixes for layer in range(3)]
positive += [f"gradients/{prefix}/embeddings_l2" for prefix in prefixes]
positive += (["gradients/classifier_l2", "gradients/prior_transaction_vectors_l2"]
if classification else ["gradients/mlm_head_l2", "gradients/context_projection_l2",
"gradients/transaction_vectors_l2"])
for row in records:
for name, value in row.items():
if isinstance(value, (float, int)):
require(math.isfinite(value), f"Nonfinite {name}")
if name.startswith("gradients/"):
require(math.isfinite(value) and value >= 0, f"Nonfinite/negative {name}")
for name in positive:
require(row.get(name, 0) > 0, f"No positive gradient in {name}")
pre, post = row["gradients/pre_clip_global_l2"], row["gradients/post_clip_global_l2"]
require(pre > 0 and post > 0 and post <= 1.00001, "Clipping did not bound an actual norm")
close(pre, row["gradients/global_l2"], "preclip global norm", 1e-6)
require(row["gradients/clip_max_norm"] == 1., "Clip limit differs")
require(row["gradients/clipping_applied"] == int(pre > 1.), "Clipping flag differs")
close(post, min(pre, 1.), "Expected clipped norm", 1e-5)
clipped = sum(row["gradients/clipping_applied"] for row in records)
pre = max(row["gradients/pre_clip_global_l2"] for row in records)
post = max(row["gradients/post_clip_global_l2"] for row in records)
close(runtime["maximum_pre_clip_global_l2"], pre, "Maximum preclip norm")
close(runtime["maximum_post_clip_global_l2"], post, "Maximum postclip norm")
require(runtime["clipped_updates"] == clipped, "Clipped update total differs")
return {"optimizer_updates": expected_steps, "clipped_updates": clipped,
"maximum_pre_clip_global_l2": pre, "maximum_post_clip_global_l2": post,
"minimum_history_vector_gradient_l2": min(row[positive[-1]] for row in records),
"all_encoder_layers_and_history_vectors_receive_positive_gradients": True}
def saved_classification(records, examples):
require(len(records) == len(examples) == 54, "Expected 54 fixed test account examples")
for row, example in zip(records, examples, strict=True):
require(row["account"] == example.group_id and row["label"] == example.label
and row["candidate_tx_hash"] == example.target.tx_hash
and row["history_transactions"] == len(example.history),
"Saved prediction identity/label/history differs from authentic source")
require(math.isfinite(row["probability"]) and 0 < row["probability"] < 1,
"Invalid probability")
labels = np.array([row["label"] for row in records])
probabilities = np.array([row["probability"] for row in records])
truth = np.where(labels, probabilities, 1 - probabilities)
return {**classification_metrics(labels, probabilities), "loss": float(-np.log(truth).mean())}
def audit_mlm_rows(directory, report):
for mode, suffix in (("causal", "block-causal"), ("erased", "block-erased"),
("none", "block-none"), ("sender_causal", "sender-causal"),
("sender_erased", "sender-erased")):
records = rows(directory / f"test-{suffix}.jsonl")
count = sum(row["target_count"] for row in records)
metric = report["test"][mode]
close(metric["loss"], sum(row["loss_sum"] for row in records) / count, f"MLM {mode} loss")
close(metric["masked_accuracy"], sum(row["correct"] for row in records) / count,
f"MLM {mode} masked accuracy")
require(metric["mask_seed"] == 20017 and metric["masked_tokens"] == count,
"MLM test mask/target count differs")
require(metric["groups"] == len(records), "MLM test group count differs")
context_count = sum(row["history_target_count"] for row in records)
close(metric["history_only"]["loss"],
sum(row["history_loss_sum"] for row in records) / context_count,
f"MLM {mode} history-only loss")
def auc(labels, probabilities):
positive = probabilities[labels == 1]
negative = probabilities[labels == 0]
return float(((positive[:, None] > negative) + .5 * (positive[:, None] == negative)).mean())
def paired_auc_delta(labels, left, right, *, draws=2000, seed=9917):
generator = np.random.default_rng(seed)
classes = [np.flatnonzero(labels == label) for label in (0, 1)]
deltas = []
for _ in range(draws):
selected = np.concatenate([generator.choice(indices, len(indices), replace=True) for indices in classes])
deltas.append(auc(labels[selected], left[selected]) - auc(labels[selected], right[selected]))
return {"left_minus_right_auc": auc(labels, left) - auc(labels, right),
"paired_stratified_bootstrap_95_interval": np.quantile(deltas, [.025, .975]).tolist(),
"bootstrap_draws": draws, "bootstrap_seed": seed,
"scope": "conditional on these fixed single-seed models and 54 historical account proxies; not training-seed uncertainty"}
def audit(root, output=None):
root = Path(root).resolve()
output = Path(output).resolve() if output else root / "audit.json"
require(not output.exists(), "Audit sidecar already exists; choose a new --output")
comparison = load(root / "comparison.json")
results, contract = comparison["results"], comparison["contract"]
require(len(results) == 4 and {(row["profile"], row["architecture"]) for row in results} == EXPECTED_PAIRS,
"Comparison is partial or does not contain exactly four unique planned configurations")
require(load(root / "predeclared.json") == contract, "Comparison differs from its predeclared contract")
require(contract["seed"] == 17 and contract["pretraining_epochs"] == 1
and contract["finetuning_epochs"] == 5 and contract["rope"] == EXPECTED_ROPE,
"Unexpected comparison budget or positional schedule")
original = Path("artifacts/pretrained-20ep/model")
require(sha(original / "model.safetensors") == contract["source_weights_sha256"], "Original Part1 weights changed")
require(sha(original / "config.json") == contract["source_config_sha256"], "Original Part1 config changed")
scratch = output.parent / f"{output.stem}-cpu"
require(not scratch.exists(), "CPU inference audit directory already exists")
scratch.mkdir(parents=True)
torch.set_num_threads(4)
started = time.monotonic()
block_rows, block_audit = load_history_source("data/transactions/dataset", block_disjoint=True)
block_binding = validate_block_source_binding("data/transactions/dataset", block_rows, tokenizer_dir=original)
groups = build_block_sequences(block_rows, source_manifest=load("data/transactions/manifest.json"))
account_rows, account_audit = load_history_source("data/kaggle/history-transactions/dataset", account_disjoint=True)
account_binding = validate_account_source_binding("data/kaggle/history-transactions/dataset", account_rows)
examples, contexts = build_account_examples(account_rows, max_history_transactions=7, require_history=True)
tracked_files = {root / "comparison.json", root / "predeclared.json",
original / "config.json", original / "model.safetensors", original / "tokenizer.json",
Path("data/transactions/manifest.json"), Path("data/transactions/transactions.jsonl"),
Path("data/kaggle/history-transactions/audit.json"),
Path("data/kaggle/history-transactions/transactions.jsonl")}
tracked_files.update(path for path in root.glob("*.yaml") if path.is_file())
for path in (root / "rotary-part1-transfer").rglob("*"):
if path.is_file():
tracked_files.add(path)
table, predictions = [], {}
for item in results:
profile, architecture = item["profile"], item["architecture"]
name = f"{profile}-{architecture}-s17"
directory = root / name
pre, fine = load(directory / "report.json"), load(directory / "finetune/report.json")
require(pre == item["pretraining"] and fine == item["finetuning"], "Manifest embedded report differs from saved report")
require(pre["architecture"] == fine["architecture"] == architecture, "Report architecture differs")
require(pre["seed"] == fine["seed"] == 17 and pre["epochs"] == 1 and fine["epochs"] == 5,
"Report seed/budget differs")
require(pre["input"]["sha256"] == block_audit["sha256"]
and pre["input"]["source_binding"] == block_binding, "Pretrain source binding differs")
require(fine["input"]["sha256"] == account_audit["sha256"]
and fine["input"]["source_binding"] == account_binding and fine["contexts"] == contexts,
"Account source/history binding differs")
source = original if profile == "absolute" else root / "rotary-part1-transfer"
require(pre["contract"]["source_sha256"] == sha(source / "model.safetensors"), "Source model weights differ")
require(pre["contract"]["tokenizer_sha256"] == sha(source / "tokenizer.json"), "Source tokenizer differs")
config = OmegaConf.load(directory / "resolved_config.yaml")
require(int(config.history.max_history_transactions) == 7 and int(config.history.max_length) == 256,
"History/window capacity differs")
pre_gradients = rows(directory / "gradients.jsonl")
fine_gradients = rows(directory / "finetune/gradients.jsonl")
pre_clip = audit_gradients(pre, pre_gradients, architecture)
fine_clip = audit_gradients(fine, fine_gradients, architecture, classification=True)
require(pre["optimizer_steps"] == len(groups["train"]) == 179, "Incomplete block epoch")
lookup = {group.group_id: index for index, group in enumerate(groups["train"])}
order = [lookup[row["group_id"]] for row in pre_gradients]
require(sorted(order) == list(range(179)), "Block epoch repeated or dropped a group")
epoch = pre["epoch_history"][0]
require(epoch["order_sha256"] == hashlib.sha256(json.dumps(order).encode()).hexdigest(), "Saved block order differs")
require(sum(row["transactions"] for row in pre_gradients) == epoch["transactions"] == 32414, "Training coverage differs")
close(epoch["train_loss"], sum(row["conditional_mlm_loss"] * row["masked_tokens"] for row in pre_gradients)
/ sum(row["masked_tokens"] for row in pre_gradients), "Epoch MLM training loss")
for number in range(1, 6):
selected = [row for row in fine_gradients if row["epoch"] == number]
require(len(selected) == 16 and sum(row["accounts"] for row in selected) == len(examples["train"]) == 251,
"Fine-tuning epoch account exposure differs")
selected_epoch = max(fine["epoch_history"], key=lambda value:
(value["validation"]["roc_auc"], -value["validation"]["loss"]))["epoch"]
require(fine["selected_epoch"] == selected_epoch, "Fine-tuning selection was not validation-only")
require([row["epoch"] for row in fine["epoch_history"]] == list(range(1, 6)),
"Fine-tuning validation history is incomplete")
close(fine["validation_selected"], fine["epoch_history"][selected_epoch - 1]["validation"],
"Selected classifier validation", 1e-6)
require(pre["selected_epoch"] == min(pre["epoch_history"], key=lambda value: value["validation"]["loss"])["epoch"],
"MLM selection was not validation-only")
close(pre["selected_validation"], epoch["validation"], "Selected MLM validation", 1e-6)
audit_mlm_rows(directory, pre)
for stage_dir, report in ((directory, pre), (directory / "finetune", fine)):
metadata = load(stage_dir / "model/history_config.json")
validate_model_config(metadata, profile, architecture)
require(sha(stage_dir / "model/model.safetensors") == report["model_sha256"], "Selected weights fingerprint differs")
if "model_config_sha256" in report:
require(report["model_config_sha256"] == sha(stage_dir / "model/history_config.json"), "Selected config fingerprint differs")
if "source_config_sha256" in report:
source_config = (source / "config.json" if stage_dir == directory
else directory / "model/history_config.json")
require(report["source_config_sha256"] == sha(source_config), "Source config fingerprint differs")
model = HierarchicalTransactionModel.from_pretrained(directory / "finetune/model", device="cpu").eval()
require(model.parameter_counts() == pre["parameters"], "Actual parameter counts differ from report")
require((model.transaction_encoder is model.context_encoder) == (architecture == "shared"), "Actual weight sharing differs")
for encoder in [model.transaction_encoder] + ([model.context_encoder] if architecture == "separate" else []):
if profile == "rotary":
require(encoder.embeddings.position_embeddings is None, "Rotary model retains learned positions")
for index, layer in enumerate(encoder.encoder.layer):
settings = layer.attention.self.rope
require(settings["rotary_dim"] == 8 and settings["base"] == (10000 if index < 2 else 160000)
and settings["factor"] == (1. if index < 2 else 4.)
and settings["original_context"] == (0 if index < 2 else 512), "Actual attention schedule differs")
tokenizer = load_tokenizer(directory / "finetune/model")
windows = tokenize_transactions(account_rows, tokenizer, 256)
measured_views = {}
for erased, view, filename, report_key in ((False, "causal", "test-predictions.jsonl", "test"),
(True, "erased", "test-erased-predictions.jsonl", "test_erased_history")):
saved = rows(directory / "finetune" / filename)
truth = saved_classification(saved, examples["test"])
close(fine[report_key], {key: value for key, value in truth.items() if key != "loss"}, f"Saved {view} metrics")
close(fine[report_key]["loss"], truth["loss"], f"Saved {view} probability loss", 1e-6)
generated = scratch / f"{name}-{view}.jsonl"
evaluate_accounts(model, examples["test"], windows, tokenizer, torch.device("cpu"),
batch_size=16, erase_history=erased, output=generated)
actual = rows(generated)
errors = []
for expected, observed in zip(saved, actual, strict=True):
require({k: v for k, v in expected.items() if k != "probability"}
== {k: v for k, v in observed.items() if k != "probability"}, "CPU prediction metadata differs")
errors.append(abs(expected["probability"] - observed["probability"]))
require(max(errors) <= 1e-5, "CPU checkpoint probabilities differ from saved MPS probabilities")
measured_views[view] = {"metrics_from_saved_probabilities": truth,
"cpu_reload_max_probability_error": max(errors), "cpu_predictions": str(generated),
"saved_prediction_sha256": sha(directory / "finetune" / filename), "cpu_prediction_sha256": sha(generated)}
predictions[(profile, architecture, view)] = np.array([row["probability"] for row in saved])
labels = np.array([example.label for example in examples["test"]])
delta = paired_auc_delta(labels, predictions[(profile, architecture, "causal")], predictions[(profile, architecture, "erased")])
table.append({"profile": profile, "architecture": architecture, "seed": 17,
"parameters": pre["parameters"], "pretraining_clipping": pre_clip, "finetuning_clipping": fine_clip,
"source_model_weights_sha256": sha(source / "model.safetensors"), "source_model_config_sha256": sha(source / "config.json"),
"pretrained_model_weights_sha256": sha(directory / "model/model.safetensors"),
"pretrained_model_config_sha256": sha(directory / "model/history_config.json"),
"finetuned_model_weights_sha256": sha(directory / "finetune/model/model.safetensors"),
"finetuned_model_config_sha256": sha(directory / "finetune/model/history_config.json"),
"mlm_validation_before": pre["initial_validation"]["loss"], "mlm_validation_after": pre["selected_validation"]["loss"],
"mlm_validation_loss_reduction": pre["initial_validation"]["loss"] - pre["selected_validation"]["loss"],
"classifier_train_loss_before": fine["train_before"]["loss"], "classifier_train_loss_after": fine["train_selected"]["loss"],
"classifier_train_loss_reduction": fine["train_before"]["loss"] - fine["train_selected"]["loss"],
"classifier_selected_epoch": fine["selected_epoch"], "account_views": measured_views, "history_auc_gain": delta,
"block_mlm_history_loss_reduction": pre["test"]["erased"]["loss"] - pre["test"]["causal"]["loss"],
"pretraining_elapsed_seconds": pre["elapsed_seconds"], "finetuning_elapsed_seconds": fine["elapsed_seconds"]})
for path in directory.rglob("*"):
if path.is_file():
tracked_files.add(path)
del model
print(json.dumps({"audited": name, "cpu_prediction_views": 2, "test_accounts": 54}), flush=True)
contrasts = {}
for profile in ("absolute", "rotary"):
contrasts[f"{profile}_shared_minus_separate"] = paired_auc_delta(labels,
predictions[(profile, "shared", "causal")], predictions[(profile, "separate", "causal")])
for architecture in ("separate", "shared"):
contrasts[f"{architecture}_rotary_minus_absolute"] = paired_auc_delta(labels,
predictions[("rotary", architecture, "causal")], predictions[("absolute", architecture, "causal")])
report = {"status": "passed", "completed_at": datetime.now(UTC).isoformat(), "device": "cpu",
"scope": "Independent immutable-source, local-gradient, selected-config/checkpoint, and CPU probability audit; no W&B server query",
"comparison_contract": contract, "block_source_binding": block_binding, "account_source_binding": account_binding,
"model_config_binding_scope": "Independent sidecar binds actual saved config files; original in-flight reports are unchanged",
"runs": table, "paired_auc_contrasts": contrasts,
"optimizer_updates": sum(row["pretraining_clipping"]["optimizer_updates"] + row["finetuning_clipping"]["optimizer_updates"] for row in table),
"cpu_predictions_verified": 4 * 2 * 54, "probability_absolute_tolerance": 1e-5,
"all_file_sha256": {str(path): sha(path) for path in sorted(tracked_files)},
"elapsed_seconds": time.monotonic() - started,
"limits": ["Four configurations, one seed, one block epoch and five fine-tuning epochs establish integration and fitting, not a powered positional or architecture advantage.",
"54 historical account FLAG proxies do not label individual transaction fraud or establish deployment performance.",
"The rotary adapter retains dense BERT attention and separate K/V projections; it does not reproduce DeepSeek V4.1 compression, sparse attention or 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/position-lightning"), show_default=True)
@click.option("--output", type=click.Path(path_type=Path), default=None)
def main(root, output):
"""Audit all four completed configurations using CPU only."""
report = audit(root, output)
click.echo(json.dumps({"status": report["status"], "optimizer_updates": report["optimizer_updates"],
"cpu_predictions_verified": report["cpu_predictions_verified"]}))
if __name__ == "__main__":
main()
|