-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_to_dataset.py
More file actions
2212 lines (1887 loc) · 88.2 KB
/
commit_to_dataset.py
File metadata and controls
2212 lines (1887 loc) · 88.2 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
"""
Create canonical ISO-Bench dataset records for all commits in the extractions directory
and (optionally) export SWE-Perf/GSO compatible views, with optional push to Hugging Face.
Pipeline (batch commit processing):
1) Scan all JSON files in extractions_dir to discover commits
2) For each commit: Collect commit metadata (reuses collect.analysis.commits.PerfCommitAnalyzer)
3) For each commit: Build code-change fields (unified diff; split into patch vs test_patch; function names)
4) For each commit: Tests and timings (read/generate tests; run on base/head; parse times)
5) For each commit: Environment/version (compose version string; record setup/install commands if provided)
6) Assemble all records and export (canonical JSONL/Parquet; optional SWE-Perf/GSO views; push to HF)
Usage example (YAML config):
# commit_to_dataset.yaml
repo_path: /home/you/coding-mess/vllm
extractions_dir: misc/experiments/commit_extractions_with_apis # directory containing commit JSONs
use_docker: false
docker_image: anonymous/vllm-bench:latest
hf_repo: yourname/omni-commit-dataset # optional
push_to_hf: false
Run:
PYTHONPATH=src python src/collect/commit_to_dataset.py commit_to_dataset.yaml
The script will automatically process all JSON files in the extractions_dir (except extraction_summary.json),
extract commit hashes and parent hashes from each file, and create dataset records for all commits.
Requires:
- docs/dataset_schema.md for the canonical schema (this script does a minimal structural validation).
############################ TODO #########################################
- Running locally right now. Need to test on docker yet.
- Paths are changed everywhere because they are hardcoded everywhere (YAML & generate_test_generators.py).
- Need to change the test generation prompt. Running it on `device=CPU` need GPU,
there are `DummyLayers`, unavailable APIs & attributes like `custom_ops, input_scale, cutlass_fp8_supported`,
simplified functionality tests instead of complex internal mocking etc.
"""
from __future__ import annotations
import json
import logging
import os
import re
import shutil
import subprocess
import tempfile
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import sys
# Load environment variables from .env if present (so OPENROUTER_API_KEY is available)
try:
from dotenv import load_dotenv # type: ignore
load_dotenv()
except Exception:
pass
# Ensure local src/ is importable (for collect.* and test_scripts.*)
_ROOT_DIR = Path(__file__).resolve().parent
_SRC_DIR = _ROOT_DIR / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('commit_to_dataset.log', mode='w')
]
)
logger = logging.getLogger(__name__)
# Prefer local imports from repo
try:
# Reuse commit analysis utilities
from collect.analysis.commits import PerfCommitAnalyzer
except Exception:
PerfCommitAnalyzer = None # type: ignore
try:
# Timing helpers (we reuse parse_times signature/regex)
from collect.execute.evaluate import parse_times
except Exception:
parse_times = None # type: ignore
# Simple commit-hopping approach for vLLM API compatibility
# No complex environment managers needed - just checkout, install, test
# Optional: import the LLM test generator utilities
try:
from test_scripts.generate_test_generators import process_extraction_file, LLMClient # type: ignore
except Exception:
process_extraction_file = None # type: ignore
LLMClient = None # type: ignore
# YAML loader
try:
import yaml # type: ignore
except Exception:
yaml = None # type: ignore
# -------------------------- Utilities --------------------------
def run(cmd: List[str], cwd: Optional[Path] = None, env: Optional[Dict[str, str]] = None) -> str:
result = subprocess.run(cmd, cwd=str(cwd) if cwd else None, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
raise RuntimeError(f"Command failed: {' '.join(cmd)}\nSTDERR:\n{result.stderr}")
return result.stdout
_API_MANIFESTS: Dict[str, Dict[str, Any]] = {}
def _read_text_safe(path: Path) -> str:
try:
return path.read_text()
except Exception:
return ""
def _guess_project_name_from_pyproject(repo_path: Path) -> Optional[str]:
"""Best-effort parse of [project] name from pyproject.toml without adding deps."""
try:
pp = repo_path / "pyproject.toml"
if not pp.exists():
return None
content = pp.read_text(encoding="utf-8", errors="ignore")
# crude parse: find [project] section and name = "..."
section_start = content.find("[project]")
if section_start == -1:
return None
section = content[section_start:]
# stop at next section
for delim in ("\n[", "\r["):
idx = section.find(delim)
if idx != -1:
section = section[:idx]
break
m = re.search(r"^\s*name\s*=\s*['\"]([^'\"]+)['\"]", section, re.MULTILINE)
if m:
return m.group(1).strip()
except Exception:
return None
return None
def _candidate_import_names(repo_path: Path) -> List[str]:
"""Generate candidate top-level import names for the installed project."""
candidates: List[str] = []
# Common case for this repo's target
candidates.append("vllm")
project_name = _guess_project_name_from_pyproject(repo_path)
if project_name:
candidates.append(project_name)
candidates.append(project_name.replace('-', '_'))
repo_basename = repo_path.name
if repo_basename:
candidates.append(repo_basename)
candidates.append(repo_basename.replace('-', '_'))
# Deduplicate while preserving order
seen: set = set()
unique: List[str] = []
for c in candidates:
if c and c not in seen:
unique.append(c)
seen.add(c)
return unique
def _select_import_name_via_venv(venv_python: Path, repo_path: Path, prefer: Optional[str] = None) -> Optional[str]:
"""Attempt to import candidate names inside venv and return the first that succeeds."""
if prefer:
candidates = [prefer] + [c for c in _candidate_import_names(repo_path) if c != prefer]
else:
candidates = _candidate_import_names(repo_path)
for name in candidates:
try:
r = subprocess.run(
[str(venv_python), "-c", "import importlib,sys; importlib.import_module(sys.argv[1])", name],
capture_output=True, text=True
)
if r.returncode == 0:
return name
except Exception:
continue
return None
def _write_api_dump_script(script_path: Path) -> None:
"""Write a small script that imports a package and emits a JSON manifest of public symbols with signatures."""
script = """
import importlib, inspect, json, pkgutil, sys, types, traceback
def extract_parameter_info(obj):
\"\"\"Extract detailed parameter information for a callable object.\"\"\"
try:
sig = inspect.signature(obj)
params = {}
defaults = {}
for param_name, param in sig.parameters.items():
if param_name == 'self':
continue
params[param_name] = {
'kind': param.kind.name,
'annotation': str(param.annotation) if param.annotation != inspect.Parameter.empty else None,
'has_default': param.default != inspect.Parameter.empty
}
if param.default != inspect.Parameter.empty:
try:
defaults[param_name] = str(param.default)
except Exception:
defaults[param_name] = "<unprintable>"
return {
'parameters': list(params.keys()),
'parameter_details': params,
'defaults': defaults,
'signature_str': str(sig)
}
except Exception as e:
return {'error': str(e)}
def collect_manifest(import_name: str, max_modules: int, walk_all: bool) -> dict:
manifest = {"package": import_name, "symbols": []}
summary = {"modules_scanned": 0, "symbols_collected": 0, "errors": []}
try:
pkg = importlib.import_module(import_name)
except Exception as e:
summary["errors"].append({"stage": "import_root", "error": repr(e)})
return {"manifest": manifest, "summary": summary}
modules = [pkg.__name__]
if hasattr(pkg, "__path__"):
try:
discovered = [m.name for m in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.')]
modules.extend(discovered)
except Exception as e:
summary["errors"].append({"stage": "walk", "error": repr(e)})
if not walk_all and max_modules is not None:
modules = modules[:max_modules]
for mod_name in modules:
try:
mod = importlib.import_module(mod_name)
except Exception as e:
summary["errors"].append({"stage": "import_module", "module": mod_name, "error": repr(e)})
continue
summary["modules_scanned"] += 1
names = None
try:
names = getattr(mod, "__all__", None)
except Exception:
names = None
if names is None:
try:
names = [n for n in dir(mod) if not n.startswith('_')]
except Exception:
names = []
for n in names:
try:
obj = getattr(mod, n)
except Exception:
continue
kind = None
sig = None
param_info = None
try:
if inspect.isclass(obj):
kind = "class"
try:
sig = str(inspect.signature(obj))
param_info = extract_parameter_info(obj)
except Exception:
sig = None
elif inspect.isfunction(obj) or inspect.ismethod(obj) or inspect.isbuiltin(obj):
kind = "function"
try:
sig = str(inspect.signature(obj))
param_info = extract_parameter_info(obj)
except Exception:
sig = None
elif inspect.ismodule(obj):
kind = "module"
elif callable(obj):
kind = "callable"
try:
sig = str(inspect.signature(obj))
param_info = extract_parameter_info(obj)
except Exception:
sig = None
else:
kind = "attribute"
except Exception:
kind = "unknown"
symbol_entry = {
"module": mod_name,
"name": n,
"qualname": f"{mod_name}.{n}",
"kind": kind,
"signature": sig,
}
# Add detailed parameter info for callable objects
if param_info is not None:
symbol_entry["param_info"] = param_info
manifest["symbols"].append(symbol_entry)
summary["symbols_collected"] += 1
return {"manifest": manifest, "summary": summary}
def main():
if len(sys.argv) < 5:
print("{}", flush=True)
return
import_name = sys.argv[1]
out_path = sys.argv[2]
max_modules = int(sys.argv[3]) if sys.argv[3] else 200
walk_all = sys.argv[4] == "1"
payload = collect_manifest(import_name, max_modules, walk_all)
with open(out_path, 'w') as f:
json.dump(payload, f)
print(out_path, flush=True)
if __name__ == "__main__":
main()
"""
script_path.write_text(script)
def snapshot_public_api(venv_python: Path, repo_path: Path, commit_hash: str, prefer_import_name: Optional[str] = None, work_dir: Optional[Path] = None) -> Optional[Tuple[Path, Dict[str, Any]]]:
"""Generate API manifest for installed package inside venv and return (path, summary)."""
try:
import_name = _select_import_name_via_venv(venv_python, repo_path, prefer=prefer_import_name)
if not import_name:
logger.warning(f"Could not determine import name for API snapshot at {commit_hash}")
return None
out_root = (work_dir or Path.cwd()) / "api_manifests"
out_root.mkdir(parents=True, exist_ok=True)
out_path = out_root / f"{commit_hash[:8]}_{import_name}_api.json"
script_path = (work_dir or Path.cwd()) / f"_api_dump_{commit_hash[:8]}.py"
_write_api_dump_script(script_path)
max_modules = int(os.getenv("ISO_BENCH_API_MAX_MODULES", "200"))
walk_all = "1" if os.getenv("ISO_BENCH_API_WALK_ALL", "0") in ("1", "true", "True") else "0"
r = subprocess.run(
[str(venv_python), str(script_path), import_name, str(out_path), str(max_modules), walk_all],
capture_output=True, text=True, cwd=str(repo_path)
)
if r.returncode != 0:
logger.warning(f"API snapshot script failed for {commit_hash}: {r.stderr}")
try:
script_path.unlink(missing_ok=True) # type: ignore[arg-type]
except Exception:
pass
return None
# Read summary
try:
data = json.loads(_read_text_safe(out_path))
summary = data.get("summary", {}) if isinstance(data, dict) else {}
except Exception:
summary = {}
try:
script_path.unlink(missing_ok=True) # type: ignore[arg-type]
except Exception:
pass
return out_path, summary
except Exception as e:
logger.warning(f"Failed to snapshot API for {commit_hash}: {e}")
return None
def _load_manifest_sets(manifest_path: Path) -> Optional[Tuple[str, set, Dict[str, List[str]]]]:
try:
payload = json.loads(_read_text_safe(manifest_path))
manifest = payload.get("manifest", {}) if isinstance(payload, dict) else {}
package_root = manifest.get("package", "")
symbols = manifest.get("symbols", [])
available: set = set()
leaf_to_quals: Dict[str, List[str]] = {}
for s in symbols:
q = s.get("qualname")
n = s.get("name")
if isinstance(q, str) and isinstance(n, str):
available.add(q)
leaf_to_quals.setdefault(n, []).append(q)
return package_root, available, leaf_to_quals
except Exception as e:
logger.warning(f"Failed to load API manifest sets from {manifest_path}: {e}")
return None
def _parse_imports_and_aliases(code: str) -> Tuple[Dict[str, str], Dict[str, List[Tuple[str, Optional[str]]]]]:
alias_to_module: Dict[str, str] = {}
from_imports: Dict[str, List[Tuple[str, Optional[str]]]] = {}
lines = code.splitlines()
import_re = re.compile(r"^\s*import\s+([\w\.]+)(?:\s+as\s+(\w+))?\s*$")
from_re = re.compile(r"^\s*from\s+([\w\.]+)\s+import\s+(.+)$")
for line in lines:
m = import_re.match(line)
if m:
mod, alias = m.group(1), m.group(2)
alias_to_module[alias or mod.split('.')[-1]] = mod
continue
m = from_re.match(line)
if m:
mod = m.group(1)
names_part = m.group(2)
# remove parentheses and split by commas
names_part = names_part.strip().strip('()')
parts = [p.strip() for p in names_part.split(',') if p.strip()]
entries: List[Tuple[str, Optional[str]]] = []
for p in parts:
segs = p.split()
if len(segs) == 1:
entries.append((segs[0], None))
elif len(segs) == 3 and segs[1] == 'as':
entries.append((segs[0], segs[2]))
from_imports.setdefault(mod, []).extend(entries)
return alias_to_module, from_imports
def _extract_dotted_refs(code: str, alias_to_module: Dict[str, str], package_root: str) -> List[Tuple[str, str]]:
refs: List[Tuple[str, str]] = []
dotted = re.compile(r"\b([A-Za-z_]\w*)\.([A-Za-z_]\w*)\b")
for m in dotted.finditer(code):
left, right = m.group(1), m.group(2)
mod = alias_to_module.get(left)
if not mod:
continue
if not (mod == package_root or mod.startswith(package_root + '.')):
continue
refs.append((left, right))
return refs
def _choose_best_qual(target_leaf: str, origin_module: str, candidates: List[str]) -> Optional[str]:
if not candidates:
return None
# Prefer within same module path or closest path by longest common prefix
best = None
best_score = -1
for q in candidates:
try:
module_path = q.rsplit('.', 1)[0]
except Exception:
module_path = q
score = 0
# exact module match
if module_path == origin_module:
score = 100
else:
# common prefix length on segments
a = origin_module.split('.')
b = module_path.split('.')
k = 0
for x, y in zip(a, b):
if x == y:
k += 1
else:
break
score = k
if score > best_score:
best = q
best_score = score
return best
def _insert_additional_imports(code: str, new_import_lines: List[str]) -> str:
if not new_import_lines:
return code
lines = code.splitlines()
insert_idx = 0
for i, line in enumerate(lines):
if line.strip().startswith(('import ', 'from ')):
insert_idx = i + 1
else:
if insert_idx != 0:
break
return "\n".join(lines[:insert_idx] + new_import_lines + lines[insert_idx:])
def _load_param_info_from_manifest(manifest_path: Path) -> Dict[str, Dict[str, Any]]:
"""Load parameter information for key classes from the manifest."""
try:
payload = json.loads(_read_text_safe(manifest_path))
manifest = payload.get("manifest", {}) if isinstance(payload, dict) else {}
symbols = manifest.get("symbols", [])
param_info = {}
for symbol in symbols:
qualname = symbol.get("qualname", "")
if symbol.get("param_info") and qualname:
param_info[qualname] = symbol["param_info"]
return param_info
except Exception as e:
logger.warning(f"Failed to load parameter info from manifest: {e}")
return {}
def _add_api_probing_helpers(code: str, package_root: str) -> str:
"""Add helper functions for safe API calls to the test script."""
helpers = f'''
import inspect
import logging
# API Probing helpers - auto-generated for compatibility
def safe_create_object(cls, **kwargs):
"""Create object with only valid arguments based on signature."""
try:
if not callable(cls):
raise TypeError(f"{{cls}} is not callable")
sig = inspect.signature(cls)
valid_kwargs = {{k: v for k, v in kwargs.items()
if k in sig.parameters and k != "self"}}
return cls(**valid_kwargs)
except Exception as e:
logging.warning(f"Failed to create {{cls.__name__ if hasattr(cls, '__name__') else cls}} with args {{list(kwargs.keys())}}: {{e}}")
raise
def safe_call_function(func, *args, **kwargs):
"""Call function with only valid arguments based on signature."""
try:
if not callable(func):
raise TypeError(f"{{func}} is not callable")
sig = inspect.signature(func)
# Filter kwargs to only valid parameters
valid_kwargs = {{k: v for k, v in kwargs.items()
if k in sig.parameters}}
return func(*args, **valid_kwargs)
except Exception as e:
logging.warning(f"Failed to call {{func.__name__ if hasattr(func, '__name__') else func}} with args {{list(kwargs.keys())}}: {{e}}")
raise
# Specific helpers for common {package_root} classes
def safe_create_engine_output(**kwargs):
"""Create EngineCoreOutput with compatible arguments."""
try:
from {package_root}.v1.engine import EngineCoreOutput
return safe_create_object(EngineCoreOutput, **kwargs)
except ImportError:
try:
from {package_root}.engine import EngineCoreOutput
return safe_create_object(EngineCoreOutput, **kwargs)
except ImportError:
raise ImportError("EngineCoreOutput not found in {package_root}")
def safe_create_sampling_params(**kwargs):
"""Create SamplingParams with compatible arguments."""
try:
from {package_root} import SamplingParams
return safe_create_object(SamplingParams, **kwargs)
except ImportError:
try:
from {package_root}.sampling_params import SamplingParams
return safe_create_object(SamplingParams, **kwargs)
except ImportError:
raise ImportError("SamplingParams not found in {package_root}")
def safe_create_llm(**kwargs):
"""Create LLM with compatible arguments."""
try:
from {package_root} import LLM
return safe_create_object(LLM, **kwargs)
except ImportError:
raise ImportError("LLM not found in {package_root}")
'''
# Insert helpers after existing imports
lines = code.splitlines()
insert_idx = 0
for i, line in enumerate(lines):
if line.strip().startswith(('import ', 'from ')):
insert_idx = i + 1
else:
if insert_idx != 0:
break
return "\n".join(lines[:insert_idx] + [helpers] + lines[insert_idx:])
def _rewrite_api_calls_in_code(code: str, param_info: Dict[str, Dict[str, Any]]) -> str:
"""Rewrite direct API calls to use safe creation patterns."""
import re
# Common patterns to replace with safe versions
replacements = [
# EngineCoreOutput instantiation
(r'EngineCoreOutput\\(([^)]+)\\)', r'safe_create_engine_output(\\1)'),
# SamplingParams instantiation
(r'SamplingParams\\(([^)]+)\\)', r'safe_create_sampling_params(\\1)'),
# LLM instantiation
(r'(?<!safe_create_)LLM\\(([^)]+)\\)', r'safe_create_llm(\\1)'),
]
modified_code = code
for pattern, replacement in replacements:
modified_code = re.sub(pattern, replacement, modified_code)
return modified_code
def rewrite_test_script_with_api_probing(test_script: Path, manifest_path: Path) -> Dict[str, Any]:
"""Enhanced version that combines manifest rewriting with API probing."""
# First, do the standard manifest-based rewriting
summary = rewrite_test_script_against_manifest(test_script, manifest_path)
# Load parameter information
param_info = _load_param_info_from_manifest(manifest_path)
# Read the current code (after standard rewriting)
code = _read_text_safe(test_script)
if not code:
return summary
# Determine package root
s = _load_manifest_sets(manifest_path)
if s is None:
return summary
package_root, _, _ = s
# Add API probing helpers
code_with_helpers = _add_api_probing_helpers(code, package_root)
# Rewrite API calls to use safe patterns
final_code = _rewrite_api_calls_in_code(code_with_helpers, param_info)
# Write back the enhanced code
test_script.write_text(final_code)
# Add to summary
summary["api_probing_added"] = True
summary["param_info_loaded"] = len(param_info)
return summary
def rewrite_test_script_against_manifest(test_script: Path, manifest_path: Path) -> Dict[str, Any]:
summary: Dict[str, Any] = {"rewrites": [], "added_imports": []}
s = _load_manifest_sets(manifest_path)
if s is None:
return summary
package_root, available, leaf_to_quals = s
code = _read_text_safe(test_script)
if not code:
return summary
alias_to_module, from_imports = _parse_imports_and_aliases(code)
# Only consider aliases mapping to our package root
alias_to_module = {a: m for a, m in alias_to_module.items() if m == package_root or m.startswith(package_root + '.')}
# 1) Fix from-imports where module.path symbol no longer exists
from_rewrites: Dict[Tuple[str, str], str] = {}
for mod, entries in from_imports.items():
if not (mod == package_root or mod.startswith(package_root + '.')):
continue
for name, alias in entries:
qual = f"{mod}.{name}"
if qual in available:
continue
cands = leaf_to_quals.get(name, [])
best = _choose_best_qual(name, mod, cands)
if best and best != qual:
new_mod = best.rsplit('.', 1)[0]
from_rewrites[(mod, name)] = new_mod
summary["rewrites"].append({"type": "from", "old": qual, "new": f"{new_mod}.{name}"})
if from_rewrites:
def _rewrite_from_line(line: str) -> str:
m = re.match(r"^(\s*from\s+)([\w\.]+)(\s+import\s+)(.+)$", line)
if not m:
return line
prefix, mod, mid, tail = m.group(1), m.group(2), m.group(3), m.group(4)
# rebuild tail respecting commas and aliases
parts = [p.strip() for p in tail.strip().strip('()').split(',') if p.strip()]
new_parts: List[str] = []
# Check if any symbols need rewriting to different modules
needs_rewrite = False
dest_modules = set()
changed_symbols = set()
for p in parts:
segs = p.split()
if len(segs) == 1:
name, alias = segs[0], None
elif len(segs) == 3 and segs[1] == 'as':
name, alias = segs[0], segs[2]
else:
continue
key = (mod, name)
dest_mod = from_rewrites.get(key)
if dest_mod:
needs_rewrite = True
dest_modules.add(dest_mod)
changed_symbols.add(name)
if not needs_rewrite:
# No rewrites needed for this line
return line
# Count symbols that don't need rewriting
unchanged_count = sum(1 for p in parts if p.split() and p.split()[0] not in changed_symbols)
# If all symbols that need rewriting go to the same module AND there are no unchanged symbols, rewrite the whole line
if len(dest_modules) == 1 and unchanged_count == 0:
new_mod = dest_modules.pop()
return f"{prefix}{new_mod}{mid}{tail}"
# Otherwise, split into separate import lines
else:
new_import_lines = []
# Group symbols by their target module
module_groups = {}
for p in parts:
segs = p.split()
if len(segs) == 1:
name, alias = segs[0], None
elif len(segs) == 3 and segs[1] == 'as':
name, alias = segs[0], segs[2]
else:
# Invalid import part, skip
continue
key = (mod, name)
dest_mod = from_rewrites.get(key, mod)
if dest_mod not in module_groups:
module_groups[dest_mod] = []
module_groups[dest_mod].append(p)
# Create import lines for each module
for target_mod, symbols in module_groups.items():
new_import_lines.append(f"{prefix}{target_mod}{mid}{', '.join(symbols)}")
return "\n".join(new_import_lines)
code_lines = code.splitlines()
code_lines = [_rewrite_from_line(ln) for ln in code_lines]
code = "\n".join(code_lines)
# 2) For dotted refs alias.symbol, add explicit from-imports and replace usage
dotted_refs = _extract_dotted_refs(code, alias_to_module, package_root)
additions: Dict[str, str] = {} # name -> module
replacements: List[Tuple[str, str]] = [] # (pattern, replacement)
for alias, name in dotted_refs:
origin_module = alias_to_module.get(alias)
if not origin_module:
continue
qual = f"{origin_module}.{name}"
if qual in available:
continue
cands = leaf_to_quals.get(name, [])
best = _choose_best_qual(name, origin_module, cands)
if not best:
continue
new_module = best.rsplit('.', 1)[0]
additions[name] = new_module
# replace only this exact token pattern
pattern = rf"\b{re.escape(alias)}\.{re.escape(name)}\b"
replacements.append((pattern, name))
summary["rewrites"].append({"type": "dotted", "old": qual, "new": f"{new_module}.{name}"})
# Insert new imports if any
new_import_lines = [f"from {mod} import {name}" for name, mod in sorted(additions.items())]
if new_import_lines:
code = _insert_additional_imports(code, new_import_lines)
summary["added_imports"] = new_import_lines
# Apply replacements
if replacements:
for pattern, repl in replacements:
code = re.sub(pattern, repl, code)
try:
test_script.write_text(code)
except Exception as e:
logger.warning(f"Failed to write rewritten test to {test_script}: {e}")
return summary
def _extract_hf_repo_id(hf_repo: Optional[str], default_repo_name: str = "omni_commit_dataset") -> Optional[str]:
"""Normalize various HF repo formats to a repo id suitable for push_to_hub.
Examples:
- "https://huggingface.co/user/repo" -> "user/repo"
- "https://huggingface.co/repo" -> "repo"
- "user/repo" -> "user/repo"
- "repo" -> "repo"
"""
if not hf_repo:
return None
s = hf_repo.strip().rstrip("/")
if "huggingface.co" in s:
# Strip domain
after = s.split("huggingface.co", 1)[1]
after = after.lstrip("/")
# Remove common prefixes like 'datasets/'
if after.startswith("datasets/"):
after = after[len("datasets/"):]
# If path has more than two segments, keep last two
segs = [p for p in after.split("/") if p]
if len(segs) >= 2:
return "/".join(segs[-2:])
if len(segs) == 1:
return f"{segs[0]}/{default_repo_name}"
return None
# Non-URL input
if "/" in s:
return s
# Single segment -> treat as org/user and append default repo name
return f"{s}/{default_repo_name}"
def clone_or_update_repo(repo_url: str, dest_dir: Path) -> Path:
if dest_dir.exists():
return dest_dir
run(["git", "clone", repo_url, str(dest_dir)])
return dest_dir
def checkout_commit(repo_path: Path, commit_hash: str) -> None:
run(["git", "fetch", "--all", "--tags"], cwd=repo_path)
run(["git", "checkout", "--force", commit_hash], cwd=repo_path)
def git_unified_diff(repo_path: Path, base_commit: str, head_commit: str) -> str:
return run(["git", "diff", "-p", base_commit, head_commit], cwd=repo_path)
def get_main_branch_head(repo_path: Path) -> str:
# Try common main branch names
for ref in ("origin/main", "origin/master", "main", "master"):
try:
return run(["git", "rev-parse", ref], cwd=repo_path).strip()
except Exception:
continue
raise RuntimeError("Unable to determine main branch HEAD (tried origin/main, origin/master, main, master)")
def is_test_path(path: str) -> bool:
p = path.lower()
fname = os.path.basename(p)
return (
"/tests/" in p
or p.startswith("tests/")
or fname.startswith("test_")
or fname.endswith("_test.py")
)
def write_tests_to_tmp(tests: List[str], tmp_dir: Path) -> List[Path]:
paths: List[Path] = []
for idx, code in enumerate(tests):
p = tmp_dir / f"perf_test_{idx}.py"
p.write_text(code)
paths.append(p)
return paths
def run_tests_locally(repo_path: Path, commit_hash: str, test_entry: Path) -> List[float]:
"""Checkout commit and run prob_script with CUDA event timing for precise GPU measurement."""
import torch
import time as _time
import subprocess
checkout_commit(repo_path, commit_hash)
try:
# Run from repo root so imports resolve
rel = str(test_entry.relative_to(repo_path))
# Use CUDA events for precise GPU timing if GPU available
if torch.cuda.is_available():
torch.cuda.synchronize() # Ensure GPU is ready
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()
# Run the prob_script - it will execute the performance test
result = subprocess.run([sys.executable, rel], cwd=str(repo_path),
capture_output=True, text=True, timeout=300)
end_event.record()
torch.cuda.synchronize()
# Get precise GPU execution time in milliseconds
execution_time = start_event.elapsed_time(end_event)
else:
# Fallback to CPU timing if no GPU available
start = _time.time()
result = subprocess.run([sys.executable, rel], cwd=str(repo_path),
capture_output=True, text=True, timeout=300)
end = _time.time()
execution_time = (end - start) * 1000 # Convert to milliseconds
# Check for script errors and print output for debugging
if result.returncode != 0:
print(f"Script exited with code {result.returncode}")
print(f"STDOUT: {result.stdout}")
print(f"STDERR: {result.stderr}")
return [float('inf')]
return [execution_time]
except subprocess.TimeoutExpired:
print(f"Script execution timed out after 300 seconds: {test_entry}")
return [300000.0] # 5 minutes in milliseconds
except Exception as e:
print(f"Error running script: {e}")
return [float('inf')]
def check_capability_requirements(test_script: Path) -> bool:
"""Check if current hardware meets test requirements."""
capabilities = detect_capabilities()
if not capabilities["cuda_available"]:
logger.warning("CUDA not available - skipping GPU tests")
return False
# Check specific generator requirements
generator_name = test_script.stem
# FP8-related tests require SM90+ (Hopper GPUs)
fp8_tests = ["8d75fe48", "2a052011"] # Add more FP8 tests as needed
if any(fp8_test in generator_name for fp8_test in fp8_tests):
if not capabilities.get("supports_fp8", False):
logger.warning(f"FP8 not supported (SM{capabilities['sm_version']}, CUDA {capabilities['cuda_version']}) - skipping {generator_name}")
return False
return True
def detect_capabilities() -> Dict[str, Any]:
"""Detect GPU and CUDA capabilities for hardware filtering."""
capabilities = {
"cuda_available": False,
"gpu_name": None,
"cuda_version": None,
"gpu_memory_gb": 0,
"sm_version": None,
"supports_fp8": False
}
try:
import torch
if torch.cuda.is_available():
capabilities["cuda_available"] = True
capabilities["gpu_name"] = torch.cuda.get_device_name(0)
capabilities["gpu_memory_gb"] = torch.cuda.get_device_properties(0).total_memory / (1024**3)
# Get CUDA version
try:
cuda_version = torch.version.cuda
if cuda_version:
capabilities["cuda_version"] = cuda_version
except:
pass
# Get SM version for FP8 requirements
try:
sm_version = torch.cuda.get_device_capability(0)
capabilities["sm_version"] = f"{sm_version[0]}{sm_version[1]}"
# FP8 requires SM90+ (not SM89) and CUDA 12.x
if sm_version[0] >= 9 and cuda_version and cuda_version.startswith("12"):
capabilities["supports_fp8"] = True
else:
capabilities["supports_fp8"] = False
except:
capabilities["supports_fp8"] = False
except ImportError:
pass
logger.info(f"Detected capabilities: {capabilities}")
return capabilities
def run_tests_with_commit_hopping(
test_script: Path,
commit_hash: str,
repo_path: Path,
work_dir: Path,
api_rewrite: bool = False
) -> List[float]:
"""Run test using simple commit-hopping approach with uv.
This is the winning approach: checkout commit, install with uv, run test.
Much simpler than complex environment isolation.
"""
logger.info(f"Running test with commit-hopping for {commit_hash}")
# Check hardware capabilities first
if not check_capability_requirements(test_script):
logger.warning(f"Hardware requirements not met for {test_script}")
return [float('inf')]
# Determine Python version for this commit
python_version = get_python_version_for_commit(commit_hash)
try:
# Save current commit to restore later
current_commit = run(["git", "rev-parse", "HEAD"], cwd=repo_path).strip()
# Checkout target commit
logger.info(f"Checking out commit {commit_hash}")
checkout_commit(repo_path, commit_hash)