"""Leakage-checked frozen-encoder probes for a user-supplied competition file. This module does not download a competition dataset or claim that a short masked language model smoke run establishes useful downstream performance. """ from __future__ import annotations import csv import hashlib import json from collections import Counter from pathlib import Path from typing import Any import numpy as np import torch from sklearn.linear_model import LogisticRegression from sklearn.metrics import ( accuracy_score, balanced_accuracy_score, confusion_matrix, f1_score, ) from sklearn.model_selection import GroupShuffleSplit, train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler def _get(cfg: Any, key: str, default: Any = None) -> Any: value = cfg for part in key.split("."): if value is None: return default value = value.get(part, default) if hasattr(value, "get") else getattr(value, part, default) return default if value is None else value def _load_rows(path: Path) -> list[dict[str, Any]]: suffix = path.suffix.lower() if suffix == ".csv": with path.open(newline="", encoding="utf-8-sig") as handle: return list(csv.DictReader(handle)) if suffix in {".jsonl", ".ndjson"}: with path.open(encoding="utf-8") as handle: rows = [json.loads(line) for line in handle if line.strip()] if not all(isinstance(row, dict) for row in rows): raise ValueError("Every JSONL record must be an object with raw transaction bytes and a label.") return rows if suffix == ".parquet": import pyarrow.parquet as pq return pq.read_table(path).to_pylist() raise ValueError("Competition input must be a .csv, .jsonl, .ndjson, or .parquet file.") def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _canonical_hex(value: Any, row_number: int) -> str: if not isinstance(value, str): raise ValueError(f"Row {row_number}: transaction bytes must be a hex string.") value = value.strip().lower() value = value[2:] if value.startswith("0x") else value if not value or len(value) % 2 or any(char not in "0123456789abcdef" for char in value): raise ValueError(f"Row {row_number}: transaction bytes must contain a nonempty, even number of hex digits.") return "0x" + value def _artifact_fingerprints(cfg: Any) -> dict[str, Any]: """Identify the local representation artifacts without copying their contents.""" model_dir = _get(cfg, "model.output_dir") tokenizer_dir = _get(cfg, "tokenizer.output_dir") candidates = { "model": (model_dir, [ "config.json", "model.safetensors", "training_report.json", "tokenizer.json", "byte_encoding.json", ]), "tokenizer": (tokenizer_dir, [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "byte_encoding.json", "report.json", ]), } files = { f"{section}/{name}": _sha256_file(Path(str(directory)) / name) for section, (directory, names) in candidates.items() if directory is not None for name in names if (Path(str(directory)) / name).is_file() } required = {"model/config.json", "model/model.safetensors", "tokenizer/tokenizer.json", "tokenizer/byte_encoding.json"} return { "status": "available" if required <= files.keys() else "incomplete_or_unavailable", "sha256": files, "missing_required_files": sorted(required - files.keys()), } def _pretraining_overlap_audit( cfg: Any, transactions: list[str], train: np.ndarray, test: np.ndarray ) -> dict[str, Any]: """Audit the configured corpus; reject exact test exposure to pretraining train.""" from eth_utils import keccak corpus_dir = _get(cfg, "data.output_dir") if corpus_dir is None: return {"status": "unavailable", "reason": "data.output_dir is not configured; pretraining overlap is unknown"} corpus_path = Path(str(corpus_dir)) / "transactions.jsonl" if not corpus_path.is_file(): return {"status": "unavailable", "reason": "Configured corpus has no transactions.jsonl; pretraining overlap is unknown"} digest = _sha256_file(corpus_path) corpus_hashes: dict[str, set[str]] = {split: set() for split in ("train", "validation", "test")} corpus_counts: Counter[str] = Counter() train_digest = hashlib.sha256() for row_number, row in enumerate(_load_rows(corpus_path), start=1): split = row.get("split") if split not in corpus_hashes: raise ValueError(f"Pretraining corpus row {row_number}: split must be train, validation, or test.") raw_hex = _canonical_hex(row.get("raw_hex"), row_number) raw = bytes.fromhex(raw_hex[2:]) tx_hash = "0x" + keccak(raw).hex() if row.get("tx_hash") and str(row["tx_hash"]).lower() != tx_hash: raise ValueError(f"Pretraining corpus row {row_number}: tx_hash differs from raw bytes; validate the corpus before benchmarking.") corpus_hashes[split].add(tx_hash) corpus_counts[split] += 1 if split == "train": train_digest.update(len(raw).to_bytes(8, "big")) train_digest.update(raw) if not corpus_counts["train"]: raise ValueError("Configured pretraining corpus has no train examples; overlap audit cannot establish a training reference.") train_corpus_sha256 = train_digest.hexdigest() tokenizer_dir = _get(cfg, "tokenizer.output_dir") tokenizer_metadata = Path(str(tokenizer_dir)) / "byte_encoding.json" if tokenizer_dir is not None else None tokenizer_match = None if tokenizer_metadata is not None and tokenizer_metadata.is_file(): expected = json.loads(tokenizer_metadata.read_text()).get("train_corpus_sha256") if expected is not None: tokenizer_match = expected == train_corpus_sha256 if not tokenizer_match: raise ValueError("Configured pretraining corpus differs from the tokenizer's recorded train corpus; select the matching corpus.") model_dir = _get(cfg, "model.output_dir") checkpoint_report = Path(str(model_dir)) / "training_report.json" if model_dir is not None else None checkpoint_match = None if checkpoint_report is not None and checkpoint_report.is_file(): expected = json.loads(checkpoint_report.read_text()).get("train_corpus_sha256") if expected is not None: checkpoint_match = expected == train_corpus_sha256 if not checkpoint_match: raise ValueError("Configured pretraining corpus differs from the checkpoint's recorded train corpus; select the matching corpus.") benchmark_hashes = ["0x" + keccak(bytes.fromhex(transaction[2:])).hex() for transaction in transactions] overlap = { name: { f"pretraining_{split}": sum(benchmark_hashes[index] in hashes for index in indices) for split, hashes in corpus_hashes.items() } for name, indices in (("benchmark_train", train), ("benchmark_test", test)) } exposed_test = overlap["benchmark_test"]["pretraining_train"] if exposed_test: raise ValueError( f"Benchmark test contains {exposed_test} transaction(s) from pretraining train. " "Supply clean held-out test transactions or retrain excluding them; this adapter does not allow transductive test exposure." ) if _sha256_file(corpus_path) != digest: raise ValueError("Pretraining corpus changed during overlap audit; rerun with stable artifacts.") return { "status": "checked", "file_name": corpus_path.name, "sha256": digest, "train_corpus_sha256": train_corpus_sha256, "corpus_rows": {split: corpus_counts[split] for split in corpus_hashes}, "overlap": overlap, "comparison": "Keccak-256 of canonical raw transaction bytes; declared corpus hashes are cross-checked when present", "policy": "Reject benchmark test overlap with pretraining train; report overlap with pretraining validation/test separately", "tokenizer_train_corpus_match": tokenizer_match, "checkpoint_train_corpus_match": checkpoint_match, "scope": "Configured local corpus only; absent checkpoint/tokenizer corpus digests cannot establish which data produced those artifacts", } def _prepare_rows( rows: list[dict[str, Any]], cfg: Any ) -> tuple[list[str], np.ndarray, np.ndarray | None]: if not rows: raise ValueError("Competition input is empty; provide labeled raw transaction bytes.") text_column = str(_get(cfg, "benchmark.text_column", "raw_hex")) label_column = str(_get(cfg, "benchmark.label_column", "label")) configured_group = _get(cfg, "benchmark.group_column") group_column = str(configured_group) if configured_group else ("sender" if "sender" in rows[0] else None) transactions: list[str] = [] labels: list[str] = [] groups: list[str] = [] seen: set[str] = set() for index, row in enumerate(rows, start=1): if text_column not in row or label_column not in row: raise ValueError(f"Row {index}: required columns are {text_column!r} and {label_column!r}.") transaction = _canonical_hex(row[text_column], index) if transaction in seen: raise ValueError(f"Row {index}: duplicate transaction bytes; remove duplicates before benchmarking.") seen.add(transaction) label = row[label_column] if label is None or (isinstance(label, float) and not np.isfinite(label)) or not str(label).strip(): raise ValueError(f"Row {index}: label is missing.") transactions.append(transaction) labels.append(str(label)) if group_column: group = row.get(group_column) if group is None or (isinstance(group, float) and not np.isfinite(group)) or not str(group).strip(): raise ValueError(f"Row {index}: group column {group_column!r} is missing.") # Ethereum address casing must not make the same sender two groups. groups.append(str(group).strip().lower()) return transactions, np.asarray(labels), np.asarray(groups) if group_column else None def _split_indices( rows: list[dict[str, Any]], labels: np.ndarray, groups: np.ndarray | None, cfg: Any ) -> tuple[np.ndarray, np.ndarray, str]: seed = int(_get(cfg, "benchmark.seed", 17)) fraction = float(_get(cfg, "benchmark.test_fraction", 0.25)) if not 0 < fraction < 1: raise ValueError("benchmark.test_fraction must be strictly between zero and one.") indices = np.arange(len(rows)) classes = set(labels.tolist()) if len(classes) < 2: raise ValueError("The benchmark requires at least two label classes.") split_column = _get(cfg, "benchmark.split_column") or ("split" if "split" in rows[0] else None) if split_column: split_values = [str(row.get(str(split_column), "")).strip().lower() for row in rows] if set(split_values) != {"train", "test"}: raise ValueError("The configured split column must contain exactly 'train' and 'test'; hold other splits out of this file.") train = indices[np.asarray(split_values) == "train"] test = indices[np.asarray(split_values) == "test"] strategy = "explicit train/test split" elif groups is None: try: train, test = train_test_split(indices, test_size=fraction, random_state=seed, stratify=labels) except ValueError as error: raise ValueError(f"Cannot make a stratified split; supply more examples per class or an explicit split: {error}") from error strategy = "stratified transaction-disjoint holdout" else: if len(set(groups.tolist())) < 2: raise ValueError("A group-disjoint benchmark needs at least two distinct groups.") # Candidate group splits are selected using only labels and group IDs, # before any embeddings or classifier are fit. Approximate stratification # is necessary because groups are indivisible and can mix labels. splitter = GroupShuffleSplit(n_splits=256, test_size=fraction, random_state=seed) target = np.asarray([np.mean(labels == label) for label in sorted(classes)]) candidates: list[tuple[float, np.ndarray, np.ndarray]] = [] for candidate_train, candidate_test in splitter.split(indices, labels, groups): if set(labels[candidate_train].tolist()) != classes or set(labels[candidate_test].tolist()) != classes: continue test_distribution = np.asarray([np.mean(labels[candidate_test] == label) for label in sorted(classes)]) train_distribution = np.asarray([np.mean(labels[candidate_train] == label) for label in sorted(classes)]) score = float(np.abs(test_distribution - target).sum() + np.abs(train_distribution - target).sum()) score += abs(len(candidate_test) / len(rows) - fraction) candidates.append((score, candidate_train, candidate_test)) if not candidates: raise ValueError("No class-complete group-disjoint split found; provide more independent groups per class or an explicit split.") _, train, test = min(candidates, key=lambda item: item[0]) strategy = "group-disjoint holdout with approximate label stratification (256 seeded candidates)" if groups is not None and set(groups[train].tolist()) & set(groups[test].tolist()): raise ValueError("Train and test groups overlap; provide account/group-disjoint splits.") if len(set(labels[train].tolist())) < 2 or len(set(labels[test].tolist())) < 2: raise ValueError("Both train and test must contain at least two classes.") unknown_test_labels = set(labels[test].tolist()) - set(labels[train].tolist()) if unknown_test_labels: raise ValueError("Test contains label classes absent from train.") return np.sort(train), np.sort(test), strategy def _metrics(truth: np.ndarray, predictions: np.ndarray, classes: list[str]) -> dict[str, Any]: return { "accuracy": float(accuracy_score(truth, predictions)), "balanced_accuracy": float(balanced_accuracy_score(truth, predictions)), "macro_f1": float(f1_score(truth, predictions, labels=classes, average="macro", zero_division=0)), "confusion_matrix": confusion_matrix(truth, predictions, labels=classes).tolist(), "classes": classes, "support": {label: int(np.sum(truth == label)) for label in classes}, } def _probe( features: np.ndarray, labels: np.ndarray, train: np.ndarray, test: np.ndarray, seed: int ) -> tuple[np.ndarray, dict[str, Any]]: # Scaling and logistic-regression fitting see only the training partition. classifier = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000, random_state=seed)) classifier.fit(features[train], labels[train]) predictions = classifier.predict(features[test]) return predictions, _metrics(labels[test], predictions, sorted(set(labels[train].tolist()))) def _load_encoders(cfg: Any, seed: int) -> tuple[Any, torch.nn.Module, torch.nn.Module]: from transformers import AutoModelForMaskedLM from evm_bert.tokenizer import load_tokenizer model_dir = Path(str(_get(cfg, "model.output_dir", "artifacts/model"))) if not (model_dir / "config.json").is_file(): raise FileNotFoundError("A pretrained model checkpoint is required; run `evm train` before the benchmark.") tokenizer_dir = Path(str(_get(cfg, "tokenizer.output_dir", "artifacts/tokenizer"))) for filename in ("tokenizer.json", "byte_encoding.json"): saved = model_dir / filename selected = tokenizer_dir / filename if saved.is_file() and (not selected.is_file() or _sha256_file(saved) != _sha256_file(selected)): raise ValueError(f"Selected tokenizer differs from the checkpoint's saved {filename}; use the matching tokenizer.") tokenizer = load_tokenizer(tokenizer_dir) pretrained = AutoModelForMaskedLM.from_pretrained(model_dir, local_files_only=True).base_model if pretrained.config.vocab_size != len(tokenizer) or pretrained.config.pad_token_id != tokenizer.pad_token_id: raise ValueError("Checkpoint vocabulary/padding configuration differs from the selected tokenizer.") with torch.random.fork_rng(devices=[]): torch.manual_seed(seed) random_encoder = AutoModelForMaskedLM.from_config(pretrained.config).base_model return tokenizer, pretrained, random_encoder @torch.inference_mode() def _extract_embeddings( model: torch.nn.Module, tokenizer: Any, transactions: list[str], cfg: Any ) -> np.ndarray: from evm_bert.tokenizer import encode_raw_hex max_length = int(_get(cfg, "model.max_length", 256)) batch_size = int(_get(cfg, "benchmark.batch_size", 16)) if max_length < 3 or max_length > model.config.max_position_embeddings: raise ValueError("model.max_length must be at least 3 and fit the saved model's position embeddings.") if batch_size < 1: raise ValueError("benchmark.batch_size must be positive.") vocabulary = tokenizer.get_vocab() special_ids = [vocabulary.get(token) for token in ("[CLS]", "[SEP]", "[PAD]")] if any(token_id is None for token_id in special_ids): raise ValueError("The tokenizer must define [CLS], [SEP], and [PAD].") cls_id, sep_id, pad_id = (int(token_id) for token_id in special_ids) model = model.cpu().eval() sums = np.zeros((len(transactions), model.config.hidden_size), dtype=np.float64) counts = np.zeros(len(transactions), dtype=np.int64) pending: list[tuple[int, list[int]]] = [] def consume() -> None: width = max(len(ids) + 2 for _, ids in pending) input_ids = torch.full((len(pending), width), pad_id, dtype=torch.long) attention_mask = torch.zeros_like(input_ids) content_mask = torch.zeros_like(input_ids) for position, (_, ids) in enumerate(pending): input_ids[position, : len(ids) + 2] = torch.tensor([cls_id, *ids, sep_id]) attention_mask[position, : len(ids) + 2] = 1 content_mask[position, 1 : len(ids) + 1] = 1 hidden = model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state window_sums = (hidden * content_mask.unsqueeze(-1)).sum(dim=1).double().numpy() for position, (transaction_index, ids) in enumerate(pending): sums[transaction_index] += window_sums[position] counts[transaction_index] += len(ids) pending.clear() for transaction_index, transaction in enumerate(transactions): ids = encode_raw_hex(tokenizer, transaction, add_special_tokens=False) if not ids: raise ValueError(f"Row {transaction_index + 1}: tokenizer returned no transaction tokens.") for start in range(0, len(ids), max_length - 2): pending.append((transaction_index, ids[start : start + max_length - 2])) if len(pending) == batch_size: consume() if pending: consume() features = (sums / counts[:, None]).astype(np.float32) if not np.isfinite(features).all(): raise ValueError("Encoder produced non-finite benchmark features.") return features def run_benchmark(cfg: Any) -> dict[str, Any]: """Run the local, frozen-encoder benchmark and save its auditable report. The user must supply their competition data. No synthetic fallback is used. """ input_value = _get(cfg, "benchmark.path") if not input_value or not Path(str(input_value)).is_file(): raise FileNotFoundError( "Competition data is not available. Run `evm benchmark --input PATH` after supplying a labeled CSV, JSONL, or Parquet file " "with raw_hex and label columns. Add sender/group IDs for account-disjoint evaluation." ) path = Path(str(input_value)) input_digest = _sha256_file(path) rows = _load_rows(path) transactions, labels, groups = _prepare_rows(rows, cfg) train, test, strategy = _split_indices(rows, labels, groups, cfg) artifact_fingerprints = _artifact_fingerprints(cfg) overlap_audit = _pretraining_overlap_audit(cfg, transactions, train, test) seed = int(_get(cfg, "benchmark.seed", 17)) tokenizer, pretrained, random_encoder = _load_encoders(cfg, seed) pretrained_features = _extract_embeddings(pretrained, tokenizer, transactions, cfg) random_features = _extract_embeddings(random_encoder, tokenizer, transactions, cfg) pretrained_predictions, pretrained_metrics = _probe(pretrained_features, labels, train, test, seed) random_predictions, random_metrics = _probe(random_features, labels, train, test, seed) classes = sorted(set(labels[train].tolist())) # Majority is selected from training labels, including deterministic tie-break. majority = min(classes, key=lambda label: (-int(np.sum(labels[train] == label)), label)) majority_predictions = np.full(len(test), majority) if _sha256_file(path) != input_digest: raise ValueError("Competition input changed during evaluation; rerun with a stable input file.") if _artifact_fingerprints(cfg) != artifact_fingerprints: raise ValueError("Checkpoint/tokenizer artifacts changed during evaluation; rerun with stable artifacts.") if overlap_audit["status"] == "checked": corpus_path = Path(str(_get(cfg, "data.output_dir"))) / "transactions.jsonl" if _sha256_file(corpus_path) != overlap_audit["sha256"]: raise ValueError("Pretraining corpus changed during evaluation; rerun with stable artifacts.") report = { "task": "frozen mean-pooled transaction encoder with a train-only logistic-regression probe", "input": { "file_name": path.name, "sha256": input_digest, "rows": len(rows), "prediction_row_index_base": 0, }, "seed": seed, "pretraining_overlap": overlap_audit, "artifact_fingerprints": artifact_fingerprints, "probe_configuration": { "scaler": "StandardScaler fit on benchmark train only", "classifier": "LogisticRegression", "C": 1.0, "max_iter": 1000, "hyperparameter_search": "none; fixed settings for both encoder baselines", }, "representation": { "encoder_parameters": sum(parameter.numel() for parameter in pretrained.parameters()), "pooling": "token-weighted mean across all non-overlapping transaction windows; excludes [CLS], [SEP], and padding", "max_window_length": int(_get(cfg, "model.max_length", 256)), "encoder_training": "frozen for both pretrained and independently seeded random-init baselines", }, "split": { "strategy": strategy, "train_rows": len(train), "test_rows": len(test), "train_class_counts": dict(Counter(labels[train].tolist())), "test_class_counts": dict(Counter(labels[test].tolist())), "duplicate_transactions": 0, "group_disjoint": groups is not None, "train_groups": len(set(groups[train].tolist())) if groups is not None else None, "test_groups": len(set(groups[test].tolist())) if groups is not None else None, }, "pretrained": pretrained_metrics, "random_init": random_metrics, "majority_baseline": {"training_majority_class": majority, **_metrics(labels[test], majority_predictions, classes)}, "evidence_limits": [ "A frozen-encoder probe is a downstream sanity check; a short pretraining run may provide no improvement over random initialization.", "Hex syntax and duplicate/group separation are checked here; competition provenance, label quality, and on-chain validity require separate verification.", "Hyperparameters are fixed before evaluation; during this benchmark no classifier, scaler, or encoder is fit on the test partition.", "The pretraining_overlap section states whether the configured local corpus was checked; missing corpus or artifact bindings leave exposure unknown.", "Exact transaction exclusion does not establish account-disjoint pretraining; competition rules must permit the earlier unlabeled corpus.", "When group IDs are absent, this establishes transaction separation only; related-account leakage remains possible.", ], } output_dir = Path(str(_get(cfg, "benchmark.output_dir", "artifacts/benchmark"))) output_dir.mkdir(parents=True, exist_ok=True) with (output_dir / "predictions.csv").open("w", newline="", encoding="utf-8") as handle: writer = csv.writer(handle) writer.writerow(["input_row_index", "label", "pretrained_prediction", "random_init_prediction", "majority_prediction"]) for index, pretrained_prediction, random_prediction in zip(test, pretrained_predictions, random_predictions, strict=True): writer.writerow([int(index), labels[index], pretrained_prediction, random_prediction, majority]) (output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") return report