Repository navigation
Expand file tree
/
Copy pathengineV2.py
More file actions
1554 lines (1413 loc) · 54 KB
/
Copy pathengineV2.py
File metadata and controls
1554 lines (1413 loc) · 54 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 atexit
import errno
import gc
import os
import re
import shutil
import signal
import subprocess
import sys
import time
from concurrent.futures import TimeoutError, as_completed
from datetime import datetime
from multiprocessing import Lock, Manager, cpu_count, set_start_method
from pathlib import Path
from typing import TYPE_CHECKING
import numpy as np
import pynvml
import yaml
from pebble import ProcessExpired, ProcessPool
if TYPE_CHECKING:
import paddle
import torch
from tester import (
APIConfig,
APITestAccuracy,
APITestAccuracyStable,
APITestCINNVSDygraph,
APITestCustomDeviceVSCPU,
APITestPaddleDeviceVSGPU,
APITestPaddleGPUPerformance,
APITestPaddleOnly,
APITestPaddleTorchGPUPerformance,
APITestTorchGPUPerformance,
)
from tester.reporting import (
init_log,
log_aggregation,
log_report,
log_retest,
log_runtime,
log_worker,
)
from tester.reporting.dump_writer import (
dump_enabled,
parse_strict_bool,
record_dump_terminal_status,
resolve_dump_options,
)
from tester.runtime.config_file_loader import resolve_config_files
from tester.runtime.runtime_config import (
TestRuntimeConfig,
limit_worker_layout,
runtime_config_for_gpu,
)
os.environ["FLAGS_use_system_allocator"] = "1"
os.environ["NVIDIA_TF32_OVERRIDE"] = "0"
VALID_TEST_ARGS = {
"test_amp",
"test_backward",
"atol",
"rtol",
"accuracy_manual_threshold_config",
"record_accuracy_tolerance",
"operation_mode",
"bos_path",
"random_seed",
"bos_conf_path",
"bcecmd_path",
"bitwise_alignment",
"use_gpu_mode",
"accuracy_dual_gpu",
"runtime_config",
}
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
_MEM_SNAPSHOT_TTL = 2.0 # seconds — snapshot cache ttl
def cleanup(pool):
print(f"\n{datetime.now()} Cleanup started", flush=True)
if pool is not None:
try:
if pool.active:
pool.stop()
pool.join(timeout=5)
except Exception as e:
print(f"{datetime.now()} Error shutting down executor: {e}", flush=True)
print(f"{datetime.now()} Cleanup completed", flush=True)
def estimate_timeout(api_config) -> float:
"""Estimate timeout based on tensor size in APIConfig."""
# TIMEOUT_STEPS = (
# (1e4, 10),
# (1e5, 30),
# (1e6, 90),
# (1e7, 300),
# (1e8, 1800),
# (float("inf"), 3600),
# )
# try:
# api_config = APIConfig(api_config)
# first = None
# if api_config.args:
# first = api_config.args[0]
# elif api_config.kwargs:
# first = next(iter(api_config.kwargs.values()))
# if first is not None and hasattr(first, "shape"):
# total_elements = math.prod(first.shape)
# for threshold, timeout in TIMEOUT_STEPS:
# if total_elements <= threshold:
# return timeout
# except Exception:
# pass
# return TIMEOUT_STEPS[-1][1]
return 1800
def detect_device_type() -> str:
global DEVICE_TYPE, DEVICE_TYPE_DETECTED
if DEVICE_TYPE_DETECTED:
return DEVICE_TYPE
# 优先尝试 NVML(NVIDIA GPU)
try:
pynvml.nvmlInit()
count = pynvml.nvmlDeviceGetCount()
pynvml.nvmlShutdown()
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
if DEVICE_COUNT is not None:
return DEVICE_COUNT
device_type = detect_device_type()
if device_type == "gpu":
pynvml.nvmlInit()
try:
count = pynvml.nvmlDeviceGetCount()
finally:
pynvml.nvmlShutdown()
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."""
device_type = detect_device_type()
if device_type == "gpu":
pynvml.nvmlInit()
try:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
return int(mem_info.total) / (1024**3), int(mem_info.used) / (1024**3)
finally:
pynvml.nvmlShutdown()
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.")
ARGUMENT_ERROR_PREFIX = "[argument error]"
ARGUMENT_WARNING_PREFIX = "[argument warning]"
TEST_MODE_ERROR = (
"specify exactly one test mode: --accuracy, --paddle_only, --paddle_cinn, "
"--paddle_gpu_performance, --torch_gpu_performance, "
"--paddle_torch_gpu_performance, --accuracy_stable, "
"--accuracy_dual_gpu, --accuracy_stable_dual_gpu, "
"--paddle_custom_device, --custom_device_vs_gpu"
)
def _print_argument(prefix, message):
print(f"{prefix} {message}", flush=True)
def _mode_uses_torch(options):
return any(
getattr(options, opt, False)
for opt in (
"accuracy",
"accuracy_dual_gpu",
"paddle_cinn",
"paddle_gpu_performance",
"torch_gpu_performance",
"paddle_torch_gpu_performance",
"accuracy_stable",
"accuracy_stable_dual_gpu",
"paddle_custom_device",
"custom_device_vs_gpu",
)
)
def _load_test_classes(options):
import tester
class_name = _selected_test_class_name(options)
return {
"APIConfig": tester.APIConfig,
class_name: getattr(tester, class_name),
}
def _selected_test_class_name(options):
option_to_class_name = {
"paddle_only": "APITestPaddleOnly",
"paddle_cinn": "APITestCINNVSDygraph",
"accuracy": "APITestAccuracy",
"accuracy_dual_gpu": "APITestAccuracy",
"paddle_gpu_performance": "APITestPaddleGPUPerformance",
"torch_gpu_performance": "APITestTorchGPUPerformance",
"paddle_torch_gpu_performance": "APITestPaddleTorchGPUPerformance",
"accuracy_stable_dual_gpu": "APITestAccuracyStable",
"accuracy_stable": "APITestAccuracyStable",
"paddle_custom_device": "APITestCustomDeviceVSCPU",
"custom_device_vs_gpu": "APITestPaddleDeviceVSGPU",
}
for option, class_name in option_to_class_name.items():
if getattr(options, option, False):
return class_name
return "APITestAccuracy"
def _select_test_class(options):
test_classes = _load_test_classes(options)
return test_classes[_selected_test_class_name(options)]
def _clear_device_cache(options):
import paddle
if _mode_uses_torch(options):
import torch
torch.cuda.empty_cache()
paddle.device.cuda.empty_cache()
def _parse_gpu_ids(gpu_ids_arg, device_count):
gpu_ids = []
for raw_part in gpu_ids_arg.split(","):
part = raw_part.strip()
if not part:
continue
if part == "-1":
gpu_ids.append(-1)
continue
if "-" in part:
try:
start, end = map(int, part.split("-", 1))
except ValueError:
raise ValueError(
f"invalid --gpu_ids='{gpu_ids_arg}': expected integers or ranges like '0,2,4-7'"
) from None
if start > end:
raise ValueError(f"invalid --gpu_ids='{gpu_ids_arg}': range start must be <= end")
gpu_ids.extend(range(start, end + 1))
continue
try:
gpu_ids.append(int(part))
except ValueError:
raise ValueError(
f"invalid --gpu_ids='{gpu_ids_arg}': expected integers or ranges like '0,2,4-7'"
) from None
if not gpu_ids:
raise ValueError(f"invalid --gpu_ids='{gpu_ids_arg}': expected at least one GPU id")
seen_gpu_ids = set()
for gpu_id in gpu_ids:
if gpu_id in seen_gpu_ids:
raise ValueError(f"invalid --gpu_ids='{gpu_ids_arg}': duplicate GPU id {gpu_id}")
seen_gpu_ids.add(gpu_id)
if len(gpu_ids) > 1 and -1 in gpu_ids:
raise ValueError(
f"invalid --gpu_ids='{gpu_ids_arg}': -1 cannot be combined with explicit GPU IDs"
)
if gpu_ids != [-1] and not all(0 <= gpu_id < device_count for gpu_id in gpu_ids):
raise ValueError(
f"invalid --gpu_ids='{gpu_ids_arg}': valid GPU id range is [0, {device_count})"
)
return tuple(sorted(gpu_ids))
def validate_gpu_options(options) -> tuple:
"""Validate and normalize GPU-related options."""
normalize_dual_gpu_options(options)
device_count = get_device_count()
if device_count == 0:
raise ValueError("no accelerator devices were found")
gpu_ids = _parse_gpu_ids(options.gpu_ids, device_count) if options.gpu_ids else (-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}: expected -1 or a value in [1, {device_count}]"
)
if options.num_gpus == -1:
options.num_gpus = device_count if gpu_ids == (-1,) else len(gpu_ids)
if gpu_ids == (-1,):
gpu_ids = tuple(range(options.num_gpus))
elif len(gpu_ids) != options.num_gpus:
raise ValueError(
f"invalid --num_gpus={options.num_gpus}: expected {len(gpu_ids)} "
f"to match --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}: "
"expected -1 or a positive integer"
)
if _dual_gpu_mode_enabled(options):
if options.num_gpus < 2 or options.num_gpus % 2:
raise ValueError("dual-GPU accuracy mode requires an even --num_gpus")
if options.num_workers_per_gpu != 1:
raise ValueError("dual-GPU accuracy mode requires --num_workers_per_gpu=1")
return tuple(gpu_ids)
def _dual_gpu_mode_enabled(options):
"""双卡判断负责资源拓扑,accuracy tester 继续负责结果比较。"""
return bool(
getattr(options, "accuracy_dual_gpu", False)
or getattr(options, "accuracy_stable_dual_gpu", False)
)
def normalize_dual_gpu_options(options):
"""双卡组合开关先展开成主模式,再进入统一互斥校验。"""
for option_name, base_mode in (
("accuracy_dual_gpu", "accuracy"),
("accuracy_stable_dual_gpu", "accuracy_stable"),
):
if not getattr(options, option_name, False):
continue
if not getattr(options, "use_gpu_mode", False):
_print_argument(
ARGUMENT_WARNING_PREFIX,
f"--{option_name}=True implies --use_gpu_mode=True; enabling GPU mode",
)
options.use_gpu_mode = True
setattr(options, base_mode, True)
def _mode_runs_torch_gpu_reference(options):
"""判断 V2 是否会真实执行 Torch GPU reference。"""
# V2 与 V4 使用相同的 reference GPU 调度边界。
return any(
getattr(options, mode, False)
for mode in (
"accuracy",
"accuracy_dual_gpu",
"accuracy_stable",
"accuracy_stable_dual_gpu",
"torch_gpu_performance",
"paddle_torch_gpu_performance",
)
)
def _requires_gpu_runtime(options):
"""GPU 算子或 GPU 生成/比较任一启用时,都必须准备 GPU 运行时。"""
return bool(
not getattr(options, "test_cpu", False)
or getattr(options, "use_gpu_mode", False)
or _mode_runs_torch_gpu_reference(options)
)
def _resolve_dump_options(parser, options):
try:
options.use_dump, options.dump_dir = resolve_dump_options(
options.use_dump, options.dump_dir
)
except ValueError as err:
parser.error(str(err))
os.environ["USE_DUMP"] = str(options.use_dump)
os.environ["DUMP_DIR"] = options.dump_dir
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 _apply_single_config_gpu_defaults(options):
if not options.gpu_ids and options.num_gpus == -1:
if _dual_gpu_mode_enabled(options):
options.gpu_ids = "0,1"
options.num_gpus = 2
else:
options.gpu_ids = "0"
options.num_gpus = 1
def _prepare_single_config_gpu(options):
normalize_dual_gpu_options(options)
if not _requires_gpu_runtime(options):
options.gpu_workers_per_gpu_map = {}
options.gpu_total_memory_map = {}
options.runtime_config = TestRuntimeConfig.from_options(options)
return None
_apply_single_config_gpu_defaults(options)
gpu_ids = validate_gpu_options(options)
expected_gpu_count = 2 if _dual_gpu_mode_enabled(options) else 1
if len(gpu_ids) != expected_gpu_count:
raise ValueError(
f"single --api_config run requires exactly {expected_gpu_count} GPU(s); "
f"got {len(gpu_ids)} GPUs: {gpu_ids}"
)
os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(str(gpu_id) for gpu_id in gpu_ids)
options.gpu_total_memory_map = {}
for gpu_id in gpu_ids:
try:
options.gpu_total_memory_map[gpu_id] = get_memory_info(gpu_id)[0]
except Exception:
pass
options.gpu_workers_per_gpu_map = dict.fromkeys(gpu_ids, 1)
options.runtime_config = TestRuntimeConfig.from_options(options)
comparison_gpu_id = gpu_ids[1] if len(gpu_ids) == 2 else None
options.runtime_config = runtime_config_for_gpu(
options,
gpu_ids[0],
comparison_gpu_id=comparison_gpu_id,
)
return gpu_ids if comparison_gpu_id is not None else gpu_ids[0]
def check_gpu_memory(gpu_ids, num_workers_per_gpu):
assert isinstance(gpu_ids, tuple) and len(gpu_ids) > 0
available_gpus = []
max_workers_per_gpu = {}
for gpu_id in gpu_ids:
try:
get_memory_info(gpu_id)
except pynvml.NVMLError as e:
print(f"[warn] Failed to check GPU {gpu_id}: {e!s}", flush=True)
continue
available_gpus.append(gpu_id)
max_workers_per_gpu[gpu_id] = 1 if num_workers_per_gpu == -1 else num_workers_per_gpu
return available_gpus, max_workers_per_gpu
def limit_dual_gpu_worker_layout(available_gpus, pending_cases):
"""Limit an ordered list of complete GPU pairs to the pending case count."""
if len(available_gpus) % 2:
raise ValueError("dual-GPU worker layout requires complete GPU pairs")
pair_count = min(len(available_gpus) // 2, max(0, pending_cases))
selected_gpus = list(available_gpus[: pair_count * 2])
return selected_gpus, dict.fromkeys(selected_gpus, 1)
def _visible_gpu_ids(gpu_id, comparison_gpu_id=None):
if comparison_gpu_id is None:
return str(gpu_id)
return f"{gpu_id},{comparison_gpu_id}"
def _assign_worker_gpus(
gpu_worker_list,
available_gpus,
max_workers_per_gpu,
options,
my_pid,
pid_exists,
):
assigned_gpu = -1
assigned_comparison_gpu = None
max_available_slots = -1
dual_gpu = _dual_gpu_mode_enabled(options)
if dual_gpu:
for pair_index in range(0, len(available_gpus), 2):
compute_gpu = available_gpus[pair_index]
comparison_gpu = available_gpus[pair_index + 1]
compute_workers = gpu_worker_list[compute_gpu]
comparison_workers = gpu_worker_list[comparison_gpu]
compute_workers[:] = [pid for pid in compute_workers if pid_exists(pid)]
comparison_workers[:] = [pid for pid in comparison_workers if pid_exists(pid)]
available_slots = 1 - max(
len(compute_workers),
len(comparison_workers),
)
if available_slots > max_available_slots:
max_available_slots = available_slots
assigned_gpu = compute_gpu
assigned_comparison_gpu = comparison_gpu
else:
for gpu_id in available_gpus:
workers = gpu_worker_list[gpu_id]
workers[:] = [pid for pid in workers if pid_exists(pid)]
available_slots = max_workers_per_gpu[gpu_id] - len(workers)
if available_slots > max_available_slots:
max_available_slots = available_slots
assigned_gpu = gpu_id
if assigned_gpu == -1 or (dual_gpu and max_available_slots <= 0):
raise RuntimeError(f"Worker {my_pid} could not be assigned a GPU.")
gpu_worker_list[assigned_gpu].append(my_pid)
if assigned_comparison_gpu is not None:
gpu_worker_list[assigned_comparison_gpu].append(my_pid)
return assigned_gpu, assigned_comparison_gpu
def init_worker_gpu(gpu_worker_list, lock, available_gpus, max_workers_per_gpu, options):
init_log(options.log_dir)
my_pid = os.getpid()
def pid_exists(pid):
try:
os.kill(pid, 0)
return True
except OSError as e:
return e.errno == errno.EPERM
try:
assigned_gpu = assigned_comparison_gpu = None
if _requires_gpu_runtime(options):
with lock:
assigned_gpu, assigned_comparison_gpu = _assign_worker_gpus(
gpu_worker_list,
available_gpus,
max_workers_per_gpu,
options,
my_pid,
pid_exists,
)
os.environ["CUDA_VISIBLE_DEVICES"] = _visible_gpu_ids(
assigned_gpu,
assigned_comparison_gpu,
)
with log_worker.suppress_startup_output():
import paddle
globals()["paddle"] = paddle
if options.test_cpu:
paddle.device.set_device("cpu")
elif not getattr(options, "paddle_custom_device", False):
# CUDA_VISIBLE_DEVICES assigns the worker slot; Paddle still needs an explicit device.
paddle.set_device("gpu")
try:
import paddlefleet_ops
except ImportError:
pass
try:
import FusedQuantOps
except ImportError:
pass
globals().update(_load_test_classes(options))
def signal_handler(*args):
if _requires_gpu_runtime(options):
_clear_device_cache(options)
log_worker.restore_stdio()
log_runtime.close_process_files()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
log_worker.redirect_stdio()
except Exception as e:
print(f"[worker] INIT_FAILED | PID {my_pid} | {e}", flush=True)
raise
def run_test_case(api_config_str, options):
"""Run a single test case for the given API configuration."""
completion = [os.getpid(), None]
started_at = time.monotonic()
# 纯 CPU 模式不构造虚拟 GPU id,显存状态和日志均保持 CPU 语义。
visible_gpu_ids = ()
if _requires_gpu_runtime(options):
visible_gpu_ids = tuple(
int(value) for value in os.environ.get("CUDA_VISIBLE_DEVICES", "0").split(",")
)
gpu_id = visible_gpu_ids[0] if visible_gpu_ids else None
comparison_gpu_id = (
visible_gpu_ids[1] if _dual_gpu_mode_enabled(options) and len(visible_gpu_ids) > 1 else None
)
log_worker.write_case_begin(
api_config_str,
worker_pid=os.getpid(),
gpu=gpu_id,
paddle_version=options.paddle_version,
)
runtime_config = runtime_config_for_gpu(
options,
gpu_id,
comparison_gpu_id=comparison_gpu_id,
)
case_status = "done"
try:
if options.show_runtime_status and gpu_id is not None:
total_memory, used_memory_before = get_memory_info(gpu_id)
print(
f"{datetime.now()} GPU {gpu_id} memory before: used={used_memory_before:.1f} GB, "
f"free={total_memory - used_memory_before:.1f} GB",
flush=True,
)
api_config = None
case = None
try:
api_config = APIConfig(api_config_str)
except Exception as err:
log_worker.emit_case_result("config_parse", api_config_str, message=str(err))
case_status = "error"
return completion
test_class = _select_test_class(options)
kwargs = {k: v for k, v in vars(options).items() if k in VALID_TEST_ARGS}
kwargs["runtime_config"] = runtime_config
case = test_class(api_config, **kwargs)
try:
if dump_enabled():
case.run_with_dump()
else:
case.test()
except Exception as err:
err_msg = str(err).lower()
terminal_log_type = log_worker.get_terminal_log_type(api_config_str)
oom_markers = (
"cuda out of memory",
"out of memory error",
"resourceexhaustederror",
"out of memory",
"outofmemoryerror",
"cannot allocate memory",
"std::bad_alloc",
"bad allocation",
"memoryerror",
"cublas_status_alloc_failed",
)
cuda_markers = (
"cuda error",
"memory corruption",
"illegal memory access",
"invalid configuration argument",
"invalid resource handle",
)
fatal_log_type = None
if any(marker in err_msg for marker in oom_markers):
fatal_log_type = "oom"
elif terminal_log_type == "torch_error" and any(
marker in err_msg for marker in cuda_markers
):
fatal_log_type = "torch_error"
elif any(marker in err_msg for marker in cuda_markers):
fatal_log_type = "paddle_cuda"
if fatal_log_type is not None:
exit_code = log_worker.fatal_exit_code(
fatal_log_type, terminal_log_type == fatal_log_type
)
if dump_enabled():
record_dump_terminal_status("engine_fatal", exit_code=exit_code, error=str(err))
try:
log_runtime.close_process_files()
finally:
try:
log_worker.restore_stdio()
finally:
os._exit(exit_code)
if terminal_log_type is not None:
return completion
# if not fatal error, subprocess will be alive and report error
print(f"[error] {api_config_str}: {err}", flush=True)
raise
finally:
del test_class, api_config, case
if not getattr(options, "use_gpu_mode", False):
gc.collect()
if (
_requires_gpu_runtime(options)
and not any(
getattr(options, opt)
for opt in (
"paddle_gpu_performance",
"torch_gpu_performance",
"paddle_torch_gpu_performance",
)
)
and not getattr(options, "use_gpu_mode", False)
):
_clear_device_cache(options)
if options.show_runtime_status and gpu_id is not None:
try:
total_memory, used_memory_after = get_memory_info(gpu_id)
print(
f"{datetime.now()} GPU {gpu_id} memory after cleanup: used={used_memory_after:.1f} GB, "
f"free={total_memory - used_memory_after:.1f} GB",
flush=True,
)
except Exception as err:
print(
f"{datetime.now()} Failed to read GPU {gpu_id} memory after cleanup: {err}",
flush=True,
)
return completion
except BaseException:
case_status = "error"
raise
finally:
completion[1] = log_worker.write_case_end(
case_status,
api_config_str=api_config_str,
duration_ms=round((time.monotonic() - started_at) * 1000),
)
def main():
start_time = time.time()
set_start_method("spawn")
try:
import paddle as _paddle
paddle_version = _paddle.__version__
del _paddle
except Exception:
paddle_version = "unknown"
parser = argparse.ArgumentParser(description="Run Paddle API test cases", allow_abbrev=False)
parser.add_argument(
"--api_config_file",
nargs="+",
default=None,
help=(
"One or more config files, directories, or glob patterns. Mutually exclusive "
"with --api_config and --retest."
),
)
parser.add_argument(
"--api_config",
default="",
help=(
"Run one API config string directly. Single-case mode uses one GPU, or one "
"GPU pair with --accuracy_dual_gpu=True or --accuracy_stable_dual_gpu=True."
),
)
parser.add_argument(
"--retest",
default="",
help=(
"Retest classifications from --log_dir, e.g. config_input or "
"config_input,timeout. Mutually exclusive with other config inputs."
),
)
parser.add_argument(
"--paddle_only",
type=parse_bool,
default=False,
help="Run Paddle-only API support checks.",
)
parser.add_argument(
"--paddle_cinn",
type=parse_bool,
default=False,
help="Run Paddle dynamic graph vs CINN checks.",
)
parser.add_argument(
"--accuracy",
type=parse_bool,
default=False,
help="Run Paddle vs corresponding Torch accuracy checks.",
)
parser.add_argument(
"--paddle_gpu_performance",
type=parse_bool,
default=False,
help="Run Paddle GPU performance checks.",
)
parser.add_argument(
"--torch_gpu_performance",
type=parse_bool,
default=False,
help="Run Torch GPU performance checks.",
)
parser.add_argument(
"--paddle_torch_gpu_performance",
type=parse_bool,
default=False,
help="Run Paddle and Torch GPU performance checks.",
)
parser.add_argument(
"--accuracy_stable",
type=parse_bool,
default=False,
help="Run stable Paddle vs corresponding Torch accuracy checks.",
)
parser.add_argument(
"--accuracy_dual_gpu",
type=parse_bool,
default=False,
help="Use one compute GPU and one full-result comparison GPU per accuracy worker.",
)
parser.add_argument(
"--accuracy_stable_dual_gpu",
type=parse_bool,
default=False,
help=("Use one compute GPU and one full-result comparison GPU per accuracy-stable worker."),
)
parser.add_argument(
"--paddle_custom_device",
type=parse_bool,
default=False,
help="Run Paddle custom device vs CPU checks.",
)
parser.add_argument(
"--test_amp",
type=parse_bool,
default=False,
help="Enable auto mixed precision (AMP) checks.",
)
parser.add_argument(
"--num_gpus",
type=int,
default=-1,
help="Number of GPUs to use. Use -1 for all selected GPUs.",
)
parser.add_argument(
"--num_workers_per_gpu",
type=int,
default=1,
help="Workers per GPU. In gpu_mode, -1 uses one worker per GPU.",
)
parser.add_argument(
"--gpu_ids",
type=str,
default="",
help="GPU IDs to use, e.g. '0', '0,2', '0-3'. Use '-1' for all GPUs.",
)
parser.add_argument(
"--test_cpu",
type=parse_bool,
default=False,
help="Run only Paddle forward/backward on CPU; Torch reference remains on GPU.",
)
parser.add_argument(
"--use_cached_numpy",
type=parse_bool,
default=False,
help="Reuse cached NumPy inputs when available.",
)
parser.add_argument(
"--use_gpu_mode",
type=parse_bool,
default=False,
help=(
"Enable GPU tensor generation, comparison, and allocator reuse; "
"does not change the Paddle kernel or Torch reference devices."
),
)
parser.add_argument(
"--log_dir",
type=str,
default="",
help="Directory for test logs; default is logs/test_log_<timestamp>.",
)
parser.add_argument(