somehowchris's picture
Upload verified EVM benchmark artifacts
0edf333 verified
Raw History Blame Contribute Delete
56.1 kB
"""Short, auditable BERT MLM training with local evidence and W&B metrics.""" import json import hashlib import math import random import time from datetime import UTC, datetime from pathlib import Path import torch from datasets import load_from_disk from omegaconf import OmegaConf from .model import build_model, config_value, parameter_count, load_mlm_model from .lightning_runtime import AuditedLightningModule, fit_audited from .tokenizer import corpus_digest, decode_raw_hex, encode_raw_hex, load_tokenizer def _write_json(path, value): Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") def _setup(config): seed = int(config_value(config, "training.seed", 17)) random.seed(seed) torch.manual_seed(seed) torch.set_num_threads(int(config_value(config, "training.num_threads", 4))) device = str(config_value(config, "training.device", "cpu")) if device == "auto": device = ( "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" ) return seed, torch.device(device) def transaction_windows(tokenizer, raw_hex, max_length): """Preserve all tokens while keeping windows inside a transaction and split.""" if max_length < 3: raise ValueError("model.max_length must allow two special tokens and a byte token") ids = encode_raw_hex(tokenizer, raw_hex, add_special_tokens=False) width = max_length - 2 return [ [tokenizer.cls_token_id, *ids[start : start + width], tokenizer.sep_token_id] for start in range(0, len(ids), width) ] def _windows(tokenizer, records, max_length): windows = [] token_count = long_transactions = 0 for raw_hex in records["raw_hex"]: parts = transaction_windows(tokenizer, raw_hex, max_length) windows.extend(parts) token_count += sum(len(part) - 2 for part in parts) long_transactions += len(parts) > 1 if not windows: raise ValueError("A nonempty transaction split is required") return windows, { "transactions": len(records), "windows": len(windows), "byte_bpe_tokens": token_count, "multi_window_transactions": long_transactions, "truncated_tokens": 0, "max_window_length": max(map(len, windows)), } def mask_batch(sequences, tokenizer, probability, generator): """BERT 80% MASK / 10% random / 10% unchanged; never supervise specials. At least one eligible target per sequence is selected, so short transactions cannot produce a NaN all-ignored loss. Random replacements exclude specials. """ if not 0 < probability <= 1: raise ValueError("training.mlm_probability must be in (0, 1]") length = max(map(len, sequences)) ids = torch.full((len(sequences), length), tokenizer.pad_token_id, dtype=torch.long) attention = torch.zeros_like(ids) for index, sequence in enumerate(sequences): ids[index, : len(sequence)] = torch.tensor(sequence) attention[index, : len(sequence)] = 1 eligible = attention.bool() for token_id in tokenizer.all_special_ids: eligible &= ids != token_id selected = (torch.rand(ids.shape, generator=generator) < probability) & eligible for index in range(len(sequences)): if not selected[index].any(): choices = eligible[index].nonzero().flatten() if not len(choices): raise ValueError("Cannot mask a sequence containing only special tokens") selected[index, choices[torch.randint(len(choices), (1,), generator=generator)]] = True labels = ids.clone() labels[~selected] = -100 replacement = torch.rand(ids.shape, generator=generator) ids[selected & (replacement < 0.8)] = tokenizer.mask_token_id random_positions = selected & (replacement >= 0.8) & (replacement < 0.9) normal_ids = torch.tensor( [index for index in range(len(tokenizer)) if index not in tokenizer.all_special_ids] ) random_ids = normal_ids[torch.randint(len(normal_ids), ids.shape, generator=generator)] ids[random_positions] = random_ids[random_positions] return {"input_ids": ids, "attention_mask": attention, "labels": labels} def _evaluate(model, windows, tokenizer, config, device, seed): generator = torch.Generator().manual_seed(seed) batch_size = int(config_value( config, "training.eval_batch_size", config_value(config, "training.batch_size", 8) )) eval_batches = int(config_value(config, "training.eval_batches", 4)) if batch_size < 1 or eval_batches < 1: raise ValueError("batch_size and eval_batches must be positive") order = torch.randperm(len(windows), generator=torch.Generator().manual_seed(seed)).tolist() if not config_value(config, "training.eval_all", False): order = order[: batch_size * eval_batches] total_loss = 0.0 target_count = correct = 0 model.eval() with torch.inference_mode(): for start in range(0, len(order), batch_size): batch = mask_batch( [windows[index] for index in order[start : start + batch_size]], tokenizer, float(config_value(config, "training.mlm_probability", 0.15)), generator, ) batch = {name: value.to(device) for name, value in batch.items()} output = model(**batch) target_mask = batch["labels"] != -100 targets = int(target_mask.sum().item()) total_loss += float(output.loss.item()) * targets target_count += targets correct += int( ((output.logits.argmax(-1) == batch["labels"]) & target_mask).sum().item() ) loss = total_loss / target_count if not math.isfinite(loss): raise RuntimeError("Evaluation loss is not finite") return { "loss": loss, "masked_accuracy": correct / target_count, "masked_perplexity": math.exp(min(loss, 50)), "masked_tokens": target_count, "windows": len(order), "mask_seed": seed, "perplexity_definition": "exp(mean cross-entropy on selected MLM targets); not autoregressive perplexity", } def _gradient_metrics(model): squares = {} for name, parameter in model.named_parameters(): if parameter.grad is None: continue if not torch.isfinite(parameter.grad).all(): raise RuntimeError(f"Nonfinite gradient in {name}") if name.startswith("bert.encoder.layer."): group = "layer_" + name.split(".")[3] elif name.startswith("bert.embeddings."): group = "embeddings" else: group = "mlm_head" squares[group] = squares.get(group, 0.0) + float( parameter.grad.detach().float().square().sum().item() ) metrics = {f"gradients/{name}_l2": math.sqrt(value) for name, value in squares.items()} metrics["gradients/global_l2"] = math.sqrt(sum(squares.values())) expected = [ "embeddings", "mlm_head", *[f"layer_{index}" for index in range(model.config.num_hidden_layers)], ] if any(metrics.get(f"gradients/{name}_l2", 0) <= 0 for name in expected): raise RuntimeError("An embedding, encoder layer, or MLM head received no nonzero gradient") return metrics def _load_inputs(config): corpus_root = Path(config_value(config, "data.output_dir", "data/transactions")) if (corpus_root / "manifest.json").exists(): from .data import validate_dataset validate_dataset(config) dataset = load_from_disk( str(corpus_root / "dataset") ) if "train" not in dataset or "validation" not in dataset: raise ValueError("Dataset must have disjoint train and validation splits") tokenizer = load_tokenizer(config) metadata = json.loads( ( Path(config_value(config, "tokenizer.output_dir", "artifacts/tokenizer")) / "byte_encoding.json" ).read_text() ) if metadata["train_corpus_sha256"] != corpus_digest(dataset["train"]): raise ValueError("Tokenizer was trained on a different training corpus; retrain it") if len(tokenizer) != int(config_value(config, "tokenizer.vocab_size", 8192)): raise ValueError("Configured vocabulary size differs from the saved tokenizer") max_length = int(config_value(config, "model.max_length", 256)) if max_length > int(config_value(config, "model.max_position_embeddings", 512)): raise ValueError("model.max_length exceeds model.max_position_embeddings") windows = {} coverage = {} for split, records in dataset.items(): windows[split], coverage[split] = _windows(tokenizer, records, max_length) return tokenizer, windows, coverage def train_mlm(config): """Keep the short step-based PoC; dispatch explicit epochs to the full trainer.""" if config_value(config, "training.epochs") is not None: return train_mlm_epochs(config) return _train_mlm_steps(config) def _train_mlm_steps(config): created_at = datetime.now(UTC).isoformat() if _accumulation_steps(config) != 1: raise ValueError("Explicit gradient accumulation requires training.epochs") if _drop_last(config): raise ValueError("Explicit drop_last requires training.epochs") seed, device = _setup(config) tokenizer, windows, coverage = _load_inputs(config) max_steps = int(config_value(config, "training.max_steps", 20)) batch_size = int(config_value(config, "training.batch_size", 8)) if max_steps < 1 or batch_size < 1: raise ValueError("max_steps and batch_size must be positive") output_dir = Path(config_value(config, "training.output_dir", "artifacts/training")) model_dir = Path(config_value(config, "model.output_dir", "artifacts/model")) output_dir.mkdir(parents=True, exist_ok=True) model_dir.mkdir(parents=True, exist_ok=True) resolved = ( OmegaConf.to_container(config, resolve=True) if OmegaConf.is_config(config) else config ) OmegaConf.save(OmegaConf.create(resolved), output_dir / "resolved_config.yaml") model = build_model(config).to(device) initial = { name: parameter.detach().cpu().clone() for name, parameter in model.named_parameters() } initial_eval = _evaluate(model, windows["validation"], tokenizer, config, device, seed + 10000) initial_train_eval = _evaluate(model, windows["train"], tokenizer, config, device, seed + 10001) optimizer = torch.optim.AdamW( model.parameters(), lr=float(config_value(config, "training.learning_rate", 5e-4)), weight_decay=float(config_value(config, "training.weight_decay", 0.01)), ) import wandb wandb_dir = Path(config_value(config, "logging.wandb_dir", "artifacts/wandb")) wandb_dir.mkdir(parents=True, exist_ok=True) mode = str(config_value(config, "logging.mode", "online")) if mode not in {"online", "offline", "disabled"}: raise ValueError("logging.mode must be online, offline, or disabled") entity = config_value(config, "logging.entity") if entity is None and mode == "online": viewer = wandb.Api().viewer entity = viewer.get("username") if isinstance(viewer, dict) else viewer.username if not entity: raise RuntimeError("Could not resolve the authenticated personal W&B entity") run = wandb.init( project=str(config_value(config, "logging.project", "evm-bert-poc")), entity=entity, dir=str(wandb_dir), mode=mode, config=resolved, job_type="masked-language-model-poc", ) started = time.monotonic() metrics = [] run_url = getattr(run, "url", None) if mode == "online" else None try: run.watch(model, log="all", log_freq=1) run.log( { "validation/initial_loss": initial_eval["loss"], "train/initial_fixed_mask_loss": initial_train_eval["loss"], }, step=0, ) generator = torch.Generator().manual_seed(seed + 1) order_generator = torch.Generator().manual_seed(seed + 2) order = [] with (output_dir / "metrics.jsonl").open("w") as log_file: def training_step(module, batch_index, _): nonlocal order step = int(batch_index) + 1 while len(order) < batch_size: order.extend( torch.randperm(len(windows["train"]), generator=order_generator).tolist() ) batch_indices, order = order[:batch_size], order[batch_size:] batch = mask_batch( [windows["train"][index] for index in batch_indices], tokenizer, float(config_value(config, "training.mlm_probability", 0.15)), generator, ) batch = {name: value.to(device) for name, value in batch.items()} model.train() module.begin_update() result = model(**batch) module.backward_loss(result.loss) row = { "step": step, "train/loss": float(result.loss.item()), **module.finish_update(_gradient_metrics), } row["train/masked_tokens"] = int((batch["labels"] != -100).sum().item()) row["elapsed_seconds"] = time.monotonic() - started log_file.write(json.dumps(row, allow_nan=False) + "\n") log_file.flush() run.log(row, step=step) metrics.append(row) lightning_module = AuditedLightningModule( model, optimizer, step_fn=training_step, max_norm=1.0 ) fit_audited( lightning_module, lambda _: range(max_steps), epochs=1, device=device, batches_per_epoch=max_steps, ) final_eval = _evaluate( model, windows["validation"], tokenizer, config, device, seed + 10000 ) final_train_eval = _evaluate( model, windows["train"], tokenizer, config, device, seed + 10001 ) changes = { name: float((parameter.detach().cpu() - initial[name]).double().square().sum().item()) for name, parameter in model.named_parameters() } delta = math.sqrt(sum(changes.values())) if not math.isfinite(delta) or delta <= 0: raise RuntimeError("Training did not change model parameters") model.eval() model.save_pretrained(str(model_dir), safe_serialization=True) tokenizer.save_pretrained(str(model_dir)) # Keep the byte contract beside the standard HF model/tokenizer files. byte_metadata = ( Path(config_value(config, "tokenizer.output_dir", "artifacts/tokenizer")) / "byte_encoding.json" ) (model_dir / "byte_encoding.json").write_bytes(byte_metadata.read_bytes()) probe = torch.tensor([windows["validation"][0]], device=device) with torch.inference_mode(): expected = ( model(input_ids=probe, attention_mask=torch.ones_like(probe)).logits.detach().cpu() ) reloaded = ( load_mlm_model(str(model_dir), local_files_only=True) .to(device) .eval() ) actual = ( reloaded(input_ids=probe, attention_mask=torch.ones_like(probe)) .logits.detach() .cpu() ) reload_error = float((expected - actual).abs().max().item()) if not torch.equal(expected, actual): raise RuntimeError(f"Checkpoint reload changed logits (max error {reload_error})") report = { "created_at": created_at, "completed_at": datetime.now(UTC).isoformat(), "task": "bert_masked_language_modeling", "parameters": parameter_count(model), "vocab_size": len(tokenizer), "train_corpus_sha256": json.loads(byte_metadata.read_text())["train_corpus_sha256"], "dataset_manifest_sha256": ( hashlib.sha256( (Path(config_value(config, "data.output_dir")) / "manifest.json").read_bytes() ).hexdigest() if (Path(config_value(config, "data.output_dir")) / "manifest.json").exists() else None ), "artifact_sha256": { name: hashlib.sha256((model_dir / name).read_bytes()).hexdigest() for name in ("model.safetensors", "config.json", "tokenizer.json", "byte_encoding.json") }, "steps": max_steps, "seed": seed, "device": str(device), "coverage": coverage, "validation_before": initial_eval, "validation_after": final_eval, "train_fixed_masks_before": initial_train_eval, "train_fixed_masks_after": final_train_eval, "parameter_delta_l2": delta, "changed_parameter_tensors": sum(value > 0 for value in changes.values()), "all_steps_finite_nonzero_layer_gradients": True, "gradient_steps": len(metrics), "lightning_runtime": lightning_module.runtime_report, "checkpoint_reload_identical_logits": True, "checkpoint_max_logit_error": reload_error, "tied_embeddings": model.get_input_embeddings().weight.data_ptr() == model.get_output_embeddings().weight.data_ptr(), "elapsed_seconds": time.monotonic() - started, "wandb": {"mode": mode, "entity": entity, "run_id": run.id, "url": run_url}, "evaluation_scope": "Fixed validation masks; test split is reserved for final evaluation.", "limitation": "A short pipeline smoke test, not evidence of downstream competition performance.", } _write_json(output_dir / "report.json", report) _write_json(model_dir / "training_report.json", report) (model_dir / "README.md").write_text( "---\nlibrary_name: transformers\npipeline_tag: fill-mask\ntags:\n- ethereum\n- bert\n- masked-language-modeling\n---\n\n" "# Ethereum transaction byte BERT PoC\n\n" f"Standard BERT MLM with {report['parameters']:,} tied parameters and " f"{len(tokenizer):,} byte-BPE tokens. Trained for {max_steps} optimizer steps.\n\n" "Map each raw byte b to `chr(0xE000+b)` before tokenization; use " "`evm_bert.tokenizer.encode_raw_hex` and `decode_raw_hex`. Raw hexadecimal " "text passed directly to a fill-mask pipeline has the wrong input encoding.\n\n" "Training uses dynamic 15% token masking with BERT's 80/10/10 replacement " "rule (or the configured probability); padding and specials never become targets. " "At least one token per window is selected. Long transactions are split into " "windows with no discarded tokens. This is bidirectional masked modeling, " "not a transaction generator.\n\n" "This short run demonstrates finite nonzero gradients, parameter updates, " "fixed-mask evaluation, and identical logits after checkpoint reload. " "It establishes no fraud-detection, security, or competition accuracy claim. " "See `training_report.json` for measured results and provenance.\n" ) run.log( { "validation/final_loss": final_eval["loss"], "validation/masked_accuracy": final_eval["masked_accuracy"], "train/final_fixed_mask_loss": final_train_eval["loss"], "parameters/delta_l2": delta, }, step=max_steps + 1, ) run.summary.update( { "parameters": report["parameters"], "checkpoint_reload_identical_logits": True, "all_steps_finite_nonzero_layer_gradients": True, } ) return report finally: run.finish() def _parameter_digest(model): digest = hashlib.sha256() for name, parameter in model.named_parameters(): digest.update(name.encode()) digest.update(parameter.detach().cpu().contiguous().numpy().tobytes()) return digest.hexdigest() def _epoch_batches(size, batch_size, generator): """One shuffled, complete pass, retaining the final partial batch.""" if size < 1 or batch_size < 1: raise ValueError("Dataset and batch_size must be positive") order = torch.randperm(size, generator=generator).tolist() return [order[start : start + batch_size] for start in range(0, size, batch_size)] def _accumulation_steps(config): value = config_value(config, "training.gradient_accumulation_steps", 1) if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError("training.gradient_accumulation_steps must be a positive integer") return value def _masked_batch_digest(batch): """Bind the exact CPU corruption/targets and padding without consuming RNG.""" digest = hashlib.sha256() for name in ("input_ids", "labels", "attention_mask"): tensor = batch[name].detach().cpu().contiguous() digest.update(name.encode()) digest.update(str((tuple(tensor.shape), tensor.dtype)).encode()) digest.update(tensor.numpy().tobytes()) return digest.hexdigest() def _drop_last(config): value = config_value(config, "training.drop_last", False) if not isinstance(value, bool): raise ValueError("training.drop_last must be a boolean") return value def _index_digest(indices): return hashlib.sha256(torch.tensor(indices, dtype=torch.int64).numpy().tobytes()).hexdigest() def _batch_call_counts(size, effective_size, physical_size, micro_size, *, drop_last=False): sizes = [min(effective_size, size - start) for start in range(0, size, effective_size)] if drop_last: sizes = [count for count in sizes if count == effective_size] if not sizes: raise ValueError("training.drop_last leaves no complete effective optimizer batch") return { "optimizer_steps": len(sizes), "available_windows": size, "used_windows": sum(sizes), "omitted_windows": size - sum(sizes), "physical_batches": sum(math.ceil(count / physical_size) for count in sizes), "forward_backward_calls": sum(math.ceil(count / micro_size) for count in sizes), "last_effective_batch_size": sizes[-1], "last_physical_batches": math.ceil(sizes[-1] / physical_size), "last_forward_backward_calls": math.ceil(sizes[-1] / micro_size), } def _backward_effective_batch(model, batch, micro_batch_size, device, *, backward_fn=None): """Accumulate the selected-token mean loss, including unequal target counts. The caller masks an entire effective batch first. Splitting the tensor only bounds peak memory; every selected token has weight 1 / total_targets. """ if micro_batch_size < 1: raise ValueError("training.micro_batch_size must be positive") total_targets = int((batch["labels"] != -100).sum().item()) if not total_targets: raise ValueError("An effective batch must contain masked targets") total_loss = 0.0 for start in range(0, len(batch["input_ids"]), micro_batch_size): micro = { name: value[start : start + micro_batch_size].to(device) for name, value in batch.items() } targets = int((micro["labels"] != -100).sum().item()) output = model(**micro) if not torch.isfinite(output.loss): raise RuntimeError("Nonfinite training loss") weight = targets / total_targets weighted_loss = output.loss * weight if backward_fn is None: weighted_loss.backward() # Low-level gradient-equivalence utility; training supplies Lightning. else: backward_fn(weighted_loss) total_loss += float(output.loss.detach().item()) * weight return total_loss, total_targets def _rng_state(device): state = {"torch": torch.get_rng_state(), "python": random.getstate()} if device.type == "cuda": state["cuda"] = torch.cuda.get_rng_state_all() elif device.type == "mps": state["mps"] = torch.mps.get_rng_state() return state def _restore_rng(state, device): torch.set_rng_state(state["torch"]) random.setstate(state["python"]) if device.type == "cuda": torch.cuda.set_rng_state_all(state["cuda"]) elif device.type == "mps": torch.mps.set_rng_state(state["mps"]) def _save_mlm_artifact(model, tokenizer, config, probe_window, device): model_dir = Path(config_value(config, "model.output_dir", "artifacts/model")) model_dir.mkdir(parents=True, exist_ok=True) model.eval() model.save_pretrained(str(model_dir), safe_serialization=True) tokenizer.save_pretrained(str(model_dir)) metadata_path = ( Path(config_value(config, "tokenizer.output_dir", "artifacts/tokenizer")) / "byte_encoding.json" ) (model_dir / "byte_encoding.json").write_bytes(metadata_path.read_bytes()) probe = torch.tensor([probe_window], device=device) with torch.inference_mode(): expected = model(input_ids=probe, attention_mask=torch.ones_like(probe)).logits.cpu() reloaded = load_mlm_model( str(model_dir), local_files_only=True ).to(device).eval() actual = reloaded(input_ids=probe, attention_mask=torch.ones_like(probe)).logits.cpu() error = float((expected - actual).abs().max().item()) if not torch.equal(expected, actual): raise RuntimeError(f"Checkpoint reload changed logits (max error {error})") return { "checkpoint_reload_identical_logits": True, "checkpoint_max_logit_error": error, "artifact_sha256": { name: hashlib.sha256((model_dir / name).read_bytes()).hexdigest() for name in ("model.safetensors", "config.json", "tokenizer.json", "byte_encoding.json") }, } def train_mlm_epochs(config): """Train randomly initialized BERT for complete epochs with resumable evidence. Checkpoints are trusted local PyTorch files and contain optimizer, RNG and shuffle/mask generator state. Resume is exact at a completed epoch boundary, on the same device/backend and configuration; no within-epoch work is claimed. """ seed, device = _setup(config) epochs = int(config_value(config, "training.epochs", 20)) batch_size = int(config_value(config, "training.batch_size", 256)) micro_batch_size = int(config_value(config, "training.micro_batch_size", batch_size)) accumulation_steps = _accumulation_steps(config) drop_last = _drop_last(config) effective_batch_size = batch_size * accumulation_steps if accumulation_steps > 1 and micro_batch_size > batch_size: raise ValueError("With gradient accumulation, micro_batch_size cannot exceed physical batch_size") if min(epochs, batch_size, micro_batch_size) < 1: raise ValueError("epochs, batch_size and micro_batch_size must be positive") tokenizer, windows, coverage = _load_inputs(config) call_counts = _batch_call_counts( len(windows["train"]), effective_batch_size, batch_size, micro_batch_size, drop_last=drop_last ) output_dir = Path(config_value(config, "training.output_dir", "artifacts/pretraining")) model_dir = Path(config_value(config, "model.output_dir", "artifacts/pretrained-model")) checkpoint_dir = output_dir / "checkpoints" output_dir.mkdir(parents=True, exist_ok=True) checkpoint_dir.mkdir(exist_ok=True) resolved = ( OmegaConf.to_container(config, resolve=True) if OmegaConf.is_config(config) else config ) resume_path = config_value(config, "training.resume_from") metrics_path = output_dir / "metrics.jsonl" if metrics_path.exists() and not resume_path: raise ValueError("Training output already exists; set training.resume_from or a new output_dir") OmegaConf.save(OmegaConf.create(resolved), output_dir / "resolved_config.yaml") metadata_path = ( Path(config_value(config, "tokenizer.output_dir", "artifacts/tokenizer")) / "byte_encoding.json" ) metadata = json.loads(metadata_path.read_text()) manifest = Path(config_value(config, "data.output_dir")) / "manifest.json" model = build_model(config).to(device) # Deliberately starts from random weights. initial = { name: parameter.detach().cpu().clone() for name, parameter in model.named_parameters() } initial_parameter_sha256 = _parameter_digest(model) learning_rate = float(config_value(config, "training.learning_rate", 1e-4)) weight_decay = float(config_value(config, "training.weight_decay", 0.01)) optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay) binding = { "train_corpus_sha256": metadata["train_corpus_sha256"], "dataset_manifest_sha256": hashlib.sha256(manifest.read_bytes()).hexdigest() if manifest.exists() else None, "tokenizer_sha256": hashlib.sha256( (metadata_path.parent / "tokenizer.json").read_bytes() ).hexdigest(), "architecture": model.config.to_dict(), "coverage": coverage, "batch_size": batch_size, "micro_batch_size": micro_batch_size, "learning_rate": learning_rate, "weight_decay": weight_decay, "mlm_probability": float(config_value(config, "training.mlm_probability", 0.15)), "eval_batch_size": int(config_value(config, "training.eval_batch_size", batch_size)), "eval_batches": int(config_value(config, "training.eval_batches", 4)), "eval_all": bool(config_value(config, "training.eval_all", False)), "seed": seed, "device": str(device), "torch_version": torch.__version__, "num_threads": torch.get_num_threads(), } # Omit the default to preserve source-bound legacy epoch checkpoints. if accumulation_steps != 1: binding["gradient_accumulation_steps"] = accumulation_steps binding["effective_batch_size"] = effective_batch_size if drop_last: binding["drop_last"] = True binding_sha256 = hashlib.sha256(json.dumps(binding, sort_keys=True).encode()).hexdigest() generator = torch.Generator().manual_seed(seed + 1) order_generator = torch.Generator().manual_seed(seed + 2) completed_epochs = global_step = windows_seen = masked_tokens_seen = 0 forward_backward_calls_seen = physical_batches_seen = 0 history = [] prior_elapsed = 0.0 created_at = datetime.now(UTC).isoformat() restored = None if resume_path: # Only load locally generated checkpoints, never an untrusted downloaded pickle. restored = torch.load(str(resume_path), map_location="cpu", weights_only=False) if restored["binding_sha256"] != binding_sha256: raise ValueError("Resume checkpoint corpus, model, optimizer or training configuration differs") model.load_state_dict(restored["model"]) optimizer.load_state_dict(restored["optimizer"]) completed_epochs = restored["completed_epochs"] if completed_epochs > epochs: raise ValueError("Checkpoint already exceeds the requested epoch count") global_step = restored["global_step"] windows_seen = restored["windows_seen"] masked_tokens_seen = restored["masked_tokens_seen"] forward_backward_calls_seen = restored.get( "forward_backward_calls_seen", completed_epochs * call_counts["forward_backward_calls"] ) physical_batches_seen = restored.get( "physical_batches_seen", completed_epochs * call_counts["physical_batches"] ) history = restored["epoch_history"] initial = restored["initial_parameters"] initial_parameter_sha256 = restored["initial_parameter_sha256"] initial_eval = restored["validation_before"] initial_train_eval = restored["train_fixed_masks_before"] prior_elapsed = restored["elapsed_seconds"] created_at = restored["created_at"] generator.set_state(restored["mask_generator"]) order_generator.set_state(restored["order_generator"]) # Discard rows from an interrupted, uncheckpointed epoch before replaying it. if metrics_path.exists(): rows = [json.loads(line) for line in metrics_path.read_text().splitlines()] metrics_path.write_text("".join( json.dumps(row, allow_nan=False) + "\n" for row in rows if row["step"] <= global_step )) else: initial_eval = _evaluate(model, windows["validation"], tokenizer, config, device, seed + 10000) initial_train_eval = _evaluate(model, windows["train"], tokenizer, config, device, seed + 10001) import wandb wandb_dir = Path(config_value(config, "logging.wandb_dir", "artifacts/wandb")) wandb_dir.mkdir(parents=True, exist_ok=True) mode = str(config_value(config, "logging.mode", "online")) if mode not in {"online", "offline", "disabled"}: raise ValueError("logging.mode must be online, offline, or disabled") entity = config_value(config, "logging.entity") if entity is None and mode == "online": viewer = wandb.Api().viewer entity = viewer.get("username") if isinstance(viewer, dict) else viewer.username if not entity: raise RuntimeError("Could not resolve the authenticated personal W&B entity") resume_wandb = restored and mode == "online" and restored["wandb"]["mode"] == "online" run = wandb.init( project=str(config_value(config, "logging.project", "evm-bert-poc")), entity=entity, dir=str(wandb_dir), mode=mode, config=resolved, job_type="masked-language-model-pretraining", **({"id": restored["wandb"]["run_id"], "resume": "must"} if resume_wandb else {}), ) tracked = { "mode": mode, "entity": entity, "run_id": run.id, "url": getattr(run, "url", None) if mode == "online" else None, } started = time.monotonic() try: run.watch(model, log="all", log_freq=int(config_value(config, "logging.watch_log_freq", 100))) if restored: _restore_rng(restored["rng"], device) else: run.log({"validation/initial_loss": initial_eval["loss"]}, step=0) with metrics_path.open("a" if restored else "w") as log_file: first_epoch = completed_epochs state = {} def epoch_start(module): epoch = first_epoch + module.current_epoch + 1 all_batches = _epoch_batches(len(windows["train"]), effective_batch_size, order_generator) batches = ([batch for batch in all_batches if len(batch) == effective_batch_size] if drop_last else all_batches) full_order = [index for batch in all_batches for index in batch] used_order = [index for batch in batches for index in batch] omitted_order = full_order[len(used_order):] state.update(epoch=epoch, batches=batches, loss=0.0, targets=0, windows=0, backward_calls=0, physical_batches=0, omitted_order=omitted_order) state["order_sha256"] = _index_digest(full_order) state["used_window_indices_sha256"] = _index_digest(used_order) state["omitted_window_indices_sha256"] = _index_digest(omitted_order) def training_step(module, batch_index, _): nonlocal global_step, windows_seen, masked_tokens_seen nonlocal forward_backward_calls_seen, physical_batches_seen indices = state["batches"][int(batch_index)] batch = mask_batch( [windows["train"][index] for index in indices], tokenizer, binding["mlm_probability"], generator, ) batch_sha256 = _masked_batch_digest(batch) if accumulation_steps != 1 or drop_last else None backward_calls = math.ceil(len(indices) / micro_batch_size) physical_batches = math.ceil(len(indices) / batch_size) model.train() backward_calls_before = module.runtime_report["backward_calls"] module.begin_update() loss, targets = _backward_effective_batch( model, batch, micro_batch_size, device, backward_fn=module.backward_loss ) gradients = module.finish_update(_gradient_metrics) actual_backward_calls = module.runtime_report["backward_calls"] - backward_calls_before if actual_backward_calls != backward_calls: raise RuntimeError("Actual Lightning backward calls differ from the accumulation plan") global_step += 1 windows_seen += len(indices) masked_tokens_seen += targets forward_backward_calls_seen += backward_calls physical_batches_seen += physical_batches state["backward_calls"] += backward_calls state["physical_batches"] += physical_batches state["targets"] += targets state["windows"] += len(indices) state["loss"] += loss * targets row = { "step": global_step, "epoch": state["epoch"], "train/loss": loss, "train/effective_batch_size": len(indices), "train/micro_batch_size": min(micro_batch_size, len(indices)), "train/masked_tokens": targets, "train/windows_seen": windows_seen, "train/learning_rate": learning_rate, **gradients, "elapsed_seconds": prior_elapsed + time.monotonic() - started, } if accumulation_steps != 1 or drop_last: row.update({ "train/physical_batch_size": min(batch_size, len(indices)), "train/physical_batches": physical_batches, "train/backward_calls": backward_calls, "train/gradient_accumulation_steps": accumulation_steps, "train/partial_accumulation_group": int(len(indices) < effective_batch_size), "train/masked_batch_sha256": batch_sha256, }) log_file.write(json.dumps(row, allow_nan=False) + "\n") log_file.flush() run.log(row) def epoch_end(module): nonlocal completed_epochs epoch = state["epoch"] batches = state["batches"] order_sha256 = state["order_sha256"] if state["windows"] != call_counts["used_windows"]: raise RuntimeError("An epoch did not expose every window required by its drop_last policy") validation = _evaluate( model, windows["validation"], tokenizer, config, device, seed + 10000 ) epoch_row = { "epoch": epoch, "optimizer_steps": len(batches), "windows": state["windows"], "masked_tokens": state["targets"], "physical_batches": state["physical_batches"], "forward_backward_calls": state["backward_calls"], "last_effective_batch_size": len(batches[-1]), "last_group_physical_batches": math.ceil(len(batches[-1]) / batch_size), "last_group_backward_calls": math.ceil(len(batches[-1]) / micro_batch_size), "train_loss": state["loss"] / state["targets"], "validation": validation, "order_sha256": order_sha256, "full_order_sha256": order_sha256, "available_windows": len(windows["train"]), "omitted_windows": len(state["omitted_order"]), "omitted_window_indices": state["omitted_order"], "used_window_indices_sha256": state["used_window_indices_sha256"], "omitted_window_indices_sha256": state["omitted_window_indices_sha256"], "drop_last": drop_last, "parameter_sha256": _parameter_digest(model), } history.append(epoch_row) completed_epochs = epoch run.log({"epoch": epoch, "validation/loss": validation["loss"], "validation/masked_accuracy": validation["masked_accuracy"], "train/epoch_loss": epoch_row["train_loss"]}) checkpoint_path = checkpoint_dir / f"epoch-{epoch:03d}.pt" temporary = checkpoint_path.with_suffix(".tmp") torch.save({ "format_version": 1, "binding_sha256": binding_sha256, "binding": binding, "created_at": created_at, "completed_epochs": completed_epochs, "next_epoch": epoch + 1, "next_window_offset": 0, "global_step": global_step, "windows_seen": windows_seen, "masked_tokens_seen": masked_tokens_seen, "forward_backward_calls_seen": forward_backward_calls_seen, "physical_batches_seen": physical_batches_seen, "omitted_window_exposures": completed_epochs * call_counts["omitted_windows"], "model": {name: tensor.detach().cpu() for name, tensor in model.state_dict().items()}, "optimizer": optimizer.state_dict(), "rng": _rng_state(device), "mask_generator": generator.get_state(), "order_generator": order_generator.get_state(), "initial_parameters": initial, "initial_parameter_sha256": initial_parameter_sha256, "validation_before": initial_eval, "train_fixed_masks_before": initial_train_eval, "epoch_history": history, "wandb": tracked, "elapsed_seconds": prior_elapsed + time.monotonic() - started, }, temporary) temporary.replace(checkpoint_path) _write_json(output_dir / "progress.json", { "completed_epochs": completed_epochs, "requested_epochs": epochs, "steps": global_step, "windows_seen": windows_seen, "validation": validation, "latest_checkpoint": str(checkpoint_path), "elapsed_seconds": prior_elapsed + time.monotonic() - started, "wandb": tracked, }) lightning_module = AuditedLightningModule( model, optimizer, step_fn=training_step, epoch_start_fn=epoch_start, epoch_end_fn=epoch_end, max_norm=1.0, ) if epochs > first_epoch: fit_audited( lightning_module, lambda _: range(call_counts["optimizer_steps"]), epochs=epochs - first_epoch, device=device, batches_per_epoch=call_counts["optimizer_steps"], ) final_eval = history[-1]["validation"] final_train_eval = _evaluate( model, windows["train"], tokenizer, config, device, seed + 10001 ) changes = { name: float((parameter.detach().cpu() - initial[name]).double().square().sum().item()) for name, parameter in model.named_parameters() } delta = math.sqrt(sum(changes.values())) if not math.isfinite(delta) or delta <= 0: raise RuntimeError("Training did not change model parameters") report = { "created_at": created_at, "completed_at": datetime.now(UTC).isoformat(), "task": "bert_masked_language_modeling", "initialization": "random", "parameters": parameter_count(model), "vocab_size": len(tokenizer), **{key: binding[key] for key in ("train_corpus_sha256", "dataset_manifest_sha256")}, "training_binding_sha256": binding_sha256, "initial_parameter_sha256": initial_parameter_sha256, "final_parameter_sha256": _parameter_digest(model), "epochs": completed_epochs, "requested_epochs": epochs, "steps": global_step, "optimizer": "AdamW", "learning_rate": learning_rate, "weight_decay": weight_decay, "batch_size": batch_size, "micro_batch_size": micro_batch_size, "physical_batch_size": batch_size, "gradient_accumulation_steps": accumulation_steps, "drop_last": drop_last, "drop_last_unit": "incomplete effective optimizer accumulation group", "available_windows_per_epoch": call_counts["available_windows"], "used_windows_per_epoch": call_counts["used_windows"], "omitted_windows_per_epoch": call_counts["omitted_windows"], "omitted_window_exposures": completed_epochs * call_counts["omitted_windows"], "omission_policy": "tail of a new full training-window shuffle each epoch", "effective_batch_size": effective_batch_size, "physical_batches_seen": physical_batches_seen, "forward_backward_calls": forward_backward_calls_seen, "forward_calls": forward_backward_calls_seen, "forward_backward_call_count_scope": "training microbatches only; evaluation forwards excluded", "optimizer_updates_per_epoch": call_counts["optimizer_steps"], "physical_batches_per_epoch": call_counts["physical_batches"], "forward_backward_calls_per_epoch": call_counts["forward_backward_calls"], "last_effective_batch_size": call_counts["last_effective_batch_size"], "last_accumulation_group_physical_batches": call_counts["last_physical_batches"], "last_accumulation_group_backward_calls": call_counts["last_forward_backward_calls"], "last_accumulation_group_partial": call_counts["last_effective_batch_size"] < effective_batch_size, "accumulation_loss_weighting": "selected MLM tokens / selected tokens in effective batch", "last_batch_size": min(batch_size, call_counts["last_effective_batch_size"]), "windows_seen": windows_seen, "masked_tokens_seen": masked_tokens_seen, "all_epochs_complete_no_dropped_windows": windows_seen == epochs * len(windows["train"]), "all_epochs_complete_under_drop_last_policy": windows_seen == epochs * call_counts["used_windows"], "seed": seed, "device": str(device), "coverage": coverage, "validation_before": initial_eval, "validation_after": final_eval, "train_fixed_masks_before": initial_train_eval, "train_fixed_masks_after": final_train_eval, "epoch_history": history, "parameter_delta_l2": delta, "changed_parameter_tensors": sum(value > 0 for value in changes.values()), "all_steps_finite_nonzero_layer_gradients": True, "gradient_steps": global_step, "lightning_runtime": {"scope": "current invocation; legacy checkpoints and counters retained", **lightning_module.runtime_report}, "tied_embeddings": model.get_input_embeddings().weight.data_ptr() == model.get_output_embeddings().weight.data_ptr(), "elapsed_seconds": prior_elapsed + time.monotonic() - started, "wandb": tracked, "evaluation_scope": "Fixed validation masks each epoch; test reserved for final evaluation.", "limitation": "MLM learning is distinct from transfer or fraud detection; evaluate the downstream task separately.", **_save_mlm_artifact(model, tokenizer, config, windows["validation"][0], device), } _write_json(output_dir / "report.json", report) _write_json(model_dir / "training_report.json", report) (model_dir / "README.md").write_text( "---\nlibrary_name: transformers\npipeline_tag: fill-mask\ntags:\n- ethereum\n- bert\n- masked-language-modeling\n---\n\n" "# EVM transaction byte BERT\n\n" f"Standard BERT MLM with {report['parameters']:,} tied parameters and {len(tokenizer):,} " f"byte-BPE tokens, initialized randomly and trained for {completed_epochs} complete epochs " f"({global_step:,} AdamW updates, learning rate {learning_rate}, physical batch size {batch_size}, " f"gradient accumulation {accumulation_steps}, effective batch size {effective_batch_size}, " f"drop_last={drop_last}).\n\n" f"Each epoch uses {call_counts['used_windows']:,} of {len(windows['train']):,} training windows; " f"the final incomplete accumulation group omits {call_counts['omitted_windows']:,} windows " "from that epoch's full shuffle.\n\n" "Map byte b to `chr(0xE000+b)` before tokenization; use " "`evm_bert.tokenizer.encode_raw_hex`. Raw hexadecimal text directly passed to a fill-mask " "pipeline has the wrong encoding. Long transactions are windowed without truncation. " "Dynamic BERT 80/10/10 masking supervises 15% of eligible tokens (at least one per window).\n\n" "Validation uses identical fixed masks each epoch. Every update records finite, nonzero " "embedding, encoder-layer and MLM-head gradients. Epoch checkpoints contain optimizer and " "RNG states. See `training_report.json` for corpus/checkpoint hashes, coverage and measured " "losses. This bidirectional model does not generate transactions; MLM learning alone " "establishes no fraud-detection performance.\n" ) run.summary.update({ "epochs_completed": completed_epochs, "optimizer_steps": global_step, "windows_seen": windows_seen, "validation_final_loss": final_eval["loss"], "parameter_delta_l2": delta, "all_epochs_complete_no_dropped_windows": report["all_epochs_complete_no_dropped_windows"], "all_epochs_complete_under_drop_last_policy": report["all_epochs_complete_under_drop_last_policy"], "drop_last": drop_last, "physical_batch_size": batch_size, "gradient_accumulation_steps": accumulation_steps, "effective_batch_size": effective_batch_size, "used_windows_per_epoch": call_counts["used_windows"], "omitted_windows_per_epoch": call_counts["omitted_windows"], "omitted_window_exposures": completed_epochs * call_counts["omitted_windows"], "forward_backward_calls": forward_backward_calls_seen, "checkpoint_reload_identical_logits": True, }) return report finally: run.finish() def evaluate_mlm(config): """Evaluate the trained checkpoint on the untouched test split with fixed masks.""" seed, device = _setup(config) tokenizer, windows, coverage = _load_inputs(config) if "test" not in windows: raise ValueError("A held-out test split is required for final evaluation") model_dir = Path(config_value(config, "model.output_dir", "artifacts/model")) model = load_mlm_model(str(model_dir), local_files_only=True).to(device).eval() report = { "split": "test", "checkpoint_sha256": hashlib.sha256((model_dir / "model.safetensors").read_bytes()).hexdigest(), "coverage": coverage["test"], **_evaluate(model, windows["test"], tokenizer, config, device, seed + 20000), } output_dir = Path(config_value(config, "training.output_dir", "artifacts/training")) output_dir.mkdir(parents=True, exist_ok=True) _write_json(output_dir / "evaluation.json", report) training_report = output_dir / "report.json" if str(config_value(config, "logging.mode", "online")) == "online" and training_report.exists(): import wandb previous = json.loads(training_report.read_text()) tracked = previous.get("wandb", {}) if tracked.get("mode") == "online" and tracked.get("run_id"): with wandb.init(project=str(config_value(config, "logging.project", "evm-bert-poc")), entity=tracked["entity"], id=tracked["run_id"], resume="must", dir=str(config_value(config, "logging.wandb_dir", "artifacts/wandb")), job_type="heldout-evaluation") as run: run.log({"test/loss": report["loss"], "test/masked_accuracy": report["masked_accuracy"], "test/masked_tokens": report["masked_tokens"], "test/windows": report["windows"]}) run.summary["test_checkpoint_sha256"] = report["checkpoint_sha256"] return report def predict_mask(config, raw_hex, mask_index=None, top_k=5): """Mask one BPE token and return byte-span predictions from the saved model.""" _, device = _setup(config) tokenizer = load_tokenizer(config) model = ( load_mlm_model( str(config_value(config, "model.output_dir", "artifacts/model")), local_files_only=True ) .to(device) .eval() ) ids = encode_raw_hex(tokenizer, raw_hex, add_special_tokens=False) width = int(config_value(config, "model.max_length", 256)) - 2 if width < 1: raise ValueError("model.max_length must be at least 3") index = len(ids) // 2 if mask_index is None else int(mask_index) if not 0 <= index < len(ids): raise ValueError(f"mask_index must be in [0, {len(ids) - 1}]") start = (index // width) * width window = ids[start : start + width] gold_id = ids[index] byte_start = sum( len(decode_raw_hex(tokenizer, [token_id])[2:]) // 2 for token_id in ids[:index] ) gold_hex = decode_raw_hex(tokenizer, [gold_id]) window[index - start] = tokenizer.mask_token_id inputs = torch.tensor( [[tokenizer.cls_token_id, *window, tokenizer.sep_token_id]], device=device ) with torch.inference_mode(): logits = ( model(input_ids=inputs, attention_mask=torch.ones_like(inputs)) .logits[0, index - start + 1] .clone() ) probabilities = logits.softmax(-1) # Special tokens are not candidate transaction bytes. logits[tokenizer.all_special_ids] = -torch.inf _, candidates = logits.topk( min(int(top_k), len(tokenizer) - len(tokenizer.all_special_ids)) ) return { "task": "masked_byte_bpe_token_prediction", "mask_token_index": index, "byte_span": [byte_start, byte_start + (len(gold_hex) - 2) // 2], "gold_hex": gold_hex, "context_window_token_range": [start, start + len(window)], "transaction_token_count": len(ids), "predictions": [ { "token_id": candidate.item(), "raw_hex": decode_raw_hex(tokenizer, [candidate.item()]), "probability": probabilities[candidate].item(), } for candidate in candidates ], "limitation": "Scores concern BPE byte spans; a short PoC is not expected to predict arbitrary transaction bytes reliably.", }
"""Short, auditable BERT MLM training with local evidence and W&B metrics."""
import json
import hashlib
import math
import random
import time
from datetime import UTC, datetime
from pathlib import Path
import torch
from datasets import load_from_disk
from omegaconf import OmegaConf
from .model import build_model, config_value, parameter_count, load_mlm_model
from .lightning_runtime import AuditedLightningModule, fit_audited
from .tokenizer import corpus_digest, decode_raw_hex, encode_raw_hex, load_tokenizer
def _write_json(path, value):
Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
def _setup(config):
seed = int(config_value(config, "training.seed", 17))
random.seed(seed)
torch.manual_seed(seed)
torch.set_num_threads(int(config_value(config, "training.num_threads", 4)))
device = str(config_value(config, "training.device", "cpu"))
if device == "auto":
device = (
"cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available()
else "cpu"
)
return seed, torch.device(device)
def transaction_windows(tokenizer, raw_hex, max_length):
"""Preserve all tokens while keeping windows inside a transaction and split."""
if max_length < 3:
raise ValueError("model.max_length must allow two special tokens and a byte token")
ids = encode_raw_hex(tokenizer, raw_hex, add_special_tokens=False)
width = max_length - 2
return [
[tokenizer.cls_token_id, *ids[start : start + width], tokenizer.sep_token_id]
for start in range(0, len(ids), width)
]
def _windows(tokenizer, records, max_length):
windows = []
token_count = long_transactions = 0
for raw_hex in records["raw_hex"]:
parts = transaction_windows(tokenizer, raw_hex, max_length)
windows.extend(parts)
token_count += sum(len(part) - 2 for part in parts)
long_transactions += len(parts) > 1
if not windows:
raise ValueError("A nonempty transaction split is required")
return windows, {
"transactions": len(records),
"windows": len(windows),
"byte_bpe_tokens": token_count,
"multi_window_transactions": long_transactions,
"truncated_tokens": 0,
"max_window_length": max(map(len, windows)),
}
def mask_batch(sequences, tokenizer, probability, generator):
"""BERT 80% MASK / 10% random / 10% unchanged; never supervise specials.
At least one eligible target per sequence is selected, so short transactions
cannot produce a NaN all-ignored loss. Random replacements exclude specials.
"""
if not 0 < probability <= 1:
raise ValueError("training.mlm_probability must be in (0, 1]")
length = max(map(len, sequences))
ids = torch.full((len(sequences), length), tokenizer.pad_token_id, dtype=torch.long)
attention = torch.zeros_like(ids)
for index, sequence in enumerate(sequences):
ids[index, : len(sequence)] = torch.tensor(sequence)
attention[index, : len(sequence)] = 1
eligible = attention.bool()
for token_id in tokenizer.all_special_ids:
eligible &= ids != token_id
selected = (torch.rand(ids.shape, generator=generator) < probability) & eligible
for index in range(len(sequences)):
if not selected[index].any():
choices = eligible[index].nonzero().flatten()
if not len(choices):
raise ValueError("Cannot mask a sequence containing only special tokens")
selected[index, choices[torch.randint(len(choices), (1,), generator=generator)]] = True
labels = ids.clone()
labels[~selected] = -100
replacement = torch.rand(ids.shape, generator=generator)
ids[selected & (replacement < 0.8)] = tokenizer.mask_token_id
random_positions = selected & (replacement >= 0.8) & (replacement < 0.9)
normal_ids = torch.tensor(