File size: 12,186 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
"""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)