somehowchris's picture
Upload verified EVM benchmark artifacts
0edf333 verified
Raw History Blame Contribute Delete
12.2 kB
"""Click entry points; each stage also works as a Python function."""
import json
from pathlib import Path
import click
from omegaconf import DictConfig, OmegaConf
from evm_bert.config import load_config
def emit(value: dict) -> None:
click.echo(json.dumps(value, indent=2, default=str))
@click.group()
@click.option("--config", "config_path", type=click.Path(exists=True), default="configs/poc.yaml", show_default=True)
@click.option("-o", "--override", multiple=True, help="OmegaConf key=value; repeat as needed.")
@click.pass_context
def main(ctx: click.Context, config_path: str, override: tuple[str, ...]) -> None:
"""Collect, validate, tokenize, train, evaluate and privately publish raw EVM bytes."""
try:
ctx.obj = load_config(config_path, override)
except (ValueError, KeyError) as exc:
raise click.ClickException(str(exc)) from exc
@main.command("config")
@click.pass_obj
def show_config(cfg: DictConfig) -> None:
"""Print the fully resolved configuration (contains no credentials)."""
click.echo(OmegaConf.to_yaml(cfg))
@main.command()
@click.pass_obj
def collect(cfg: DictConfig) -> None:
"""Collect the configured number of signed transactions per chain."""
from evm_bert.data import collect as run
emit(run(cfg))
@main.command()
@click.pass_obj
def validate(cfg: DictConfig) -> None:
"""Recheck every transaction, signature, split and source checksum."""
from evm_bert.data import validate_dataset
emit(validate_dataset(cfg))
@main.command("tokenizer")
@click.pass_obj
def tokenizer_command(cfg: DictConfig) -> None:
"""Train a lossless 8,192-token byte BPE using only the training split."""
from evm_bert.tokenizer import train_tokenizer
emit(train_tokenizer(cfg))
@main.command()
@click.pass_obj
def train(cfg: DictConfig) -> None:
"""Run short BERT MLM training with per-layer gradient evidence and W&B."""
from evm_bert.train import train_mlm
emit(train_mlm(cfg))
@main.command()
@click.pass_obj
def evaluate(cfg: DictConfig) -> None:
"""Evaluate the saved checkpoint on held-out masked transactions."""
from evm_bert.train import evaluate_mlm
emit(evaluate_mlm(cfg))
@main.command()
@click.argument("raw_hex")
@click.pass_obj
def predict(cfg: DictConfig, raw_hex: str) -> None:
"""Mask and rank a token in an encoded transaction."""
from evm_bert.train import predict_mask
emit(predict_mask(cfg, raw_hex))
@main.command()
@click.option("--input", "input_path", type=click.Path(exists=True, dir_okay=False))
@click.pass_obj
def benchmark(cfg: DictConfig, input_path: str | None) -> None:
"""Evaluate a supplied labeled competition dataset without group leakage."""
from evm_bert.benchmark import run_benchmark
if input_path:
cfg.benchmark.path = input_path
if not cfg.benchmark.path:
raise click.ClickException("Supply your competition dataset: evm benchmark --input PATH")
emit(run_benchmark(cfg))
@main.command("prepare-kaggle")
@click.pass_obj
def prepare_kaggle_command(cfg: DictConfig) -> None:
"""Prepare original Kaggle account rows and linked historical signed transactions."""
from evm_bert.kaggle_data import prepare_kaggle
emit(prepare_kaggle(cfg))
@main.command("finetune")
@click.pass_obj
def finetune_command(cfg: DictConfig) -> None:
"""Fine-tune the full encoder on account-disjoint Kaggle labels."""
from evm_bert.finetune import finetune_classifier
emit(finetune_classifier(cfg))
@main.command("train-history")
@click.pass_obj
def train_history_command(cfg: DictConfig) -> None:
"""Train Part 2 causal block reconstruction without changing Part 1."""
from evm_bert.history_train import train_history
emit(train_history(cfg))
@main.command("finetune-history")
@click.pass_obj
def finetune_history_command(cfg: DictConfig) -> None:
"""Adapt Part 2 to a candidate and its prior same-account transactions."""
from evm_bert.history_train import finetune_history
emit(finetune_history(cfg))
@main.command("collect-block")
@click.argument("block_number", default="latest")
@click.option("--chain", default="ethereum", show_default=True)
@click.option("--output", required=True, type=click.Path(dir_okay=False))
@click.pass_obj
def collect_block_command(cfg: DictConfig, block_number: str, chain: str, output: str) -> None:
"""Collect every supported signed envelope in a full block, with omissions audited."""
from evm_bert.history_collect import collect_block
emit(collect_block(cfg, block_number, output, chain=chain))
@main.command("embed-transactions")
@click.argument("input_jsonl", type=click.Path(exists=True, dir_okay=False))
@click.option("--checkpoint", required=True, type=click.Path(exists=True, file_okay=False))
@click.option("--output", required=True, type=click.Path(dir_okay=False))
@click.pass_obj
def embed_transactions_command(cfg: DictConfig, input_jsonl: str, checkpoint: str, output: str) -> None:
"""Write one vector per complete signed transaction."""
_embed_records_command(cfg, input_jsonl, checkpoint, output, None)
@main.command("embed-history")
@click.argument("input_jsonl", type=click.Path(exists=True, dir_okay=False))
@click.option("--checkpoint", required=True, type=click.Path(exists=True, file_okay=False))
@click.option("--kind", type=click.Choice(["block", "sender"]), default="block", show_default=True)
@click.option("--output", required=True, type=click.Path(dir_okay=False))
@click.pass_obj
def embed_history_command(cfg: DictConfig, input_jsonl: str, checkpoint: str, kind: str, output: str) -> None:
"""Write causal vectors using each block's or sender's prior transactions."""
_embed_records_command(cfg, input_jsonl, checkpoint, output, kind)
def _embed_records_command(cfg, input_jsonl, checkpoint, output, kind):
import torch
from evm_bert.history_inference import embed_history_records, embed_transaction_records
from evm_bert.history_model import HierarchicalTransactionModel
from evm_bert.history_train import write_json
from evm_bert.tokenizer import load_tokenizer
model = HierarchicalTransactionModel.from_pretrained(checkpoint).eval()
tokenizer = load_tokenizer(checkpoint)
records = [json.loads(line) for line in Path(input_jsonl).read_text().splitlines() if line.strip()]
with torch.inference_mode():
if kind:
result = embed_history_records(model, tokenizer, records, context_kind=kind,
max_length=int(cfg.model.max_length))
else:
result = embed_transaction_records(model, tokenizer, records,
max_length=int(cfg.model.max_length))
serialized = {key: value.cpu().tolist() if isinstance(value, torch.Tensor) else value
for key, value in result.items()}
write_json(output, serialized)
emit({"output": output, "transactions": len(records), "dimensions": model.config.hidden_size,
"context_kind": kind or "transaction"})
@main.command("predict-history")
@click.argument("candidate_json", type=click.Path(exists=True, dir_okay=False))
@click.argument("history_jsonl", type=click.Path(exists=True, dir_okay=False))
@click.option("--checkpoint", required=True, type=click.Path(exists=True, file_okay=False))
@click.pass_obj
def predict_history_command(cfg: DictConfig, candidate_json: str, history_jsonl: str, checkpoint: str) -> None:
"""Score an account FLAG proxy given a candidate and strictly earlier outgoing history."""
import torch
from evm_bert.history_inference import predict_candidate_history
from evm_bert.history_model import HierarchicalTransactionModel
from evm_bert.history_train import file_sha256
from evm_bert.tokenizer import load_tokenizer
directory = Path(checkpoint)
reports = [directory.parent / "report.json", directory / "experiment_report.json"]
provenance = [json.loads(path.read_text()) for path in reports if path.is_file()]
if not any(report.get("stage") == "history-account-finetuning" and
"FLAG proxy" in report.get("label_scope", "") and
report.get("model_sha256") == file_sha256(directory / "model.safetensors")
for report in provenance):
raise click.ClickException("Use a fine-tuned history checkpoint with its matching experiment report; the pretraining classifier is untrained")
model = HierarchicalTransactionModel.from_pretrained(checkpoint).eval()
tokenizer = load_tokenizer(checkpoint)
candidate = json.loads(Path(candidate_json).read_text())
history = [json.loads(line) for line in Path(history_jsonl).read_text().splitlines() if line.strip()]
with torch.inference_mode():
result = predict_candidate_history(model, tokenizer, candidate, history,
max_length=int(cfg.model.max_length))
emit({"candidate_tx_hash": result["candidate_tx_hash"],
"history_transactions": result["history_transactions"],
"probability_flagged_account": result["probabilities"][0, 1].item(),
"label_scope": "account FLAG proxy; not verified transaction fraud"})
@main.command("predict-accounts")
@click.argument("input_jsonl", type=click.Path(exists=True, dir_okay=False))
@click.pass_obj
def predict_accounts_command(cfg: DictConfig, input_jsonl: str) -> None:
"""Predict account FLAG proxies from JSONL containing account and raw_hex."""
if "finetune" not in cfg:
raise click.ClickException("Use --config configs/finetune.yaml or configs/finetune-final.yaml")
from evm_bert.finetune import AccountRiskClassifier, predict_accounts
from evm_bert.tokenizer import load_tokenizer
checkpoint = Path(cfg.finetune.output_dir) / "pretrained"
model = AccountRiskClassifier.from_pretrained(checkpoint, local_files_only=True)
tokenizer = load_tokenizer(checkpoint)
records = [json.loads(line) for line in Path(input_jsonl).read_text().splitlines() if line.strip()]
predictions = predict_accounts(model, tokenizer, records,
max_length=int(cfg.finetune.max_length),
batch_size=int(cfg.finetune.batch_size), device="cpu")
emit({"label_scope": "account FLAG proxy; not verified per-transaction fraud",
"predictions": predictions})
@main.command()
@click.argument("kind", type=click.Choice(["dataset", "model", "all", "kaggle", "finetuned"]), default="all")
@click.pass_obj
def publish(cfg: DictConfig, kind: str) -> None:
"""Use hf CLI to publish to the configured namespace, verified private."""
from evm_bert.publish import publish_artifacts, publish_finetuned, publish_kaggle
if kind == "kaggle":
emit(publish_kaggle(cfg))
elif kind == "finetuned":
emit(publish_finetuned(cfg))
else:
emit(publish_artifacts(cfg, kind))
@main.command()
@click.option("--publish", "do_publish", is_flag=True, help="Upload private dataset/model after verification.")
@click.pass_obj
def run(cfg: DictConfig, do_publish: bool) -> None:
"""Execute the full short PoC; resumes are available as individual commands."""
from evm_bert.data import collect, validate_dataset
from evm_bert.tokenizer import train_tokenizer
from evm_bert.train import evaluate_mlm, train_mlm
report = {}
for name, function in [("data", collect), ("validation", validate_dataset),
("tokenizer", train_tokenizer), ("training", train_mlm),
("evaluation", evaluate_mlm)]:
click.echo(f"Running {name}…", err=True)
report[name] = function(cfg)
if cfg.benchmark.path:
from evm_bert.benchmark import run_benchmark
report["benchmark"] = run_benchmark(cfg)
if do_publish:
from evm_bert.publish import publish_artifacts
report["hub"] = publish_artifacts(cfg, "all")
output = Path(cfg.training.output_dir) / "pipeline_report.json"
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, indent=2, default=str) + "\n")
emit(report)