-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathengineV4.py
More file actions
1667 lines (1491 loc) · 57.3 KB
/
Copy pathengineV4.py
File metadata and controls
1667 lines (1491 loc) · 57.3 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
from __future__ import annotations
import argparse
import gc
import multiprocessing as mp
import os
import queue
import re
import shlex
import shutil
import signal
import subprocess
import sys
import threading
import time
from collections import deque
from dataclasses import dataclass
from datetime import datetime
from multiprocessing import cpu_count, set_start_method
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING
import numpy as np
import pynvml
import yaml
if TYPE_CHECKING:
import paddle
import torch
from tester import (
APIConfig,
APITestAccuracy,
APITestAccuracyStable,
APITestCINNVSDygraph,
APITestCustomDeviceVSCPU,
APITestPaddleDeviceVSGPU,
APITestPaddleGPUPerformance,
APITestPaddleOnly,
APITestPaddleTorchGPUPerformance,
APITestTorchGPUPerformance,
)
from tester.api_config.log_writer import *
os.environ["FLAGS_use_system_allocator"] = "1"
os.environ["NVIDIA_TF32_OVERRIDE"] = "0"
VALID_TEST_ARGS = {
"test_amp",
"test_backward",
"atol",
"rtol",
"test_tol",
"operation_mode",
"bos_path",
"random_seed",
"bos_conf_path",
"bcecmd_path",
"generate_failed_tests",
"bitwise_alignment",
"exit_on_error",
}
SANITIZER_FORWARD_ARGS = {
"accuracy",
"paddle_only",
"paddle_cinn",
"paddle_gpu_performance",
"torch_gpu_performance",
"paddle_torch_gpu_performance",
"accuracy_stable",
"paddle_custom_device",
"custom_device_vs_gpu",
"custom_device_vs_gpu_mode",
"test_amp",
"test_cpu",
"use_cached_numpy",
"log_dir",
"required_memory",
"atol",
"rtol",
"test_tol",
"test_backward",
"show_runtime_status",
"random_seed",
"bitwise_alignment",
"generate_failed_tests",
"exit_on_error",
}
DEVICE_TYPE = None
DEVICE_TYPE_DETECTED = False
DEVICE_COUNT = None # total number of devices
_MEM_SNAPSHOT = None # dict: gpu_id -> (total_gb, used_gb)
_MEM_SNAPSHOT_TS = 0.0
_NVML_INITIALIZED = False # persistent NVML session for repeated memory queries
_MEM_SNAPSHOT_TTL = 2.0 # seconds — snapshot cache ttl
def cleanup(pool):
print(f"{datetime.now()} Cleanup started", flush=True)
if pool is not None:
try:
pool.shutdown(force=True)
except Exception as e:
print(f"{datetime.now()} Error shutting down pool: {e}", flush=True)
print(f"{datetime.now()} Cleanup completed", flush=True)
# ─── WorkerPool: per-worker queue architecture ───────────────────────────────
@dataclass
class WorkerSlot:
"""Represents one worker process slot with its own input queue."""
index: int
gpu_id: int
process: mp.Process | None = None
input_queue: mp.Queue | None = None
current_task: str | None = None
task_start_time: float | None = None
child_pid: int | None = None
state: str = "dead" # dead, starting, idle, busy
def _init_worker_runtime(slot_index, gpu_id, options, *, redirect_output):
if options.log_dir:
set_test_log_path(options.log_dir)
set_engineV2()
if gpu_id is not None:
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
import paddle
import torch
try:
import paddlefleet_ops # noqa: F401
except ImportError:
pass
try:
import FusedQuantOps # noqa: F401
except ImportError:
pass
globals()["torch"] = torch
globals()["paddle"] = paddle
from tester import (
APIConfig,
APITestAccuracy,
APITestAccuracyStable,
APITestCINNVSDygraph,
APITestCustomDeviceVSCPU,
APITestPaddleDeviceVSGPU,
APITestPaddleGPUPerformance,
APITestPaddleOnly,
APITestPaddleTorchGPUPerformance,
APITestTorchGPUPerformance,
)
test_classes = {
"APIConfig": APIConfig,
"APITestAccuracy": APITestAccuracy,
"APITestCINNVSDygraph": APITestCINNVSDygraph,
"APITestPaddleOnly": APITestPaddleOnly,
"APITestPaddleGPUPerformance": APITestPaddleGPUPerformance,
"APITestTorchGPUPerformance": APITestTorchGPUPerformance,
"APITestPaddleTorchGPUPerformance": APITestPaddleTorchGPUPerformance,
"APITestAccuracyStable": APITestAccuracyStable,
"APITestCustomDeviceVSCPU": APITestCustomDeviceVSCPU,
"APITestPaddleDeviceVSGPU": APITestPaddleDeviceVSGPU,
}
globals().update(test_classes)
if options.test_cpu:
paddle.device.set_device("cpu")
if redirect_output:
redirect_stdio()
if slot_index is not None and gpu_id is not None:
print(
f"{datetime.now()} Worker PID: {os.getpid()}, Slot: {slot_index}, GPU: {gpu_id}",
flush=True,
)
def _worker_loop(slot_index, gpu_id, input_queue, result_queue, options):
"""Long-running worker process. Receives tasks from input_queue, sends results to result_queue.
Exit behavior:
- Normal exit: receives None (poison pill) from input_queue, returns gracefully.
- Fatal CUDA error: run_test_case calls os._exit(99) for unrecoverable CUDA errors
(corruption, device-side asserts). This bypasses Python cleanup — the main process
Watchdog detects the dead process via is_alive() check and respawns a new worker.
- OOM: os._exit(98) for CUDA out-of-memory. Same recovery path as above.
- Other crashes: any unhandled signal (SIGSEGV etc.) or SIGKILL from Watchdog timeout
terminates the process. Watchdog detects exitcode != 0 and respawns.
The main process never dispatches to a dead/restarting worker — upon detecting crash or
timeout, the next task goes to `pending_dispatch` and is sent after the new worker reports
"ready".
"""
# ── GPU initialization (equivalent to init_worker_gpu) ──
try:
_init_worker_runtime(slot_index, gpu_id, options, redirect_output=True)
except Exception as e:
print(f"{datetime.now()} Worker {os.getpid()} init failed: {e}", flush=True)
result_queue.put(("init_failed", slot_index, str(e)))
return
# ── Notify main: ready ──
result_queue.put(("ready", slot_index))
# ── Task loop ──
while True:
try:
task = input_queue.get()
except (EOFError, OSError):
break
if task is None: # poison pill
break
api_config_str = task
result_queue.put(("ack", slot_index, api_config_str))
try:
run_test_case(api_config_str, options)
result_queue.put(("done", slot_index, api_config_str))
except SystemExit:
# run_test_case calls os._exit for CUDA errors, this shouldn't reach here
# but if it does via sys.exit, let it propagate
raise
except Exception as e:
result_queue.put(("error", slot_index, api_config_str, str(e)))
# Graceful exit
try:
close_process_files()
restore_stdio()
except Exception:
pass
def _format_cli_value(value):
if isinstance(value, bool):
return "True" if value else "False"
return str(value)
def _build_sanitizer_case_command(api_config_str, options):
cmd = [
*shlex.split(options.sanitizer_command),
sys.executable,
str(Path(__file__).resolve()),
f"--api_config={api_config_str}",
"--_sanitizer_child=True",
]
for key in sorted(SANITIZER_FORWARD_ARGS):
value = getattr(options, key, None)
if value is None:
continue
if isinstance(value, str) and value == "":
continue
if isinstance(value, bool) and not value:
continue
cmd.append(f"--{key}={_format_cli_value(value)}")
return cmd
def _sanitizer_worker_loop(slot_index, gpu_id, input_queue, result_queue, options):
if options.log_dir:
set_test_log_path(options.log_dir)
set_engineV2()
redirect_stdio()
child_process = None
def terminate_child(*args):
if child_process is not None and child_process.poll() is None:
try:
os.killpg(child_process.pid, signal.SIGKILL)
except (ProcessLookupError, OSError):
child_process.kill()
raise SystemExit(1)
signal.signal(signal.SIGINT, terminate_child)
signal.signal(signal.SIGTERM, terminate_child)
try:
print(
f"{datetime.now()} Sanitizer worker PID: {os.getpid()}, Slot: {slot_index}, GPU: {gpu_id}",
flush=True,
)
result_queue.put(("ready", slot_index))
while True:
try:
task = input_queue.get()
except (EOFError, OSError):
break
if task is None:
break
api_config_str = task
result_queue.put(("ack", slot_index, api_config_str))
try:
cmd = _build_sanitizer_case_command(api_config_str, options)
except ValueError as err:
result_queue.put(("error", slot_index, api_config_str, str(err)))
continue
env = os.environ.copy()
env["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
print(
f"{datetime.now()} Sanitizer slot {slot_index} launch: {' '.join(shlex.quote(part) for part in cmd)}",
flush=True,
)
try:
child_process = subprocess.Popen(
cmd,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
start_new_session=True,
)
except OSError as err:
result_queue.put(("error", slot_index, api_config_str, str(err)))
continue
result_queue.put(("child", slot_index, child_process.pid))
output_lines = deque(maxlen=40)
try:
for line in child_process.stdout:
output_lines.append(line)
print(line, end="", flush=True)
returncode = child_process.wait()
finally:
if child_process.stdout is not None:
child_process.stdout.close()
child_process = None
if returncode == 0:
result_queue.put(("done", slot_index, api_config_str))
elif returncode == 2:
output_tail = "".join(output_lines)
result_queue.put(("error", slot_index, api_config_str, output_tail))
else:
output_tail = "".join(output_lines)
result_queue.put(("crashed", slot_index, api_config_str, returncode, output_tail))
finally:
if child_process is not None and child_process.poll() is None:
try:
os.killpg(child_process.pid, signal.SIGKILL)
except (ProcessLookupError, OSError):
child_process.kill()
try:
child_process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
try:
close_process_files()
restore_stdio()
except Exception:
pass
class WorkerPool:
"""Custom process pool with per-worker queues for fair GPU scheduling."""
def __init__(self, available_gpus, max_workers_per_gpu, options):
# Convert argparse.Namespace to SimpleNamespace(dict) for cleaner pickling to workers
if isinstance(options, argparse.Namespace):
self.options = SimpleNamespace(**vars(options))
else:
self.options = options
self.result_queue = mp.Queue()
self.slots: list[WorkerSlot] = []
self._shutdown_event = threading.Event()
self._watchdog_thread = None
self._lock = threading.Lock() # protects slot state modifications
self._closed = False
# Build worker slots: deterministic GPU assignment
idx = 0
for gpu_id in available_gpus:
for _ in range(max_workers_per_gpu[gpu_id]):
slot = WorkerSlot(index=idx, gpu_id=gpu_id)
self.slots.append(slot)
idx += 1
@property
def total_workers(self):
return len(self.slots)
def start(self):
"""Spawn all worker processes and start watchdog thread."""
for slot in self.slots:
self._spawn_worker(slot)
self._watchdog_thread = threading.Thread(
target=self._watchdog_loop, daemon=True, name="pool-watchdog"
)
self._watchdog_thread.start()
def _close_queue(self, q, *, cancel_join=False):
"""Close a multiprocessing queue without letting cleanup errors mask test results."""
if q is None:
return
try:
if cancel_join:
q.cancel_join_thread()
except Exception:
pass
try:
q.close()
except Exception:
pass
if not cancel_join:
try:
q.join_thread()
except Exception:
pass
def _spawn_worker(self, slot):
"""Spawn a new worker process for the given slot."""
if self._closed or self._shutdown_event.is_set():
return False
if slot.process is not None and not slot.process.is_alive():
self._join_process(slot.process, timeout=1)
self._close_queue(slot.input_queue, cancel_join=True)
slot.input_queue = mp.Queue()
worker_target = (
_sanitizer_worker_loop
if getattr(self.options, "use_compute_sanitizer", False)
else _worker_loop
)
p = mp.Process(
target=worker_target,
args=(slot.index, slot.gpu_id, slot.input_queue, self.result_queue, self.options),
daemon=True,
)
p.start()
slot.process = p
slot.state = "starting"
slot.current_task = None
slot.task_start_time = None
slot.child_pid = None
return True
def warmup(self, timeout=180):
"""Wait for all workers to report ready."""
ready_count = 0
deadline = time.time() + timeout
failed_slots = []
while ready_count < self.total_workers and time.time() < deadline:
try:
remaining = max(0.1, deadline - time.time())
msg = self.result_queue.get(timeout=min(5.0, remaining))
msg_type = msg[0]
if msg_type == "ready":
slot_idx = msg[1]
with self._lock:
self.slots[slot_idx].state = "idle"
ready_count += 1
elif msg_type == "init_failed":
slot_idx = msg[1]
error_msg = msg[2]
failed_slots.append((slot_idx, error_msg))
ready_count += 1 # count as handled
print(
f"{datetime.now()} Worker slot {slot_idx} init failed: {error_msg}",
flush=True,
)
except queue.Empty:
# Check for dead processes
for slot in self.slots:
if slot.state == "starting" and slot.process and not slot.process.is_alive():
print(
f"{datetime.now()} Worker slot {slot.index} died during init (exit={slot.process.exitcode})",
flush=True,
)
self._spawn_worker(slot)
if ready_count < self.total_workers:
print(
f"{datetime.now()} WARNING: Only {ready_count}/{self.total_workers} workers ready after {timeout}s",
flush=True,
)
def dispatch(self, slot_index, config):
"""Send a task to a specific worker slot."""
slot = self.slots[slot_index]
with self._lock:
slot.current_task = config
slot.task_start_time = None # set when ack received
slot.state = "busy"
slot.input_queue.put(config)
def collect_one(self, timeout=5.0):
"""Get one message from result_queue. Returns None on timeout."""
try:
return self.result_queue.get(timeout=timeout)
except queue.Empty:
return None
def idle_slots(self):
"""Yield slots that are currently idle."""
for slot in self.slots:
if slot.state == "idle":
yield slot
def mark_idle(self, slot_index):
"""Mark a worker slot as idle after task completion."""
with self._lock:
slot = self.slots[slot_index]
slot.state = "idle"
slot.current_task = None
slot.task_start_time = None
slot.child_pid = None
def _watchdog_loop(self):
"""Periodically check for timeouts and unexpectedly dead workers."""
while not self._shutdown_event.is_set():
if self._shutdown_event.wait(1.0):
break
now = time.time()
for slot in self.slots:
if self._shutdown_event.is_set():
break
with self._lock:
if self._shutdown_event.is_set():
break
# Check timeout
if (
slot.state == "busy"
and slot.task_start_time is not None
and now - slot.task_start_time > self.options.timeout
):
self._handle_timeout(slot)
continue
if self._shutdown_event.is_set():
break
# Check unexpected death
if (
slot.state in ("busy", "idle")
and slot.process is not None
and not slot.process.is_alive()
):
self._handle_crash(slot)
def _handle_timeout(self, slot):
"""Kill timed-out worker and enqueue timeout result."""
if self._closed or self._shutdown_event.is_set():
return
config = slot.current_task
print(
f"{datetime.now()} Watchdog: slot {slot.index} timeout, killing PID {slot.process.pid}",
flush=True,
)
self._kill_slot_child(slot)
self._kill_process(slot.process)
if self._closed or self._shutdown_event.is_set():
return
self.result_queue.put(("timeout", slot.index, config))
self._spawn_worker(slot)
def _handle_crash(self, slot):
"""Handle unexpectedly dead worker."""
if self._closed or self._shutdown_event.is_set():
return
exitcode = slot.process.exitcode if slot.process else None
config = slot.current_task
print(
f"{datetime.now()} Watchdog: slot {slot.index} died (exit={exitcode})",
flush=True,
)
if self._closed or self._shutdown_event.is_set():
return
if config is not None:
self.result_queue.put(("crashed", slot.index, config, exitcode))
self._spawn_worker(slot)
def _kill_process_group(self, pid):
try:
os.killpg(pid, signal.SIGKILL)
except (ProcessLookupError, OSError):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, OSError):
pass
def _kill_slot_child(self, slot):
if slot.child_pid is not None:
self._kill_process_group(slot.child_pid)
slot.child_pid = None
def _sigkill_process(self, process):
"""Send SIGKILL to a process without waiting for it to exit."""
try:
if process.is_alive():
os.kill(process.pid, signal.SIGKILL)
except (ProcessLookupError, OSError):
pass
def _join_process(self, process, timeout=5):
"""Wait for a process to exit, ignoring cleanup-time failures."""
try:
process.join(timeout=timeout)
except Exception:
pass
def _kill_process(self, process):
"""SIGKILL a process (CUDA-deadlocked processes don't respond to SIGTERM)."""
self._sigkill_process(process)
self._join_process(process, timeout=5)
def shutdown(self, force=False):
"""Stop all workers and release multiprocessing queues."""
if self._closed:
return
self._closed = True
self._shutdown_event.set()
if self._watchdog_thread and self._watchdog_thread.is_alive():
self._watchdog_thread.join(timeout=3)
try:
if not force:
# Graceful: send poison pills
for slot in self.slots:
if slot.input_queue is not None:
try:
slot.input_queue.put(None)
except (OSError, EOFError, ValueError):
pass
for slot in self.slots:
if slot.process is not None:
slot.process.join(timeout=10)
if slot.process.is_alive():
self._kill_process(slot.process)
else:
# Force: send SIGKILL to all workers first, then join all.
# This avoids serial join latency when many CUDA-deadlocked workers exist.
for slot in self.slots:
self._kill_slot_child(slot)
if slot.process is not None:
self._sigkill_process(slot.process)
for slot in self.slots:
if slot.process is not None:
self._join_process(slot.process, timeout=3)
finally:
for slot in self.slots:
self._close_queue(slot.input_queue, cancel_join=force)
slot.input_queue = None
self._close_queue(self.result_queue, cancel_join=force)
def detect_device_type() -> str:
global DEVICE_TYPE, DEVICE_TYPE_DETECTED, _NVML_INITIALIZED
if DEVICE_TYPE_DETECTED:
return DEVICE_TYPE
# 优先尝试 NVML(NVIDIA GPU)
try:
if not _NVML_INITIALIZED:
pynvml.nvmlInit()
_NVML_INITIALIZED = True
count = pynvml.nvmlDeviceGetCount()
if count > 0:
DEVICE_TYPE = "gpu"
DEVICE_TYPE_DETECTED = True
return DEVICE_TYPE
except Exception:
# 没有 NVML 或不是 NVIDIA,忽略错误,继续往下探测
pass
# 再尝试 XPU
if shutil.which("xpu-smi"):
try:
out = subprocess.check_output(["xpu-smi"], text=True, stderr=subprocess.STDOUT)
if any(re.match(r"^\|\s*\d+\s+\S", line) for line in out.splitlines()):
DEVICE_TYPE = "xpu"
DEVICE_TYPE_DETECTED = True
return DEVICE_TYPE
except Exception:
pass
# 再尝试 Iluvatar
if shutil.which("ixsmi"):
try:
out = subprocess.check_output(["ixsmi"], text=True, stderr=subprocess.STDOUT)
if any(re.match(r"^\|\s*\d+\s+Iluvatar", line) for line in out.splitlines()):
DEVICE_TYPE = "iluvatar_gpu"
DEVICE_TYPE_DETECTED = True
return DEVICE_TYPE
except Exception:
pass
# 都没有就是 CPU
DEVICE_TYPE = "cpu"
DEVICE_TYPE_DETECTED = True
return DEVICE_TYPE
def get_device_count() -> int:
"""Get the number of available devices (accelerators)."""
global DEVICE_COUNT, _NVML_INITIALIZED
if DEVICE_COUNT is not None:
return DEVICE_COUNT
device_type = detect_device_type()
if device_type == "gpu":
if not _NVML_INITIALIZED:
pynvml.nvmlInit()
_NVML_INITIALIZED = True
count = pynvml.nvmlDeviceGetCount()
DEVICE_COUNT = count
return count
if device_type == "xpu":
out = subprocess.check_output(["xpu-smi"], text=True, stderr=subprocess.STDOUT)
ids = set()
for line in out.splitlines():
if "Processes:" in line:
break
m = re.match(r"^\|\s*(\d+)\s+\S", line)
if m:
ids.add(int(m.group(1)))
DEVICE_COUNT = len(ids)
return DEVICE_COUNT
if device_type == "iluvatar_gpu":
out = subprocess.check_output(["ixsmi"], text=True, stderr=subprocess.STDOUT)
ids = set()
for line in out.splitlines():
m = re.match(r"^\|\s*(\d+)\s+Iluvatar", line)
if m:
ids.add(int(m.group(1)))
DEVICE_COUNT = len(ids)
return DEVICE_COUNT
# CPU case/no accelerator
DEVICE_COUNT = 0
return 0
def _refresh_snapshot(device_type):
global _MEM_SNAPSHOT, _MEM_SNAPSHOT_TS
now = time.time()
if now - _MEM_SNAPSHOT_TS < _MEM_SNAPSHOT_TTL and _MEM_SNAPSHOT is not None:
return
snapshot = {}
if device_type == "xpu":
out = subprocess.check_output(["xpu-smi"], text=True, stderr=subprocess.STDOUT)
lines = out.splitlines()
for i, line in enumerate(lines):
m = re.match(r"^\|\s*(\d+)\s+\S", line)
if m:
dev_id = int(m.group(1))
for j in range(i + 1, min(i + 8, len(lines))):
mm = re.search(r"(\d+)\s*MiB\s*/\s*(\d+)\s*MiB", lines[j])
if mm:
used_mib = int(mm.group(1))
total_mib = int(mm.group(2))
snapshot[dev_id] = (total_mib / 1024.0, used_mib / 1024.0)
break
elif device_type == "iluvatar_gpu":
out = subprocess.check_output(["ixsmi"], text=True, stderr=subprocess.STDOUT)
lines = out.splitlines()
for i, line in enumerate(lines):
m = re.match(r"^\|\s*(\d+)\s+Iluvatar", line)
if m:
dev_id = int(m.group(1))
for j in range(i + 1, min(i + 8, len(lines))):
mm = re.search(r"(\d+)\s*MiB\s*/\s*(\d+)\s*MiB", lines[j])
if mm:
used_mib = int(mm.group(1))
total_mib = int(mm.group(2))
snapshot[dev_id] = (total_mib / 1024.0, used_mib / 1024.0)
break
else:
# GPU (NVIDIA) case does not use snapshot (use NVML directly)
_MEM_SNAPSHOT = None
_MEM_SNAPSHOT_TS = now
return
_MEM_SNAPSHOT = snapshot
_MEM_SNAPSHOT_TS = now
def get_memory_info(gpu_id):
"""Return (total_memory, used_memory) in GB for accelerator device."""
global _NVML_INITIALIZED
device_type = detect_device_type()
if device_type == "gpu":
if not _NVML_INITIALIZED:
pynvml.nvmlInit()
_NVML_INITIALIZED = True
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
return int(mem_info.total) / (1024**3), int(mem_info.used) / (1024**3)
if device_type in ("xpu", "iluvatar_gpu"):
_refresh_snapshot(device_type)
if _MEM_SNAPSHOT is None or gpu_id not in _MEM_SNAPSHOT:
raise RuntimeError(f"Failed to get memory info for {device_type} device {gpu_id}")
return _MEM_SNAPSHOT[gpu_id]
raise RuntimeError("No supported accelerator (GPU / XPU / Iluvatar) detected.")
def validate_gpu_options(options) -> tuple:
"""Validate and normalize GPU-related options."""
device_count = get_device_count()
if device_count == 0:
raise ValueError("No devices found")
if options.gpu_ids:
try:
gpu_ids = []
for part in options.gpu_ids.split(","):
part = part.strip()
if not part:
continue
if part.startswith("-") and part[1:].isdigit():
gpu_ids.append(int(part))
elif "-" in part and not part.startswith("-"):
start, end = map(int, part.split("-"))
if start > end:
raise ValueError(f"Invalid range: {part} (start > end)")
gpu_ids.extend(range(start, end + 1))
else:
gpu_ids.append(int(part))
except ValueError:
raise ValueError(
f"Invalid gpu_ids: {options.gpu_ids} (int or range expected)"
) from None
if len(gpu_ids) != len(set(gpu_ids)):
raise ValueError(f"Invalid gpu_ids: {options.gpu_ids} (duplicates)")
gpu_ids = sorted(set(gpu_ids))
if len(gpu_ids) > 1 and -1 in gpu_ids:
raise ValueError(f"Invalid gpu_ids: {options.gpu_ids} (-1 allowed only)")
if gpu_ids != [-1] and not all(0 <= id < device_count for id in gpu_ids):
raise ValueError(
f"Invalid gpu_ids: {options.gpu_ids} (valid range [0, {device_count}))"
)
else:
gpu_ids = [-1]
if options.num_gpus < -1 or options.num_gpus == 0 or options.num_gpus > device_count:
raise ValueError(f"Invalid num_gpus: {options.num_gpus}")
if options.num_gpus == -1:
options.num_gpus = device_count if gpu_ids == [-1] else len(gpu_ids)
if gpu_ids == [-1]:
gpu_ids = list(range(options.num_gpus))
elif len(gpu_ids) != options.num_gpus:
raise ValueError(f"num_gpus {options.num_gpus} mismatches gpu_ids {gpu_ids}")
if options.num_workers_per_gpu < -1 or options.num_workers_per_gpu == 0:
raise ValueError(f"Invalid num_workers_per_gpu: {options.num_workers_per_gpu}")
if options.required_memory <= 0:
raise ValueError(f"Invalid required_memory: {options.required_memory}")
return tuple(gpu_ids)
def parse_bool(value):
if isinstance(value, str):
value = value.lower()
if value in ["true", "1", "yes", "y"]:
return True
elif value in ["false", "0", "no", "n"]:
return False
else:
raise ValueError(f"Invalid boolean value: {value} parsed from command line")
def check_gpu_memory(gpu_ids, num_workers_per_gpu, required_memory): # required_memory in GB
assert isinstance(gpu_ids, tuple) and len(gpu_ids) > 0
available_gpus = []
max_workers_per_gpu = {}
for gpu_id in gpu_ids:
try:
total_memory, used_memory = get_memory_info(gpu_id)
free_memory = total_memory - used_memory
max_workers = int(free_memory // required_memory)
if max_workers >= 1:
available_gpus.append(gpu_id)
max_workers_per_gpu[gpu_id] = (
max_workers
if num_workers_per_gpu == -1
else min(max_workers, num_workers_per_gpu)
)
except pynvml.NVMLError as e:
print(f"[WARNING] Failed to check GPU {gpu_id}: {e!s}", flush=True)
continue
return available_gpus, max_workers_per_gpu
def run_test_case(api_config_str, options):
"""Run a single test case for the given API configuration."""
cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
gpu_id = int(cuda_visible.split(",")[0])
write_to_log("checkpoint", api_config_str)
print(
f"{datetime.now()} GPU {gpu_id} {os.getpid()} [paddle {options.paddle_version}] test begin: {api_config_str}",
flush=True,
)
max_memory_wait = 30 # max 30 iterations × 10s = 5 minutes
for wait_iter in range(max_memory_wait):
total_memory, used_memory = get_memory_info(gpu_id)
free_memory = total_memory - used_memory
if free_memory >= options.required_memory:
break
if wait_iter % 6 == 0: # log every ~60s (every 6th iteration)
print(
f"{datetime.now()} device {gpu_id} Free: {free_memory:.1f} GB, "
f"Required: {options.required_memory:.1f} GB. "
f"Waiting for available memory... (attempt {wait_iter + 1}/{max_memory_wait})",
flush=True,
)
time.sleep(10)
else:
print(
f"{datetime.now()} device {gpu_id} Memory wait timeout after {max_memory_wait * 10}s. "
f"Proceeding anyway (free={free_memory:.1f} GB, required={options.required_memory:.1f} GB).",
flush=True,
)
try:
api_config = APIConfig(api_config_str)
except Exception as err:
print(f"[config parse error] {api_config_str} {err!s}", flush=True)
return
option_to_class = {
"paddle_only": APITestPaddleOnly,
"paddle_cinn": APITestCINNVSDygraph,
"accuracy": APITestAccuracy,
"paddle_gpu_performance": APITestPaddleGPUPerformance,
"torch_gpu_performance": APITestTorchGPUPerformance,
"paddle_torch_gpu_performance": APITestPaddleTorchGPUPerformance,
"accuracy_stable": APITestAccuracyStable,
"paddle_custom_device": APITestCustomDeviceVSCPU,
"custom_device_vs_gpu": APITestPaddleDeviceVSGPU,
}
test_class = next(
(cls for opt, cls in option_to_class.items() if getattr(options, opt, False)),
APITestAccuracy, # default fallback
)
kwargs = {k: v for k, v in vars(options).items() if k in VALID_TEST_ARGS}
case = test_class(api_config, **kwargs)
try:
case.test()
except Exception as err:
# if fatal error happens, subprocess need to exit with non-zero status
if "CUDA error" in str(err) or "memory corruption" in str(err):
os._exit(99)
if "CUDA out of memory" in str(err) or "Out of memory error" in str(err):
os._exit(98)
if "AssertionError" in str(err) or "Tensor-likes are not equal" in str(err):
os._exit(1)
# if not fatal error, subprocess will be alive and report error
print(f"[test error] {api_config_str}: {err}", flush=True)
raise
finally:
del test_class, api_config, case
gc.collect()
if not any(
getattr(options, opt)
for opt in (
"paddle_gpu_performance",
"torch_gpu_performance",
"paddle_torch_gpu_performance",
)
):
torch.cuda.empty_cache()
paddle.device.cuda.empty_cache()