-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathworkload_optimizer.py
More file actions
6328 lines (5462 loc) · 246 KB
/
Copy pathworkload_optimizer.py
File metadata and controls
6328 lines (5462 loc) · 246 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
# Copyright (c) 2025 Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""
workload_optimizer.py — Modular workload optimization trajectory pipeline.
Each step can be run independently via subcommands, or all at once via 'run'.
State is persisted in pipeline_state.json so steps can be resumed/rerun.
Subcommands:
benchmark Run initial E2E benchmark (or load existing results)
identify Identify & classify bottleneck kernels from benchmark
list-kernels Show identified kernels (for interactive selection)
optimize Optimize selected kernels (agent + grading loop)
grade Re-grade existing solutions without re-running agent
integrate Re-inject optimized kernels for final benchmark
benchmark-final Run final E2E benchmark with optimized kernels
score Compute trajectory reward and push to leaderboard
report Generate markdown report and replication guide
run Full pipeline (all steps sequentially)
export-rl Export trajectories to RL training dataset format
optimize-kernel Optimize a standalone kernel (no full pipeline needed)
grade-kernel Grade an existing baseline + solution pair
Usage:
# Step-by-step (each step resumes from previous state):
python workload_optimizer.py benchmark -b config.yaml -r /results --skip-benchmark report.json
python workload_optimizer.py identify -r /results --kernel-types triton --top-k 20
python workload_optimizer.py list-kernels -r /results
python workload_optimizer.py optimize -r /results --kernels fused_moe,gemm_bf16
python workload_optimizer.py integrate -r /results --kernels fused_moe,gemm_bf16
python workload_optimizer.py benchmark-final -r /results
python workload_optimizer.py score -r /results --leaderboard
python workload_optimizer.py report -r /results
# Full pipeline in one command:
python workload_optimizer.py run -b config.yaml -r /results --kernel-types triton --leaderboard
"""
from __future__ import annotations
import argparse
import asyncio
import fcntl
import hashlib
import importlib.util
import json
import logging
import os
import re as _re_mod
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
_log = logging.getLogger(__name__)
import yaml
REPO_ROOT = Path(__file__).parent
sys.path.insert(0, str(REPO_ROOT))
sys.path.insert(0, str(REPO_ROOT / "graders"))
sys.path.insert(0, str(REPO_ROOT / "prompts"))
sys.path.insert(0, str(REPO_ROOT / "pipeline"))
from score import (
KernelResult,
VLLM_ROCM_IMAGE_DEFAULT,
cleanup_inference_server,
run_magpie_benchmark,
run_magpie_compare,
parse_compare_result,
extract_tps,
workload_kernel_reward,
workload_model_reward,
trajectory_reward,
)
from kernel_grader import grade_task, find_solution
from reflector import reflect, should_continue
from ground_truth import get_spec as get_ground_truth_spec, build_correctness_config
from trajectory import WorkloadTrajectoryRecord, get_store
from leaderboard import Leaderboard, LeaderboardEntry
from kernel_bottleneck import (
BottleneckKernel,
extract_bottlenecks,
classify_kernel,
match_to_kernel_spec,
detect_origin_library,
filter_by_types,
filter_by_names,
deduplicate_by_spec,
format_bottleneck_table,
)
from kernel_prompt import (
KERNEL_SPECS,
KERNEL_MAP,
KernelSpec,
applicable_kernels as _applicable_kernels,
build_kernel_prompt as _build_rich_kernel_prompt,
_format_sources_block,
ARCH_MAP,
DEFAULT_TARGET,
)
from models import MODELS, ModelConfig
MAGPIE_ROOT = Path(os.environ.get(
"MAGPIE_ROOT",
str(REPO_ROOT.parent / "Magpie"),
))
os.environ.setdefault("MAGPIE_ROOT", str(MAGPIE_ROOT))
_GLOBAL_GAP_CACHE_DIR = Path.home() / ".cache" / "apex" / "gap_analysis"
def _gap_cache_key(benchmark_config: str) -> str:
"""Stable cache key derived from benchmark config file content."""
import hashlib
cfg_path = Path(benchmark_config)
if cfg_path.exists():
content = cfg_path.read_bytes()
else:
content = benchmark_config.encode()
return hashlib.sha256(content).hexdigest()[:16]
_KERNEL_SPEC_TO_MODULE: dict[str, dict[str, str]] = {
"paged_attn_decode": {
"aiter": "aiter.ops.triton.pa_decode",
"vllm": "vllm.v1.attention.ops.triton_unified_attention",
},
"paged_attn_decode_gluon": {
"aiter": "aiter.ops.triton.pa_decode_gluon",
},
"flash_attn_prefill": {
"aiter": "aiter.ops.triton.attention.pa_prefill",
"vllm": "vllm.v1.attention.ops.triton_prefill_attention",
},
"mla_attn": {
"aiter": "aiter.mla",
"vllm": "vllm.v1.attention.ops.flashmla",
},
"gemm_w8a8": {
"aiter": "aiter.ops.gemm_op_a8w8",
"vllm": "vllm.model_executor.layers.quantization.utils.fp8_utils",
},
"gemm_bf16": {
"aiter": "aiter.ops.gemm_op_a16w16",
},
"fused_moe": {
"aiter": "aiter.fused_moe",
"vllm": "vllm.model_executor.layers.fused_moe.fused_moe",
},
"rms_norm": {
"aiter": "aiter.ops.triton.normalization.rmsnorm",
"vllm": "vllm.model_executor.layers.layernorm",
},
"silu_mul": {
"aiter": "aiter.ops.activation",
"vllm": "vllm.model_executor.layers.activation",
},
"act_quant_fp8": {
"aiter": "aiter.ops.quant",
"vllm": "vllm.model_executor.layers.quantization.utils.fp8_utils",
},
"rope_embedding": {
"aiter": "aiter.ops.triton.rope.rope",
"vllm": "vllm.model_executor.layers.rotary_embedding",
},
"kv_cache_ops": {
"aiter": "aiter.ops.cache",
"vllm": "vllm.v1.attention.ops.triton_reshape_and_cache_flash",
},
"all_reduce": {
"aiter": "aiter.dist.device_communicators.custom_all_reduce",
"vllm": "vllm.distributed.device_communicators.custom_all_reduce",
},
}
def _get_module_for_spec(kernel_spec: str, library: str = "aiter") -> Optional[str]:
"""Get the Python module path for a kernel spec in a given library."""
lib_map = _KERNEL_SPEC_TO_MODULE.get(kernel_spec, {})
return lib_map.get(library)
_LIBRARY_PREFIXES: dict[str, list[str]] = {
"aiter": ["aiter.ops.triton", "aiter.ops", "aiter"],
"vllm": ["vllm.v1.attention.ops", "vllm.model_executor.layers",
"vllm.model_executor.layers.fused_moe", "vllm.distributed"],
"sglang": ["sglang.srt.layers", "sglang.srt.layers.attention"],
"pytorch": ["torch.nn.modules", "torch.nn.functional"],
}
_HIP_SPEC_TO_SO: dict[str, dict[str, str]] = {
"all_reduce": {
"aiter": "custom_all_reduce",
"vllm": "_C",
},
"kv_cache_ops": {
"vllm": "_C",
},
"silu_mul": {
"aiter": "activation_kernels",
"vllm": "_C",
},
}
_MONOLITHIC_SO_LIBRARIES = {"vllm", "pytorch", "sglang"}
_DEFAULT_PATCH_DIR = Path("/tmp")
def _patch_lock_path(results_dir: Path | None = None) -> Path:
d = results_dir or _DEFAULT_PATCH_DIR
return d / "magpie_kernel_patch.lock"
def _patch_manifest_path(results_dir: Path | None = None) -> Path:
d = results_dir or _DEFAULT_PATCH_DIR
return d / "magpie_kernel_patch_manifest.json"
# Backwards-compat aliases (used when no results_dir is known)
PATCH_LOCK_PATH = _patch_lock_path()
PATCH_MANIFEST_PATH = _patch_manifest_path()
MIN_SPEEDUP_FOR_REINJECTION = 1.05
SMOKE_TEST_REGRESSION_THRESHOLD = 0.5
_SESSION_BACKUPS: dict[str, str] = {}
def _resolve_installed_module_path(kernel_spec: str, library: str = "aiter") -> Optional[Path]:
"""Resolve a kernel spec to its installed Python module file path.
Tries the static map for the given library first, then auto-discovers
by scanning library-specific module prefixes.
"""
module_name = _get_module_for_spec(kernel_spec, library)
if module_name:
try:
spec = importlib.util.find_spec(module_name)
if spec and spec.origin:
return Path(spec.origin)
except (ModuleNotFoundError, ValueError):
pass
prefixes = _LIBRARY_PREFIXES.get(library, _LIBRARY_PREFIXES["aiter"])
for prefix in prefixes:
candidate = f"{prefix}.{kernel_spec}"
try:
spec = importlib.util.find_spec(candidate)
if spec and spec.origin:
print(f" Auto-discovered module for {kernel_spec}: {candidate}")
return Path(spec.origin)
except (ModuleNotFoundError, ValueError):
continue
# Fallback: try aiter if the requested library didn't resolve
if library != "aiter":
return _resolve_installed_module_path(kernel_spec, library="aiter")
return None
def _clear_pycache(module_path: Path) -> None:
"""Remove __pycache__ for the directory containing a patched module."""
cache_dir = module_path.parent / "__pycache__"
if cache_dir.exists():
shutil.rmtree(cache_dir)
print(f" Cleared bytecode cache: {cache_dir}")
def _is_hip_patchable(kernel_spec: str, library: str) -> bool:
"""Check if a HIP kernel can be patched as a standalone .so."""
if library in _MONOLITHIC_SO_LIBRARIES:
so_map = _HIP_SPEC_TO_SO.get(kernel_spec, {})
so_name = so_map.get(library, "")
if so_name in ("_C", "_custom_ops", ""):
return False
return True
def _find_installed_so(kernel_spec: str, library: str = "aiter") -> Optional[Path]:
"""Find the installed shared library for a HIP kernel spec."""
so_map = _HIP_SPEC_TO_SO.get(kernel_spec, {})
so_name = so_map.get(library)
if not so_name:
return None
if so_name in ("_C", "_custom_ops"):
return None
pkg_name = {"aiter": "aiter", "vllm": "vllm", "sglang": "sglang",
"pytorch": "torch"}.get(library, library)
try:
pkg = importlib.import_module(pkg_name)
pkg_dir = Path(pkg.__file__).parent
for so in pkg_dir.rglob(f"*{so_name}*.so"):
return so
except Exception as e:
_log.debug("SO lookup for %s failed: %s", so_name, e)
return None
def _hipcc_compile(source: Path, build_dir: str, kernel_spec: str, gpu_arch: str = "gfx950") -> Optional[Path]:
"""Compile a .hip/.cu source into a shared library."""
output = Path(build_dir) / f"{kernel_spec}.so"
cmd = [
"hipcc", "-shared", "-fPIC", "-O3",
f"--offload-arch={gpu_arch}",
"-o", str(output),
str(source),
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
print(f" hipcc error: {result.stderr[:500]}")
return None
return output
except (subprocess.TimeoutExpired, FileNotFoundError) as e:
print(f" hipcc failed: {e}")
return None
def _compile_and_patch_hip(
solution_path: Path, kernel_spec: str, gpu_arch: str = "gfx950",
library: str = "aiter",
) -> tuple[Optional[Path], Optional[Path]]:
"""Compile a .hip solution and patch the installed .so library."""
installed_so = _find_installed_so(kernel_spec, library=library)
if not installed_so:
print(f" WARNING: Cannot find installed .so for {kernel_spec}, skipping HIP patch")
return None, None
backup = Path(str(installed_so) + ".bak")
shutil.copy2(installed_so, backup)
with tempfile.TemporaryDirectory(prefix="hip_build_") as build_dir:
compiled = _hipcc_compile(solution_path, build_dir, kernel_spec, gpu_arch)
if compiled and compiled.exists():
shutil.copy2(compiled, installed_so)
print(f" Patched HIP kernel: {installed_so}")
else:
shutil.move(str(backup), str(installed_so))
print(f" WARNING: HIP compilation failed for {kernel_spec}")
return None, None
return installed_so, backup
def _acquire_patch_lock(timeout_s: float = 60.0) -> "IO":
"""Acquire an exclusive file lock with stale-PID detection."""
lock_fd = open(PATCH_LOCK_PATH, "w+")
deadline = time.monotonic() + timeout_s
while True:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
lock_fd.seek(0)
lock_fd.truncate()
lock_fd.write(str(os.getpid()))
lock_fd.flush()
return lock_fd
except BlockingIOError:
# Check if the holding PID is still alive
try:
lock_fd.seek(0)
holder_pid = int(lock_fd.read().strip())
os.kill(holder_pid, 0)
except (ValueError, ProcessLookupError, PermissionError):
print(f" WARNING: Breaking stale patch lock (holder PID gone)")
lock_fd.close()
PATCH_LOCK_PATH.unlink(missing_ok=True)
return _acquire_patch_lock(timeout_s=5.0)
if time.monotonic() > deadline:
lock_fd.close()
raise RuntimeError(
f"Patch lock held by PID {holder_pid} for >{timeout_s}s. "
f"Kill it or delete {PATCH_LOCK_PATH}"
)
time.sleep(2.0)
def _release_patch_lock(lock_fd) -> None:
"""Release the patch lock and clean up lock/manifest files."""
try:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
lock_fd.close()
except Exception as e:
_log.debug("patch lock release failed: %s", e)
PATCH_LOCK_PATH.unlink(missing_ok=True)
PATCH_MANIFEST_PATH.unlink(missing_ok=True)
def _recover_orphaned_patches() -> None:
"""Restore any orphaned patches from a previous crashed run."""
if not PATCH_MANIFEST_PATH.exists():
return
print(" WARNING: Found orphaned kernel patches from a previous crashed run")
try:
manifest = json.loads(PATCH_MANIFEST_PATH.read_text())
for installed, backup in manifest.items():
if Path(backup).exists():
shutil.move(backup, installed)
print(f" Restored: {installed}")
else:
print(f" WARNING: Backup missing, cannot restore: {backup}")
PATCH_MANIFEST_PATH.unlink(missing_ok=True)
print(" Orphaned patches recovered successfully")
except Exception as e:
print(f" WARNING: Failed to recover orphaned patches: {e}")
def _ensure_clean_baseline() -> None:
"""Guarantee all patchable library modules are in original state.
Called once at pipeline startup to prevent cross-session contamination.
"""
_recover_orphaned_patches()
for library in ("aiter", "vllm", "sglang"):
try:
pkg = importlib.import_module(library)
pkg_dir = Path(pkg.__file__).parent
restored = 0
for bak in sorted(pkg_dir.rglob("*.bak")):
original = bak.with_suffix("")
if original.suffix in (".py", ".so") and original.exists():
shutil.copy2(bak, original)
_clear_pycache(original)
restored += 1
bak.unlink()
if restored:
print(f" Restored {restored} leftover patch(es) in {library}")
except ImportError:
continue
PATCH_LOCK_PATH.unlink(missing_ok=True)
PATCH_MANIFEST_PATH.unlink(missing_ok=True)
print(" Baseline libraries verified clean")
def _session_cleanup() -> None:
"""atexit handler: restore any patches made during this session."""
if _SESSION_BACKUPS:
print(f"\n Session cleanup: restoring {len(_SESSION_BACKUPS)} patched module(s)...")
for installed, backup in list(_SESSION_BACKUPS.items()):
try:
if Path(backup).exists():
shutil.copy2(backup, installed)
_clear_pycache(Path(installed))
Path(backup).unlink(missing_ok=True)
except Exception as e:
print(f" WARNING: Failed to restore {installed}: {e}")
_SESSION_BACKUPS.clear()
PATCH_LOCK_PATH.unlink(missing_ok=True)
PATCH_MANIFEST_PATH.unlink(missing_ok=True)
def _register_session_handlers() -> None:
"""Register atexit + signal handlers for guaranteed cleanup."""
import atexit
import signal as _sig
atexit.register(_session_cleanup)
for sig in (_sig.SIGTERM, _sig.SIGINT):
old = _sig.getsignal(sig)
def _handler(signum, frame, _old=old):
_session_cleanup()
if callable(_old) and _old not in (_sig.SIG_DFL, _sig.SIG_IGN):
_old(signum, frame)
else:
raise SystemExit(128 + signum)
_sig.signal(sig, _handler)
def _apply_multi_file_patch(
solution_dir: Path, spec: str, library: str, gpu_arch: str,
backups: dict[Path, Path], write_manifest_fn, ast_module,
) -> None:
"""Apply a multi-file solution from a directory with a manifest.json.
The manifest maps relative file names to their install targets:
{"rmsnorm.py": "aiter.ops.triton.normalization.rmsnorm",
"__init__.py": "aiter.ops.triton.normalization.__init__"}
All files in the manifest are backed up and patched atomically -- if any
file fails, the entire group is rolled back.
"""
manifest_path = solution_dir / "manifest.json"
if not manifest_path.exists():
print(f" WARNING: Multi-file solution dir {solution_dir} has no manifest.json, skipping")
return
try:
manifest = json.loads(manifest_path.read_text())
except (json.JSONDecodeError, OSError) as e:
print(f" REJECTED multi-file {spec}: bad manifest.json: {e}")
return
group_backups: list[tuple[Path, Path]] = []
group_ok = True
for filename, target_module in manifest.items():
src = solution_dir / filename
if not src.exists():
print(f" REJECTED multi-file {spec}: missing file {filename}")
group_ok = False
break
if src.suffix == ".py":
try:
ast_module.parse(src.read_text())
except SyntaxError as e:
print(f" REJECTED multi-file {spec}/{filename}: syntax error: {e}")
group_ok = False
break
installed_path = _resolve_module_to_path(target_module)
if not installed_path:
print(f" WARNING: Cannot resolve {target_module} for {spec}/{filename}, skipping group")
group_ok = False
break
backup = Path(str(installed_path) + ".bak")
shutil.copy2(installed_path, backup)
shutil.copy2(src, installed_path)
_fixup_patched_imports(installed_path, library=library)
_clear_pycache(installed_path)
group_backups.append((installed_path, backup))
_SESSION_BACKUPS[str(installed_path)] = str(backup)
print(f" Patched (multi): {installed_path} <- {filename}")
else:
print(f" WARNING: Multi-file patch skipping non-.py file {filename}")
if not group_ok:
for installed_path, backup in group_backups:
shutil.copy2(backup, installed_path)
_clear_pycache(installed_path)
_SESSION_BACKUPS.pop(str(installed_path), None)
print(f" Rolled back multi-file group for {spec}")
return
for installed_path, backup in group_backups:
backups[installed_path] = backup
write_manifest_fn()
def _resolve_module_to_path(module_name: str) -> Optional[Path]:
"""Resolve a dotted module name to its installed file path."""
import importlib
try:
spec = importlib.util.find_spec(module_name)
if spec and spec.origin:
return Path(spec.origin)
except (ModuleNotFoundError, ValueError):
pass
return None
def _resolve_benchmark_docker_image(
benchmark_config_path: str = "",
docker_image: str = "",
) -> str:
"""Resolve the Docker image the benchmark will actually use."""
if docker_image:
return docker_image
if benchmark_config_path:
try:
cfg = yaml.safe_load(Path(benchmark_config_path).read_text()) or {}
bench = cfg.get("benchmark", {})
if bench.get("docker_image"):
return str(bench["docker_image"])
if str(bench.get("framework", "")).lower() == "vllm":
return os.environ.get("APEX_VLLM_ROCM_IMAGE", "") or VLLM_ROCM_IMAGE_DEFAULT
except Exception:
pass
return os.environ.get("APEX_VLLM_ROCM_IMAGE", "") or VLLM_ROCM_IMAGE_DEFAULT
def _get_container_site_packages(
docker_image: str = "",
benchmark_config_path: str = "",
) -> str:
"""Probe the benchmark Docker image for its Python site-packages path."""
resolved_image = _resolve_benchmark_docker_image(
benchmark_config_path=benchmark_config_path,
docker_image=docker_image,
)
if resolved_image:
try:
result = subprocess.run(
["docker", "run", "--rm", resolved_image,
"python3", "-c",
"import site; print(site.getsitepackages()[0])"],
capture_output=True, text=True, timeout=30,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except Exception:
pass
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}"
return f"/usr/local/lib/python{py_ver}/dist-packages"
def _site_packages_relative(path: str) -> Optional[str]:
"""Return the portion of a path after site/dist-packages, if present."""
for marker in ("site-packages/", "dist-packages/"):
if marker in path:
return path.split(marker, 1)[1]
return None
def _hook_docker_volumes(
backups: dict[Path, Path],
docker_image: str = "",
benchmark_config_path: str = "",
) -> callable:
"""Monkey-patch subprocess.Popen to inject -v mounts for patched files.
Returns an unhook callable that restores the original Popen.
This lets Apex inject patched kernels into Magpie's Docker containers
without modifying any Magpie code.
"""
import subprocess as _sp
container_site_packages = _get_container_site_packages(
docker_image=docker_image,
benchmark_config_path=benchmark_config_path,
)
volume_flags: list[str] = []
for patched_path in backups:
host = str(patched_path.resolve())
rel = _site_packages_relative(host)
if rel:
container = f"{container_site_packages}/{rel}"
else:
container = host
volume_flags.extend(["-v", f"{host}:{container}"])
print(f" Docker mount: {host} -> {container}")
if not volume_flags:
return lambda: None
_orig_popen = _sp.Popen
class _PatchedPopen(_orig_popen):
def __init__(self, args, *a, **kw):
if isinstance(args, (list, tuple)) and len(args) > 1:
args = list(args)
if args[0] == "docker" and "run" in args[:3]:
run_idx = args.index("run")
for i, flag in enumerate(volume_flags):
args.insert(run_idx + 1 + i, flag)
super().__init__(args, *a, **kw)
_sp.Popen = _PatchedPopen
def _unhook():
_sp.Popen = _orig_popen
return _unhook
def _apply_kernel_patches(
reinjected_dir: Path, gpu_arch: str = "gfx950",
) -> tuple[dict[Path, Path], "IO"]:
"""Patch installed kernel modules with optimized solutions.
Supports both single-file solutions (*_solution.py) and multi-file
solution directories (*_solution/ with manifest.json).
Reads per-solution .library metadata files to determine which library
to target. The manifest is written incrementally after each patch so
that ``_recover_orphaned_patches()`` can restore even if the process
crashes mid-way.
Returns (backups_dict, lock_fd) for use with _restore_kernel_patches.
"""
import ast as _ast
_recover_orphaned_patches()
lock_fd = _acquire_patch_lock()
backups: dict[Path, Path] = {}
def _write_manifest() -> None:
PATCH_MANIFEST_PATH.write_text(json.dumps(
{str(k): str(v) for k, v in backups.items()}
))
try:
if not reinjected_dir.exists():
print(" No reinjected directory found -- nothing to patch")
return backups, lock_fd
# Single-file solutions
for solution_file in sorted(reinjected_dir.glob("*_solution.*")):
if solution_file.is_dir():
continue
spec = solution_file.name.split("_solution")[0]
suffix = solution_file.suffix
lib_meta = solution_file.parent / f"{solution_file.name}.library"
library = "aiter"
if lib_meta.exists():
library = lib_meta.read_text().strip() or "aiter"
is_python = suffix == ".py"
if not is_python and suffix in (".hip", ".cu"):
try:
_ast.parse(solution_file.read_text())
is_python = True
print(f" {spec}: {suffix} file contains valid Python — treating as .py patch")
except SyntaxError:
pass
if is_python:
try:
_ast.parse(solution_file.read_text())
except SyntaxError as e:
print(f" REJECTED {spec}: solution has syntax error: {e}")
continue
installed_path = _resolve_installed_module_path(spec, library=library)
if not installed_path:
print(f" WARNING: No installed module for {spec} (library={library}), skipping")
continue
backup = Path(str(installed_path) + ".bak")
shutil.copy2(installed_path, backup)
shutil.copy2(solution_file, installed_path)
_fixup_patched_imports(installed_path, library=library)
_clear_pycache(installed_path)
backups[installed_path] = backup
_SESSION_BACKUPS[str(installed_path)] = str(backup)
_write_manifest()
print(f" Patched: {installed_path} (library={library})")
elif suffix in (".hip", ".cu"):
if not _is_hip_patchable(spec, library):
print(f" Skipping HIP patch for {spec}: {library} compiles into "
f"monolithic _C.so (not individually patchable)")
continue
installed, backup = _compile_and_patch_hip(
solution_file, spec, gpu_arch, library=library,
)
if installed and backup:
backups[installed] = backup
_SESSION_BACKUPS[str(installed)] = str(backup)
_write_manifest()
else:
print(f" WARNING: Unknown solution type {suffix} for {spec}")
# Multi-file solution directories
for solution_dir in sorted(reinjected_dir.glob("*_solution")):
if not solution_dir.is_dir():
continue
spec = solution_dir.name.split("_solution")[0]
lib_meta = solution_dir.parent / f"{solution_dir.name}.library"
library = "aiter"
if lib_meta.exists():
library = lib_meta.read_text().strip() or "aiter"
_apply_multi_file_patch(
solution_dir, spec, library, gpu_arch,
backups, _write_manifest, _ast,
)
except Exception:
_restore_kernel_patches(backups, lock_fd)
raise
return backups, lock_fd
def _restore_kernel_patches(
backups: dict[Path, Path], lock_fd=None,
) -> None:
"""Restore all backed-up modules and release the patch lock."""
for installed, backup in backups.items():
try:
if backup.exists():
shutil.move(str(backup), str(installed))
_clear_pycache(installed)
_SESSION_BACKUPS.pop(str(installed), None)
print(f" Restored: {installed}")
else:
print(f" WARNING: Backup missing for {installed}")
except Exception as e:
print(f" ERROR restoring {installed}: {e}")
if lock_fd:
_release_patch_lock(lock_fd)
def _verify_patched_kernels(
backups: dict[Path, Path],
config: "WorkloadConfig",
) -> list[Path]:
"""Run correctness checks on patched installed modules.
For each patched module:
1. Verify it imports without error
2. If a testcase.py exists in the corresponding task dir, run it
3. Run the library's own test suite via ground_truth MANUAL_REGISTRY
Returns list of installed paths that failed verification (already rolled back).
"""
import importlib
_MODULE_TO_SPEC: dict[str, str] = {}
for kspec, lib_map in _KERNEL_SPEC_TO_MODULE.items():
for _lib, mod_name in lib_map.items():
_MODULE_TO_SPEC[mod_name] = kspec
failed: list[Path] = []
for installed_path, backup_path in list(backups.items()):
spec_name = installed_path.stem
module_name = None
for mod, kspec in _MODULE_TO_SPEC.items():
try:
s = importlib.util.find_spec(mod)
if s and s.origin and Path(s.origin) == installed_path:
module_name = mod
spec_name = kspec
break
except (ModuleNotFoundError, ValueError):
continue
# Fallback: derive module name from filesystem path when static map misses
if module_name is None:
parts = installed_path.parts
sp_idx = next(
(i for i, p in enumerate(parts) if p == "site-packages"), None
)
if sp_idx is not None and installed_path.suffix == ".py":
mod_parts = list(parts[sp_idx + 1:])
if mod_parts:
last = mod_parts[-1]
if last.endswith(".py"):
mod_parts[-1] = last[:-3]
candidate = ".".join(mod_parts)
if candidate.endswith(".__init__"):
candidate = candidate[: -len(".__init__")]
module_name = candidate
print(f" Derived module name: {module_name} (from path)")
# 1. Import check
if module_name:
try:
importlib.invalidate_caches()
mod = importlib.import_module(module_name)
importlib.reload(mod)
print(f" VERIFIED import: {module_name}")
except Exception as e:
print(f" FAILED import for {spec_name}: {e}")
shutil.copy2(backup_path, installed_path)
_clear_pycache(installed_path)
print(f" Rolled back: {installed_path}")
failed.append(installed_path)
continue
# 2. Testcase check (from task dir)
testcase_ran = False
if hasattr(config, "output_dir"):
task_id_patterns = [
f"workload__vllm__{spec_name}",
f"workload__sglang__{spec_name}",
]
for pattern in task_id_patterns:
task_dir = config.output_dir / pattern
testcase = task_dir / "testcase.py"
if testcase.exists():
try:
result = subprocess.run(
[sys.executable, str(testcase)],
capture_output=True, text=True, timeout=120,
cwd=str(task_dir),
)
if result.returncode != 0:
print(f" FAILED testcase for {spec_name}: {result.stderr[:200]}")
shutil.copy2(backup_path, installed_path)
_clear_pycache(installed_path)
print(f" Rolled back: {installed_path}")
failed.append(installed_path)
testcase_ran = True
else:
print(f" VERIFIED testcase: {spec_name}")
testcase_ran = True
except subprocess.TimeoutExpired:
print(f" TIMEOUT testcase for {spec_name}")
shutil.copy2(backup_path, installed_path)
_clear_pycache(installed_path)
failed.append(installed_path)
testcase_ran = True
break
if installed_path in failed:
continue
# 3. Library test verification via ground_truth MANUAL_REGISTRY
gt_spec = get_ground_truth_spec(spec_name)
if gt_spec and gt_spec.unit_test_command and gt_spec.source_library:
working_dir = REPO_ROOT / "tools" / "rocm" / gt_spec.source_library
if working_dir.is_dir():
print(f" Running library test for {spec_name}: {gt_spec.unit_test_command}")
try:
lib_result = subprocess.run(
gt_spec.unit_test_command,
shell=True,
cwd=str(working_dir),
capture_output=True,
text=True,
timeout=180,
)
if lib_result.returncode != 0:
print(f" FAILED library test for {spec_name} "
f"(exit {lib_result.returncode}): {lib_result.stderr[:300]}")
shutil.copy2(backup_path, installed_path)
_clear_pycache(installed_path)
print(f" Rolled back: {installed_path}")
failed.append(installed_path)
else:
print(f" VERIFIED library test: {spec_name}")
except subprocess.TimeoutExpired:
print(f" TIMEOUT library test for {spec_name} (180s)")
shutil.copy2(backup_path, installed_path)
_clear_pycache(installed_path)
failed.append(installed_path)
except Exception as e:
print(f" WARNING: library test error for {spec_name}: {e}")
return failed
# ---------------------------------------------------------------------------
# Dispatch path validation (Fix 7)
# ---------------------------------------------------------------------------
def _validate_optimization_relevance(
solution_path: Path,
baseline_path: Optional[Path],
benchmark_config: dict,
model_config: dict,
kernel_spec: str,
) -> Optional[str]:
"""Check if the optimization targets a code path actually used at runtime.
Returns a warning string if the optimization is likely a no-op, else None.
"""
if kernel_spec != "paged_attn_decode":
return None
if not baseline_path or not baseline_path.exists() or not solution_path.exists():
return None
try:
baseline_text = baseline_path.read_text()
solution_text = solution_path.read_text()
except OSError:
return None
baseline_partition = _re_mod.search(r'_SEQ_PARTITION_SIZE\s*=\s*(\d+)', baseline_text)
solution_partition = _re_mod.search(r'_SEQ_PARTITION_SIZE\s*=\s*(\d+)', solution_text)
if not baseline_partition or not solution_partition:
return None
if baseline_partition.group(1) == solution_partition.group(1):
return None
bench_section = benchmark_config.get("benchmark", {})
envs = bench_section.get("envs", {})
conc = int(envs.get("CONC", 64))
osl = int(envs.get("OSL", 1024))
num_q_heads = model_config.get("num_q_heads", 0)
if num_q_heads == 0:
return None
num_seqs_times_heads = conc * num_q_heads
max_seq_len = osl
use_v1 = (num_seqs_times_heads > 512) and (max_seq_len <= 8192)
if use_v1:
return (
f"WARNING: Optimization modifies V2 path (_SEQ_PARTITION_SIZE "
f"{baseline_partition.group(1)}->{solution_partition.group(1)}) but workload "
f"uses V1 path (max_seq_len={max_seq_len} <= 8192 and "
f"num_seqs*num_q_heads={num_seqs_times_heads} > 512). "
f"This optimization may have NO EFFECT on the actual workload."
)
return None