Repository navigation
Expand file tree
/
Copy pathtrain.py
More file actions
5050 lines (4634 loc) · 192 KB
/
Copy pathtrain.py
File metadata and controls
5050 lines (4634 loc) · 192 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
End-to-End Training Pipeline for Smart Contract Decompilation
This script provides a single command to:
1. Collect verified contracts from Etherscan
2. Convert bytecode to TAC and pair with Solidity source
3. Build and split the training dataset
4. Fine-tune Qwen2.5-Coder-7B-Instruct with LoRA
5. Evaluate the trained model
Usage:
# Full pipeline
uv run --extra training train.py
# Quick test (fewer contracts, 1 epoch)
uv run --extra training train.py --small
# Skip data collection, use existing dataset
uv run --extra training train.py --skip-collection --dataset data/train_dataset.jsonl
# Only build dataset, no training
uv run --extra training train.py --dataset-only
# Use a specific contract addresses file
uv run --extra training train.py --addresses data/contract_addresses.txt
# Evaluate a previously trained model (auto-detects data/test_dataset.jsonl)
uv run --extra evaluation train.py --eval-only --model-path models/smart_contract_decompiler
# Evaluate with a specific test dataset
uv run --extra evaluation train.py --eval-only --model-path models/smart_contract_decompiler --test-dataset data/test_dataset.jsonl --eval-batch-size 4 --eval-output results/heldout.json
# Evaluate after re-splitting a source dataset
uv run --extra evaluation train.py --eval-only --model-path models/smart_contract_decompiler --dataset data/my_dataset.jsonl
# Train with safe bytecode/TAC-derived prompt metadata (default)
uv run --extra training train.py --skip-collection --dataset data/hf_training_dataset.jsonl --max-steps 300
# Resume the latest checkpoint under --output-dir and persist a manifest
uv run --extra training train.py --skip-collection --dataset data/hf_training_dataset.jsonl --resume auto
# Multi-GPU evaluation with torchrun (shards test data across GPUs)
uv run --extra evaluation torchrun --nproc_per_node=4 train.py --eval-only --model-path models/smart_contract_decompiler
# Override the default 4-GPU LoRA/Qwen recipe
uv run --extra quantization train.py --config training_config.yaml --num-gpus 1 --quantization
"""
import argparse
from collections import Counter, defaultdict
from datetime import datetime, timezone
import hashlib
import importlib.metadata as importlib_metadata
import inspect
import json
import logging
import os
import random
import re
import subprocess
import sys
import time
import traceback
from pathlib import Path
from typing import Any, Mapping
import yaml
DEFAULT_MODEL_NAME = "Qwen/Qwen2.5-Coder-7B-Instruct"
DEFAULT_NUM_GPUS = 4
DEFAULT_BATCH_SIZE = 1
DEFAULT_GLOBAL_BATCH_SIZE = 16
DEFAULT_MAX_SEQ_LENGTH = 8192
DEFAULT_EVAL_MAX_NEW_TOKENS = 256
DEFAULT_EVAL_REPETITION_PENALTY = 1.05
DEFAULT_GLOBAL_SEED = 42
DEFAULT_USE_QUANTIZATION = False
DEFAULT_PRECISION = "fp16"
DEFAULT_GRADIENT_CHECKPOINTING = True
DEFAULT_LORA_RANK = 16
DEFAULT_LORA_ALPHA = 32
DEFAULT_LORA_DROPOUT = 0.1
DEFAULT_EVAL_SEED = 42
SPLIT_ARTIFACT_FILENAMES = {
"train_dataset.jsonl",
"val_dataset.jsonl",
"validation_dataset.jsonl",
"test_dataset.jsonl",
}
SPLIT_CACHE_SCHEMA_VERSION = 2
PREFLIGHT_CACHE_SCHEMA_VERSION = 3
DEFAULT_MIN_SPLIT_TARGET_RATIO = 0.5
DEFAULT_MAX_COMPONENT_TARGET_RATIO = 1.0
DEFAULT_QUALITY_THRESHOLDS = {
"semantic_similarity_mean": {"op": ">=", "value": 0.82, "required": True},
"pct_above_0.8_similarity": {"op": ">=", "value": 0.78, "required": True},
"pct_below_0.4_edit_dist": {"op": ">=", "value": 0.82, "required": True},
"failure_rate": {"op": "<=", "value": 0.0, "required": True},
"replication_f1_mean": {"op": ">=", "value": 0.75, "required": True},
"solidity_valid_mean": {"op": ">=", "value": 1.0, "required": True},
"solidity_compiler_checked_mean": {"op": ">=", "value": 1.0, "required": True},
"solidity_ast_valid_mean": {"op": ">=", "value": 1.0, "required": True},
"bytecode_semantic_score_mean": {"op": ">=", "value": 0.5, "required": True},
"bytecode_semantic_checked_mean": {"op": ">=", "value": 1.0, "required": True},
"bytecode_deployable_mean": {"op": ">=", "value": 1.0, "required": True},
}
def _distributed_world_size() -> int:
raw_world_size = os.getenv("WORLD_SIZE")
try:
return max(1, int(raw_world_size)) if raw_world_size else 1
except ValueError:
return 1
def resolve_gradient_accumulation_steps(
per_device_batch_size: int,
world_size: int = 1,
global_batch_size: int | None = DEFAULT_GLOBAL_BATCH_SIZE,
explicit_steps: int | None = None,
) -> int:
"""Resolve gradient accumulation while preserving the target global batch."""
if explicit_steps is not None:
return max(1, int(explicit_steps))
if not global_batch_size:
return 1
denominator = max(1, int(per_device_batch_size) * max(1, int(world_size)))
return max(1, (int(global_batch_size) + denominator - 1) // denominator)
def _cuda_device_count() -> int:
try:
import torch
if not torch.cuda.is_available():
return 0
return int(torch.cuda.device_count())
except Exception:
return 0
def _is_distributed_launch() -> bool:
return "LOCAL_RANK" in os.environ or _distributed_world_size() > 1
def _maybe_relaunch_with_torchrun(args: argparse.Namespace) -> None:
"""Use torchrun for the default multi-GPU training/eval path."""
if args.dataset_only or args.no_auto_torchrun or _is_distributed_launch():
return
if args.num_gpus <= 1:
return
available_gpus = _cuda_device_count()
if available_gpus <= 1:
return
nproc = min(args.num_gpus, available_gpus)
if nproc < args.num_gpus:
print(
f"Requested {args.num_gpus} GPUs but only {available_gpus} are visible; "
f"launching with {nproc}.",
flush=True,
)
print(f"Launching distributed run with torchrun on {nproc} GPUs.", flush=True)
cmd = [
sys.executable,
"-m",
"torch.distributed.run",
"--standalone",
f"--nproc_per_node={nproc}",
*sys.argv,
]
os.execv(sys.executable, cmd)
def _normalize_config_key(key: str) -> str:
return str(key).strip().replace("-", "_")
def _flatten_cli_config(config: Mapping[str, Any]) -> dict[str, Any]:
"""Flatten supported nested YAML/JSON training config sections to argparse dests."""
flattened: dict[str, Any] = {}
key_aliases = {
"learning_rate": "lr",
"max_sequence_length": "max_seq_length",
"gpus": "num_gpus",
"gpu_count": "num_gpus",
"quantization": "use_quantization",
}
def merge_mapping(mapping: Mapping[str, Any], section: str | None = None) -> None:
for raw_key, value in mapping.items():
key = _normalize_config_key(raw_key)
if key == "model" and isinstance(value, Mapping):
merge_mapping(value, "model")
continue
if key == "lora" and isinstance(value, Mapping):
merge_lora_mapping(value)
continue
if key in {"training", "trainer", "data", "dataset", "evaluation"} and isinstance(
value, Mapping
):
merge_mapping(value, key)
continue
if section == "model":
if key in {"name", "model"}:
flattened["model_name"] = value
continue
if key == "max_sequence_length":
flattened["max_seq_length"] = value
continue
if section in {"data", "dataset"} and key in {"path", "dataset_path"}:
flattened["dataset"] = value
continue
if section == "evaluation" and key == "batch_size":
flattened["eval_batch_size"] = value
continue
flattened[key_aliases.get(key, key)] = value
def merge_lora_mapping(mapping: Mapping[str, Any]) -> None:
for raw_key, value in mapping.items():
key = _normalize_config_key(raw_key)
if key == "enabled":
flattened["use_lora"] = value
elif key in {"rank", "r"}:
flattened["lora_rank"] = value
elif key in {"alpha", "lora_alpha"}:
flattened["lora_alpha"] = value
elif key in {"dropout", "lora_dropout"}:
flattened["lora_dropout"] = value
elif key in {"target_modules", "targets"}:
flattened["lora_target_modules"] = value
else:
flattened[f"lora_{key}"] = value
merge_mapping(config)
return flattened
def _load_cli_config(path: str | None) -> dict[str, Any]:
if not path:
return {}
config_path = Path(path)
with open(config_path, "r") as f:
if config_path.suffix.lower() == ".json":
payload = json.load(f)
else:
payload = yaml.safe_load(f)
if payload is None:
return {}
if not isinstance(payload, Mapping):
raise ValueError(f"Training config must be a mapping: {config_path}")
return _flatten_cli_config(payload)
def _parser_destinations(parser: argparse.ArgumentParser) -> set[str]:
return {
action.dest
for action in parser._actions
if action.dest and action.dest != argparse.SUPPRESS and action.dest != "help"
}
def setup_logging(log_file: str = "train.log"):
"""Configure logging to file and console."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(),
],
)
def load_settings() -> dict:
"""Load settings from src/settings.yaml and environment variables."""
settings = {}
settings_path = Path("src/settings.yaml")
if settings_path.exists():
with open(settings_path, "r") as f:
settings = yaml.safe_load(f) or {}
# Environment variables override file settings
if os.getenv("ETHERSCAN_API_KEY"):
settings["ETHERSCAN_API_KEY"] = os.getenv("ETHERSCAN_API_KEY")
if os.getenv("HF_TOKEN"):
settings["HF_TOKEN"] = os.getenv("HF_TOKEN")
return settings
def load_contract_addresses(filepath: str) -> list:
"""Load contract addresses from a text file (one per line, # comments)."""
addresses = []
with open(filepath, "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
addresses.append(line)
return addresses
def collect_dataset(
api_key: str,
addresses_file: str,
output_dir: str = "data",
max_contracts: int = None,
max_compiler_configs: int = 1,
max_workers: int = 3,
allow_demo_fallback: bool = False,
) -> str:
"""Collect contracts from Etherscan and compile locally to build dataset.
Uses local solc compilation (via py-solc-x) for each contract with one
source-aligned compiler configuration. Compiler metadata is stored in each
record's metadata field, but prompts only use bytecode/TAC-derived metadata
and sanitize oracle annotations.
Returns path to the exported JSONL dataset file.
"""
from src.dataset_pipeline import DatasetBuilder
logger = logging.getLogger(__name__)
# Load addresses
addresses = load_contract_addresses(addresses_file)
if max_contracts:
addresses = addresses[:max_contracts]
logger.info(f"Loaded {len(addresses)} contract addresses from {addresses_file}")
# Initialize builder
builder = DatasetBuilder(api_key, output_dir=output_dir)
# Collect, compile locally, and build function pairs in one pass
logger.info(
"Downloading source from Etherscan and compiling locally "
"(single source-aligned config per contract; requested max configs=%s; "
"requested workers=%s)...",
max_compiler_configs,
max_workers,
)
collect_kwargs = {"max_compiler_configs": max_compiler_configs}
collect_signature = inspect.signature(builder.collect_and_compile_contracts)
supports_max_workers = "max_workers" in collect_signature.parameters or any(
param.kind == inspect.Parameter.VAR_KEYWORD
for param in collect_signature.parameters.values()
)
if supports_max_workers:
collect_kwargs["max_workers"] = max_workers
logger.info("Collection/compile worker count: %s", max_workers)
elif max_workers not in (None, 1):
logger.warning(
"DatasetBuilder.collect_and_compile_contracts does not support "
"max_workers; running collection sequentially."
)
total_pairs = builder.collect_and_compile_contracts(addresses, **collect_kwargs)
logger.info(f"Created {total_pairs} function pairs")
if total_pairs == 0:
message = (
"No function pairs created from Etherscan data. "
"Refusing to train on demo data unless --allow-demo-fallback is set."
)
if not allow_demo_fallback:
raise RuntimeError(message)
logger.warning("%s Using explicit demo fallback.", message)
return _ensure_demo_dataset(output_dir, reason="zero_function_pairs")
# Filter
logger.info("Filtering dataset...")
filtered = builder.filter_and_clean_dataset(min_length=20, max_length=20000)
logger.info(f"After filtering: {filtered} pairs")
if filtered == 0:
message = (
"All collected function pairs were filtered out. "
"Refusing to train on demo data unless --allow-demo-fallback is set."
)
if not allow_demo_fallback:
raise RuntimeError(message)
logger.warning("%s Using explicit demo fallback.", message)
return _ensure_demo_dataset(output_dir, reason="all_pairs_filtered")
# Export
dataset_path = builder.export_dataset("jsonl")
logger.info(f"Dataset exported to {dataset_path}")
# Print stats
stats = builder.get_dataset_statistics()
logger.info(f"Dataset statistics: {json.dumps(stats, indent=2, default=str)}")
return dataset_path
def _ensure_demo_dataset(output_dir: str, reason: str = "explicit_demo_fallback") -> str:
"""Copy demo_dataset.jsonl to output_dir if no real data available."""
logger = logging.getLogger(__name__)
demo_path = Path("demo_dataset.jsonl")
if not demo_path.exists():
raise RuntimeError("demo_dataset.jsonl not found. Cannot proceed without data.")
target = Path(output_dir) / "dataset_from_demo.jsonl"
import shutil
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(str(demo_path), str(target))
manifest_path = Path(f"{target}.manifest.json")
manifest = {
"manifest_kind": "demo_dataset_fallback",
"schema_version": 1,
"created_at": _utc_now_iso(),
"demo_fallback": True,
"reason": reason,
"source": _file_artifact(demo_path, jsonl=True),
"output": _file_artifact(target, jsonl=True),
}
manifest_path.parent.mkdir(parents=True, exist_ok=True)
with open(manifest_path, "w") as f:
json.dump(_json_safe(manifest), f, indent=2, sort_keys=True)
logger.warning("Using explicit demo dataset fallback: %s (%s)", target, reason)
return str(target)
SPLIT_NAMES = ("train", "val", "test")
GROUP_KEY_PRECEDENCE = (
"source_hash",
"contract_address",
"contract_function",
"body_hash",
"output_hash",
"input_hash",
)
LEAKAGE_KEY_CATEGORIES = (
"source_hash",
"contract_address",
"contract_function",
"body_hash",
"input_hash",
"output_hash",
)
COVERAGE_FIELDS = (
"compiler_version",
"optimizer",
"visibility",
"source",
"length_bucket",
"function_family",
)
def _metadata_dict(item: dict) -> dict:
metadata = item.get("metadata")
return metadata if isinstance(metadata, dict) else {}
def _metadata_value(item: dict, *keys: str):
metadata = _metadata_dict(item)
nested_containers = []
for parent_key in (
"decontamination",
"decontamination_keys",
"split_keys",
"dedup_keys",
"quality_keys",
):
value = metadata.get(parent_key)
if isinstance(value, dict):
nested_containers.append(value)
value = item.get(parent_key)
if isinstance(value, dict):
nested_containers.append(value)
containers = [item, metadata, *nested_containers]
for key in keys:
for container in containers:
value = container.get(key) if isinstance(container, dict) else None
if value not in (None, ""):
return str(value)
return None
def _normalize_key_value(value: Any, lowercase: bool = True) -> str | None:
if value in (None, ""):
return None
if isinstance(value, bool):
text = "true" if value else "false"
else:
text = str(value).strip()
if not text:
return None
return text.lower() if lowercase else text
def _exact_text_hash(value: Any) -> str | None:
if value is None:
return None
return hashlib.sha256(str(value).encode("utf-8")).hexdigest()
def _stable_row_hash(item: dict) -> str:
return hashlib.sha256(
json.dumps(item, sort_keys=True, ensure_ascii=False, default=str).encode("utf-8")
).hexdigest()
def _add_leakage_key(keys: dict[str, set[str]], category: str, value: Any) -> None:
normalized = _normalize_key_value(value)
if normalized:
keys.setdefault(category, set()).add(normalized)
def _row_leakage_keys(item: dict) -> dict[str, set[str]]:
"""Return all decontamination keys used to prevent split leakage."""
keys: dict[str, set[str]] = {}
_add_leakage_key(
keys,
"source_hash",
_metadata_value(
item,
"source_hash",
"source_code_hash",
"contract_source_hash",
"decontamination_source_hash",
),
)
contract_address = _metadata_value(
item,
"contract_address",
"address",
"deployed_address",
)
_add_leakage_key(keys, "contract_address", contract_address)
selector = _metadata_value(
item,
"function_selector",
"selector",
"method_id",
"4byte_selector",
)
signature = _metadata_value(
item,
"function_signature",
"signature",
"canonical_signature",
"method_signature",
)
if contract_address and selector:
_add_leakage_key(keys, "contract_function", f"{contract_address}:{selector}")
if contract_address and signature:
_add_leakage_key(keys, "contract_function", f"{contract_address}:{signature}")
_add_leakage_key(
keys,
"body_hash",
_metadata_value(
item,
"body_hash",
"function_body_hash",
"normalized_body_hash",
"solidity_body_hash",
),
)
_add_leakage_key(
keys,
"input_hash",
_metadata_value(
item,
"input_hash",
"exact_input_hash",
"tac_hash",
"bytecode_hash",
),
)
_add_leakage_key(keys, "input_hash", _exact_text_hash(item.get("input")))
_add_leakage_key(
keys,
"output_hash",
_metadata_value(
item,
"output_hash",
"exact_output_hash",
"solidity_hash",
),
)
_add_leakage_key(keys, "output_hash", _exact_text_hash(item.get("output")))
return keys
def _dataset_group_key(item: dict) -> str:
"""Stable leakage-prevention key for dataset splitting."""
keys = _row_leakage_keys(item)
for category in GROUP_KEY_PRECEDENCE:
values = sorted(keys.get(category, ()))
if values:
return f"{category}:{values[0]}"
return f"row:{_stable_row_hash(item)}"
def _find_parent(parent: list[int], idx: int) -> int:
while parent[idx] != idx:
parent[idx] = parent[parent[idx]]
idx = parent[idx]
return idx
def _union_parent(parent: list[int], left: int, right: int) -> None:
left_root = _find_parent(parent, left)
right_root = _find_parent(parent, right)
if left_root != right_root:
parent[right_root] = left_root
def _coverage_length_bucket(item: dict) -> str:
token_estimate = len(str(item.get("input", "")).split()) + len(
str(item.get("output", "")).split()
)
if token_estimate <= 256:
return "<=256"
if token_estimate <= 512:
return "257-512"
if token_estimate <= 1024:
return "513-1024"
if token_estimate <= 2048:
return "1025-2048"
if token_estimate <= 4096:
return "2049-4096"
return ">4096"
def _parse_bool_label(value: Any) -> str:
if value in (None, ""):
return "unknown"
if isinstance(value, bool):
return "enabled" if value else "disabled"
text = str(value).strip().lower()
if text in {"true", "1", "yes", "y", "enabled", "on"}:
return "enabled"
if text in {"false", "0", "no", "n", "disabled", "off"}:
return "disabled"
return text or "unknown"
def _function_family(item: dict) -> str:
name = (
_metadata_value(item, "function_name", "name")
or _metadata_value(item, "function_signature", "signature")
or ""
)
text = name.lower()
if not text:
return "unknown"
if "fallback" in text or "receive" in text:
return "fallback_receive"
if "constructor" in text:
return "constructor"
if "transfer" in text or "send" in text:
return "transfer"
if "approve" in text or "allowance" in text or "permit" in text:
return "approval"
if "balance" in text or text.startswith("get") or re.search(r"\bview\b", text):
return "read_getter"
if text.startswith("set") or "update" in text:
return "write_setter"
if "owner" in text or "admin" in text or "role" in text:
return "access_control"
if "mint" in text:
return "mint"
if "burn" in text:
return "burn"
if "pause" in text:
return "pause"
return "other"
def _coverage_dimensions(item: dict) -> dict[str, str]:
return {
"compiler_version": _normalize_key_value(
_metadata_value(
item,
"compiler_version",
"solc_version",
"solidity_compiler_version",
),
lowercase=False,
)
or "unknown",
"optimizer": _parse_bool_label(
_metadata_value(
item,
"optimizer_enabled",
"optimization_enabled",
"optimizer",
)
),
"visibility": _normalize_key_value(_metadata_value(item, "visibility"), lowercase=True)
or "unknown",
"source": _normalize_key_value(
_metadata_value(item, "source", "dataset_source", "origin"), lowercase=True
)
or "unknown",
"length_bucket": _coverage_length_bucket(item),
"function_family": _function_family(item),
}
def _build_leakage_components(data: list[dict]) -> list[dict]:
parent = list(range(len(data)))
key_owner: dict[tuple[str, str], int] = {}
row_keys: list[dict[str, set[str]]] = []
for idx, item in enumerate(data):
keys = _row_leakage_keys(item)
row_keys.append(keys)
for category, values in keys.items():
for value in values:
key = (category, value)
if key in key_owner:
_union_parent(parent, key_owner[key], idx)
else:
key_owner[key] = idx
components_by_root: dict[int, dict] = {}
for idx, item in enumerate(data):
root = _find_parent(parent, idx)
component = components_by_root.setdefault(
root,
{
"indices": [],
"rows": [],
"leakage_keys": defaultdict(set),
"primary_group_keys": set(),
"coverage": {field: Counter() for field in COVERAGE_FIELDS},
},
)
component["indices"].append(idx)
component["rows"].append(item)
component["primary_group_keys"].add(_dataset_group_key(item))
for category, values in row_keys[idx].items():
component["leakage_keys"][category].update(values)
for field, value in _coverage_dimensions(item).items():
component["coverage"][field][value] += 1
components = []
for component in components_by_root.values():
component["leakage_keys"] = {
category: sorted(values) for category, values in component["leakage_keys"].items()
}
component["primary_group_keys"] = sorted(component["primary_group_keys"])
stable_basis = {
"indices": component["indices"],
"primary_group_keys": component["primary_group_keys"],
}
component["id"] = hashlib.sha256(
json.dumps(stable_basis, sort_keys=True).encode("utf-8")
).hexdigest()
components.append(component)
return components
def _score_component_assignment(
split_name: str,
component: dict,
ratios: dict[str, float],
target_rows: dict[str, float],
row_counts: dict[str, int],
split_coverage: dict[str, dict[str, Counter]],
global_coverage: dict[str, Counter],
assigned: dict[str, list[dict]],
) -> float:
size = len(component["rows"])
desired_rows = max(target_rows[split_name], 1.0)
projected_rows = row_counts[split_name] + size
row_score = abs(projected_rows - desired_rows) / desired_rows
if row_counts[split_name] > desired_rows:
row_score += 1.0
if ratios[split_name] > 0 and not assigned[split_name]:
row_score -= 0.15
stratum_score = 0.0
for field in COVERAGE_FIELDS:
for value, count in component["coverage"][field].items():
desired_value = global_coverage[field][value] * ratios[split_name]
if desired_value <= 0:
continue
projected_value = split_coverage[split_name][field][value] + count
stratum_score += abs(projected_value - desired_value) / max(desired_value, 1.0)
return (4.0 * row_score) + (0.1 * stratum_score)
def _stratified_component_split(
components: list[dict],
train_ratio: float,
val_ratio: float,
seed: int,
) -> dict[str, list[dict]]:
ratios = {
"train": train_ratio,
"val": val_ratio,
"test": max(0.0, 1.0 - train_ratio - val_ratio),
}
total_rows = sum(len(component["rows"]) for component in components)
target_rows = {name: total_rows * ratios[name] for name in SPLIT_NAMES}
global_coverage = {field: Counter() for field in COVERAGE_FIELDS}
for component in components:
for field in COVERAGE_FIELDS:
global_coverage[field].update(component["coverage"][field])
rng = random.Random(seed)
ordered = list(components)
rng.shuffle(ordered)
ordered.sort(key=lambda component: (-len(component["rows"]), component["id"]))
assigned: dict[str, list[dict]] = {name: [] for name in SPLIT_NAMES}
row_counts = {name: 0 for name in SPLIT_NAMES}
split_coverage = {name: {field: Counter() for field in COVERAGE_FIELDS} for name in SPLIT_NAMES}
for component in ordered:
eligible = [name for name in SPLIT_NAMES if ratios[name] > 0]
if not eligible:
eligible = ["train"]
split_name = min(
eligible,
key=lambda candidate: _score_component_assignment(
candidate,
component,
ratios,
target_rows,
row_counts,
split_coverage,
global_coverage,
assigned,
),
)
assigned[split_name].append(component)
row_counts[split_name] += len(component["rows"])
for field in COVERAGE_FIELDS:
split_coverage[split_name][field].update(component["coverage"][field])
# If enough groups exist, keep validation and test non-empty when requested.
for split_name in ("val", "test"):
if ratios[split_name] <= 0 or assigned[split_name] or len(components) < 3:
continue
donor = max(
(name for name in SPLIT_NAMES if name != split_name and len(assigned[name]) > 1),
key=lambda name: row_counts[name],
default=None,
)
if donor is None:
continue
moved = min(assigned[donor], key=lambda component: len(component["rows"]))
assigned[donor].remove(moved)
assigned[split_name].append(moved)
row_counts[donor] -= len(moved["rows"])
row_counts[split_name] += len(moved["rows"])
return assigned
def _grouped_split(
data: list,
train_ratio: float,
val_ratio: float,
seed: int = 42,
) -> tuple:
"""Split rows by leakage-connected groups so variants cannot cross boundaries."""
components = _build_leakage_components(data)
if len(components) < 3:
logging.getLogger(__name__).warning(
"Dataset has only %d split groups; writing all rows to train and "
"leaving validation/test empty to avoid leakage.",
len(components),
)
return list(data), [], []
assigned = _stratified_component_split(components, train_ratio, val_ratio, seed)
train_data = [row for component in assigned["train"] for row in component["rows"]]
val_data = [row for component in assigned["val"] for row in component["rows"]]
test_data = [row for component in assigned["test"] for row in component["rows"]]
return train_data, val_data, test_data
def validate_split_leakage(
split_rows: dict[str, list[dict]],
sample_limit: int = 20,
) -> dict:
"""Validate that leakage keys do not appear in more than one split."""
key_locations: dict[str, dict[str, Counter]] = {
category: defaultdict(Counter) for category in LEAKAGE_KEY_CATEGORIES
}
for split_name, rows in split_rows.items():
for row in rows:
for category, values in _row_leakage_keys(row).items():
if category not in key_locations:
continue
for value in values:
key_locations[category][value][split_name] += 1
overlaps = []
overlap_counts = {}
for category in LEAKAGE_KEY_CATEGORIES:
category_overlaps = []
for value, counts in key_locations[category].items():
split_counts = {name: count for name, count in counts.items() if count > 0}
if len(split_counts) > 1:
category_overlaps.append(
{
"key": value,
"split_counts": split_counts,
}
)
category_overlaps.sort(key=lambda item: (-sum(item["split_counts"].values()), item["key"]))
overlap_counts[category] = len(category_overlaps)
for item in category_overlaps[:sample_limit]:
overlaps.append({"category": category, **item})
total_overlaps = sum(overlap_counts.values())
return {
"status": "passed" if total_overlaps == 0 else "failed",
"checked_categories": list(LEAKAGE_KEY_CATEGORIES),
"overlap_counts": overlap_counts,
"total_overlap_keys": total_overlaps,
"sample_overlaps": overlaps[:sample_limit],
}
def _split_group_counts(split_rows: dict[str, list[dict]]) -> dict[str, int]:
return {
name: len(_build_leakage_components(rows)) if rows else 0
for name, rows in split_rows.items()
}
def split_coverage_report(
split_rows: dict[str, list[dict]],
min_holdout_stratum_count: int = 0,
) -> dict:
"""Report split and holdout coverage over dataset quality strata."""
coverage = {
name: {
"row_count": len(rows),
"group_count": len(_build_leakage_components(rows)) if rows else 0,
"fields": {field: Counter() for field in COVERAGE_FIELDS},
}
for name, rows in split_rows.items()
}
total = {"row_count": 0, "fields": {field: Counter() for field in COVERAGE_FIELDS}}
holdout = {"row_count": 0, "fields": {field: Counter() for field in COVERAGE_FIELDS}}
for split_name, rows in split_rows.items():
for row in rows:
dims = _coverage_dimensions(row)
total["row_count"] += 1
if split_name in {"val", "test"}:
holdout["row_count"] += 1
for field, value in dims.items():
coverage[split_name]["fields"][field][value] += 1
total["fields"][field][value] += 1
if split_name in {"val", "test"}:
holdout["fields"][field][value] += 1
violations = []
threshold = int(min_holdout_stratum_count or 0)
if threshold > 0:
for split_name in ("val", "test"):
for field in COVERAGE_FIELDS:
for value, total_count in total["fields"][field].items():
# Only require per-holdout coverage for strata common enough
# to make train/val/test coverage practical.
if total_count < threshold * 3:
continue
count = coverage[split_name]["fields"][field].get(value, 0)
if count < threshold:
violations.append(
{
"split": split_name,
"field": field,
"value": value,
"count": count,
"required": threshold,
"total_count": total_count,
}
)