forked from PFCCLab/PaddleAPITest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.py
More file actions
2576 lines (2347 loc) · 106 KB
/
Copy pathbase.py
File metadata and controls
2576 lines (2347 loc) · 106 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 collections
import contextlib
import gc
import inspect
import math
import os
import re
from dataclasses import dataclass
import numpy
import paddle
import yaml
from .api_config.config_analyzer import (
USE_CACHED_NUMPY,
TensorConfig,
get_cached_numpy_array,
)
from .api_config.dump_writer import DEFAULT_DUMP_DIR, DumpContext, dump_enabled
from .log_writer.log_comparison import log_accuracy_tolerance
from .log_writer.log_schema import MAX_CSV_CONFIG_LENGTH
from .log_writer.log_worker import write_to_log
from .runtime_config import TestRuntimeConfig
with open("tester/base_config.yaml", encoding="utf-8") as f:
config = yaml.safe_load(f)
forward_only_apis = frozenset(config.get("forward_only_apis", []))
handle_axes_api = frozenset(config.get("handle_axes_api", []))
not_check_dtype = frozenset(config.get("not_check_dtype", []))
rand_apis = frozenset(config.get("rand_apis", []))
stochastic_behavior_apis = frozenset(config.get("stochastic_behavior_apis", []))
single_op_no_signature_apis = frozenset(config.get("single_op_no_signature_apis", []))
paddle_error_dismiss = {} # disabled: covered by the unified runtime error reporter
# paddle_error_dismiss = config.get("paddle_error_dismiss", {})
special_accuracy_atol_rtol = config.get("special_accuracy_atol_rtol", {})
with open("tester/api_config/torch_error_skip.txt") as f:
torch_error_skip = frozenset(line.strip() for line in f if line.strip())
del config
class _LazyTorch:
def __getattr__(self, name):
import torch
globals()["torch"] = torch
return getattr(torch, name)
torch = _LazyTorch()
_GPU_DEVICE_PATTERN = re.compile(r"^(cuda|gpu):(\d+)$", re.IGNORECASE)
CUDA_ERROR = frozenset(
[
"CUDA error",
"memory corruption",
]
)
CUDA_OOM = frozenset(
[
"CUDA out of memory",
"Out of memory error",
"ResourceExhaustedError",
"out of memory",
"OutOfMemoryError",
]
)
GPU_MEMORY_PROBE_MIN_BYTES = 256 << 20
_GIB = 1024**3
_TENSOR_DTYPE_BYTES = {
"bool": 1,
"uint8": 1,
"int8": 1,
"float8_e4m3fn": 1,
"float8_e5m2": 1,
"uint16": 2,
"int16": 2,
"float16": 2,
"bfloat16": 2,
"uint32": 4,
"int32": 4,
"float32": 4,
"uint64": 8,
"int64": 8,
"float64": 8,
"complex64": 8,
"complex128": 16,
}
def _dtype_element_size(dtype):
dtype_name = str(dtype).split(".")[-1]
return _TENSOR_DTYPE_BYTES.get(dtype_name, 4)
def _tensor_element_size(value):
try:
return int(value.element_size())
except (AttributeError, TypeError, ValueError):
return _dtype_element_size(value.dtype)
@dataclass(frozen=True)
class GpuMemoryDecision:
cleanup_performed: bool = False
should_spill: bool = False
free_before_bytes: int | None = None
free_after_bytes: int | None = None
required_headroom_bytes: int = 0
pressure_before: bool = False
pressure_after: bool = False
def _gpu_memory_is_under_pressure(gpu_config, free_bytes, total_bytes, required_headroom_bytes):
workers_on_gpu = max(1, int(gpu_config.workers_on_gpu or 1))
memory_budget_bytes = max(0, int(float(gpu_config.memory_budget or 0.0) * _GIB))
device_budget_bytes = (
memory_budget_bytes * workers_on_gpu if memory_budget_bytes > 0 else total_bytes
)
device_used_bytes = max(0, total_bytes - free_bytes)
over_budget = bool(
device_budget_bytes > 0
and device_used_bytes >= int(device_budget_bytes * float(gpu_config.cleanup_used_ratio))
)
low_free = bool(
device_budget_bytes > 0
and free_bytes <= int(device_budget_bytes * float(gpu_config.cleanup_pressure_ratio))
)
insufficient_headroom = bool(
required_headroom_bytes > 0 and free_bytes < required_headroom_bytes
)
return over_budget or low_free or insufficient_headroom
def _release_gpu_allocator_caches(torch_module):
gc.collect()
try:
torch_module.cuda.empty_cache()
except Exception:
pass
try:
paddle.device.cuda.empty_cache()
except Exception:
pass
def _query_gpu_memory(torch_module):
try:
free_bytes, total_bytes = torch_module.cuda.mem_get_info()
return int(free_bytes), int(total_bytes)
except Exception:
return None
def gpu_mode_memory_decision(
gpu_config,
force=False,
request_spill=False,
probe_bytes=None,
retained_tree_bytes=0,
required_headroom_bytes=None,
):
"""Release idle allocator blocks and decide whether live result trees must spill."""
if not gpu_config.enabled:
return GpuMemoryDecision()
probe_bytes = max(0, int(probe_bytes or 0))
retained_tree_bytes = max(0, int(retained_tree_bytes or 0))
if required_headroom_bytes is None:
required_headroom_bytes = probe_bytes
required_headroom_bytes = max(0, int(required_headroom_bytes or 0))
decision_probe_bytes = max(probe_bytes, retained_tree_bytes, required_headroom_bytes)
if not force and decision_probe_bytes < GPU_MEMORY_PROBE_MIN_BYTES:
return GpuMemoryDecision(required_headroom_bytes=required_headroom_bytes)
try:
import torch as torch_module
except (ImportError, OSError):
if force:
gc.collect()
try:
paddle.device.cuda.empty_cache()
except Exception:
pass
return GpuMemoryDecision(
cleanup_performed=True,
required_headroom_bytes=required_headroom_bytes,
)
return GpuMemoryDecision(required_headroom_bytes=required_headroom_bytes)
if force:
_release_gpu_allocator_caches(torch_module)
return GpuMemoryDecision(
cleanup_performed=True,
required_headroom_bytes=required_headroom_bytes,
)
before = _query_gpu_memory(torch_module)
pressure_before = before is None or _gpu_memory_is_under_pressure(
gpu_config, *before, required_headroom_bytes
)
cleanup_performed = pressure_before
after = before
if cleanup_performed:
_release_gpu_allocator_caches(torch_module)
after = _query_gpu_memory(torch_module)
# Unknown whole-device headroom is treated as pressure after cleanup.
pressure_after = after is None or _gpu_memory_is_under_pressure(
gpu_config, *after, required_headroom_bytes
)
should_spill = bool(request_spill and retained_tree_bytes > 0 and pressure_after)
return GpuMemoryDecision(
cleanup_performed=cleanup_performed,
should_spill=should_spill,
free_before_bytes=before[0] if before is not None else None,
free_after_bytes=after[0] if after is not None else None,
required_headroom_bytes=required_headroom_bytes,
pressure_before=pressure_before,
pressure_after=pressure_after,
)
def gpu_mode_maybe_empty_cache(
gpu_config,
force=False,
request_spill=False,
probe_bytes=None,
retained_tree_bytes=0,
required_headroom_bytes=None,
):
decision = gpu_mode_memory_decision(
gpu_config,
force=force,
request_spill=request_spill,
probe_bytes=probe_bytes,
retained_tree_bytes=retained_tree_bytes,
required_headroom_bytes=required_headroom_bytes,
)
return decision.should_spill if request_spill else decision.cleanup_performed
def classify_runtime_error(error_msg):
"""Classify runtime errors without printing or mutating log state."""
error_msg_lower = error_msg.lower()
if error_msg.startswith("[torch_assert_OOM]"):
return "oom", False
oom_markers = tuple(marker.lower() for marker in CUDA_OOM) + (
"cannot allocate memory",
"std::bad_alloc",
"bad allocation",
"memoryerror",
"cublas_status_alloc_failed",
)
if any(marker in error_msg_lower for marker in oom_markers):
return "oom", True
cuda_markers = tuple(marker.lower() for marker in CUDA_ERROR) + (
"illegal memory access",
"invalid configuration argument",
"invalid resource handle",
)
if any(marker in error_msg_lower for marker in cuda_markers):
return "paddle_cuda", True
# (Unimplemented): Paddle 已知不支持的功能,当前 case 无法有效验证
if "(unimplemented)" in error_msg_lower:
return "skip", False
# Paddle 输出数值检查失败
if "there are nan or inf" in error_msg_lower or "check_numerics" in error_msg_lower:
return "paddle_error", False
# (InvalidArgument) / (PreconditionNotMet) / (OutOfRange): 输入/配置不满足前提
if (
"(invalidargument)" in error_msg_lower
or "(preconditionnotmet)" in error_msg_lower
or "(outofrange)" in error_msg_lower
):
return "config_input", False
# Torch-side equivalents of invalid configs (accuracy runs torch before paddle).
torch_invalid_config_markers = (
"out of bounds for dimension",
"is invalid for input of size",
"must match the size of tensor b",
"does not match the shape of the indexed tensor",
)
if any(marker in error_msg_lower for marker in torch_invalid_config_markers):
return "config_input", False
return None, False
def _contains_non_finite_scalar(value):
if isinstance(value, bool) or isinstance(value, int):
return False
if isinstance(value, float):
return not math.isfinite(value)
if isinstance(value, numpy.generic):
try:
return not numpy.isfinite(value).item()
except Exception:
return False
if isinstance(value, complex):
return not math.isfinite(value.real) or not math.isfinite(value.imag)
if isinstance(value, TensorConfig):
return False
if isinstance(value, (list, tuple)):
return any(_contains_non_finite_scalar(item) for item in value)
if isinstance(value, (dict, collections.OrderedDict)):
return any(_contains_non_finite_scalar(item) for item in value.values())
return False
def _normalize_visible_gpu_device(value):
if not isinstance(value, str):
return value
match = _GPU_DEVICE_PATTERN.match(value)
if match is None:
return value
try:
gpu_count = paddle.device.cuda.device_count()
except Exception:
return value
if gpu_count <= 0:
return value
return f"cuda:{int(match.group(2)) % gpu_count}"
def _normalize_runtime_value_tree(value):
if isinstance(value, TensorConfig):
return value
if isinstance(value, list):
return [_normalize_runtime_value_tree(item) for item in value]
if isinstance(value, tuple):
return tuple(_normalize_runtime_value_tree(item) for item in value)
if isinstance(value, collections.OrderedDict):
return collections.OrderedDict(
(key, _normalize_runtime_value_tree(item)) for key, item in value.items()
)
if isinstance(value, dict):
return {key: _normalize_runtime_value_tree(item) for key, item in value.items()}
return _normalize_visible_gpu_device(value)
def _normalize_shape_like_api_arguments(api_name, args):
if api_name in {"paddle.zeros", "paddle.ones", "paddle.empty"}:
if len(args) > 1 and not isinstance(args[0], (list, tuple, TensorConfig)):
return [list(args)]
if api_name == "paddle.full":
if len(args) > 1 and not isinstance(args[0], (list, tuple, TensorConfig)):
return [list(args[:-1]), args[-1]]
return list(args)
def normalize_api_arguments(api_name, args, kwargs):
normalized_args = _normalize_shape_like_api_arguments(api_name, args)
normalized_args = _normalize_runtime_value_tree(normalized_args)
normalized_kwargs = _normalize_runtime_value_tree(kwargs)
return normalized_args, normalized_kwargs
def get_arg(api_config, arg_pos, arg_name, default=None):
if 0 <= arg_pos < len(api_config.args):
return api_config.args[arg_pos]
if arg_name in api_config.kwargs:
return api_config.kwargs[arg_name]
return default
no_signature_api_mappings = {
f"paddle.Tensor.{method}": {
"self": lambda cfg: get_arg(cfg, 0, "self"),
"y": lambda cfg: get_arg(cfg, 1, "y"),
}
for method in single_op_no_signature_apis
}
# For _C_ops builtins that share the same parameter names as a public Paddle API,
# we reuse the public API's signature for argument binding instead of a manual mapping.
# Positional args beyond the public API's parameter count (e.g. a trailing `place`)
# are silently dropped.
_COPS_API_PUBLIC_ALIAS: dict[str, str] = {
"paddle._C_ops.add_": "paddle.add",
"paddle._C_ops.bitwise_not": "paddle.bitwise_not",
"paddle._C_ops.clip": "paddle.clip",
"paddle._C_ops.concat": "paddle.concat",
"paddle._C_ops.flatten_": "paddle.flatten",
"paddle._C_ops.matmul": "paddle.matmul",
"paddle._C_ops.multiply_": "paddle.multiply",
"paddle._C_ops.numel": "paddle.numel",
"paddle._C_ops.put_along_axis_": "paddle.put_along_axis",
"paddle._C_ops.reshape_": "paddle.reshape",
"paddle._C_ops.scale_": "paddle.scale",
"paddle._C_ops.subtract_": "paddle.subtract",
"paddle._C_ops.transpose": "paddle.transpose",
"paddle._C_ops.uniform": "paddle.uniform",
}
# Manual mappings for _C_ops that have no public API counterpart or whose signature
# differs materially from any public API.
no_signature_api_mappings.update(
{
# adamw_(param, grad, lr, moment1, moment2, moment2_max,
# beta1_pow, beta2_pow, master_param, skip_update,
# beta1, beta2, epsilon, lr_ratio, coeff, with_decay,
# lazy_mode, min_row_size, multi_precision, use_global_beta_pow, amsgrad)
"paddle._C_ops.adamw_": {
"param": lambda cfg: get_arg(cfg, 0, "param"),
"grad": lambda cfg: get_arg(cfg, 1, "grad"),
"learning_rate": lambda cfg: get_arg(cfg, 2, "learning_rate"),
"moment1": lambda cfg: get_arg(cfg, 3, "moment1"),
"moment2": lambda cfg: get_arg(cfg, 4, "moment2"),
"moment2_max": lambda cfg: get_arg(cfg, 5, "moment2_max"),
"beta1_pow": lambda cfg: get_arg(cfg, 6, "beta1_pow"),
"beta2_pow": lambda cfg: get_arg(cfg, 7, "beta2_pow"),
"master_param": lambda cfg: get_arg(cfg, 8, "master_param"),
"skip_update": lambda cfg: get_arg(cfg, 9, "skip_update"),
"beta1": lambda cfg: get_arg(cfg, 10, "beta1"),
"beta2": lambda cfg: get_arg(cfg, 11, "beta2"),
"epsilon": lambda cfg: get_arg(cfg, 12, "epsilon"),
"lr_ratio": lambda cfg: get_arg(cfg, 13, "lr_ratio"),
"coeff": lambda cfg: get_arg(cfg, 14, "coeff"),
"with_decay": lambda cfg: get_arg(cfg, 15, "with_decay"),
"lazy_mode": lambda cfg: get_arg(cfg, 16, "lazy_mode"),
"min_row_size_to_use_multithread": lambda cfg: get_arg(
cfg, 17, "min_row_size_to_use_multithread"
),
"multi_precision": lambda cfg: get_arg(cfg, 18, "multi_precision"),
"use_global_beta_pow": lambda cfg: get_arg(cfg, 19, "use_global_beta_pow"),
"amsgrad": lambda cfg: get_arg(cfg, 20, "amsgrad"),
},
# full_(x, shape, value, dtype, place) — fills x in-place; no public API equivalent
"paddle._C_ops.full_": {
"x": lambda cfg: get_arg(cfg, 0, "x"),
"shape": lambda cfg: get_arg(cfg, 1, "shape"),
"value": lambda cfg: get_arg(cfg, 2, "value"),
"dtype": lambda cfg: get_arg(cfg, 3, "dtype"),
},
# fused_linear_param_grad_add(x, dout, dweight, dbias, multi_precision, has_bias)
"paddle._C_ops.fused_linear_param_grad_add": {
"x": lambda cfg: get_arg(cfg, 0, "x"),
"dout": lambda cfg: get_arg(cfg, 1, "dout"),
"dweight": lambda cfg: get_arg(cfg, 2, "dweight"),
"dbias": lambda cfg: get_arg(cfg, 3, "dbias"),
"multi_precision": lambda cfg: get_arg(cfg, 4, "multi_precision"),
"has_bias": lambda cfg: get_arg(cfg, 5, "has_bias"),
},
# gaussian(shape, mean, std, seed, dtype, place) — no paddle.gaussian public API
"paddle._C_ops.gaussian": {
"shape": lambda cfg: get_arg(cfg, 0, "shape"),
"mean": lambda cfg: get_arg(cfg, 1, "mean"),
"std": lambda cfg: get_arg(cfg, 2, "std"),
"seed": lambda cfg: get_arg(cfg, 3, "seed"),
"dtype": lambda cfg: get_arg(cfg, 4, "dtype"),
},
# matmul_grad(x, y, dout, transpose_x, transpose_y) -> (dx, dy)
"paddle._C_ops.matmul_grad": {
"x": lambda cfg: get_arg(cfg, 0, "x"),
"y": lambda cfg: get_arg(cfg, 1, "y"),
"dout": lambda cfg: get_arg(cfg, 2, "dout"),
"transpose_x": lambda cfg: get_arg(cfg, 3, "transpose_x"),
"transpose_y": lambda cfg: get_arg(cfg, 4, "transpose_y"),
},
# squared_l2_norm(x)
"paddle._C_ops.squared_l2_norm": {
"x": lambda cfg: get_arg(cfg, 0, "x"),
},
# swiglu_grad(x, y, dout) -> (dx, dy); y may be None (then x is split along last dim)
"paddle._C_ops.swiglu_grad": {
"x": lambda cfg: get_arg(cfg, 0, "x"),
"y": lambda cfg: get_arg(cfg, 1, "y"),
"dout": lambda cfg: get_arg(cfg, 2, "dout"),
},
# _run_custom_op(op_name, *args) — op_name dispatches to per-op sub-rules
"paddle._C_ops._run_custom_op": {
"op_name": lambda cfg: get_arg(cfg, 0, "op_name"),
"arg1": lambda cfg: get_arg(cfg, 1, "arg1"),
"arg2": lambda cfg: get_arg(cfg, 2, "arg2"),
"arg3": lambda cfg: get_arg(cfg, 3, "arg3"),
"arg4": lambda cfg: get_arg(cfg, 4, "arg4"),
},
}
)
class APITestBase:
def __init__(self, api_config, use_torch=True, runtime_config=None):
self.api_config = api_config
self.api_config.use_torch = use_torch
self.runtime_config = runtime_config or TestRuntimeConfig()
self.gpu_mode_config = self.runtime_config.gpu_mode
self.dump_context = (
DumpContext(
os.environ.get("DUMP_DIR") or DEFAULT_DUMP_DIR, api_config=api_config.config
)
if dump_enabled()
else None
)
self.outputs_grad_numpy = []
self.outputs_grad_paddleonly = []
if use_torch:
torch.set_num_threads(8)
torch.set_printoptions(threshold=100, linewidth=120)
def run_with_dump(self):
"""Execute the test with dump output capture and lifecycle reporting."""
if self.dump_context is None:
raise RuntimeError("run_with_dump() requires dump mode to be enabled")
with self.dump_context.tee_output():
try:
return self.test()
except Exception as err:
if self.dump_context._data.get("status") is None:
self.dump_finalize("engine_error", error=str(err))
raise
def dump_event(self, name, **data):
if self.dump_context:
self.dump_context.event(name, **data)
def dump_error(self, name, err):
if self.dump_context:
self.dump_context.error_event(name, err)
def dump_save(self, stem, obj, framework=None):
if self.dump_context:
self.dump_context.save_tensors(stem, obj, framework=framework)
def dump_finalize(self, status, **data):
if self.dump_context:
self.dump_context.finalize(status, **data)
def report_runtime_error(
self,
err,
default_log_type,
phase,
allow_ignore_paddle=False,
*,
tensor_position=None,
):
err_msg = str(err)
if phase:
self.dump_error(f"{phase}_error", err)
log_type, fatal = classify_runtime_error(err_msg)
if log_type is None and allow_ignore_paddle and self.should_ignore_paddle_error(err_msg):
print(f"[pass] {self.api_config.config}", flush=True)
write_to_log("pass", self.api_config.config)
return "pass", False
if log_type is None:
log_type = default_log_type
head = f"[{log_type}]"
if phase:
head += f" {phase}"
fields = []
if tensor_position:
fields.append(f"tensor {tensor_position}")
prefix = " | ".join([head, *fields])
print(
(
f"{prefix} | {self.api_config.config}\n{err_msg}"
if phase or fields
else f"{prefix} {self.api_config.config}\n{err_msg}"
),
flush=True,
)
write_to_log(log_type, self.api_config.config)
return log_type, fatal
def reset_random_state(self, seed=42):
"""Reset NumPy and framework RNGs for reproducible executions."""
numpy.random.seed(seed)
try:
paddle.seed(seed)
if paddle.device.is_compiled_with_cuda():
try:
for device_id in range(paddle.device.cuda.device_count()):
paddle.framework.core.default_cuda_generator(device_id).manual_seed(seed)
except Exception:
pass
except Exception:
pass
try:
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
except Exception:
pass
def clear_runtime_inputs(self, framework):
"""Release one framework's generated inputs after an execution."""
attr_names = [f"{framework}_args", f"{framework}_kwargs"]
if framework == "paddle":
attr_names.append("paddle_merged_kwargs")
for attr_name in attr_names:
if hasattr(self, attr_name):
delattr(self, attr_name)
if not self.gpu_mode_config.enabled and framework == "torch":
torch.cuda.empty_cache()
elif not self.gpu_mode_config.enabled:
paddle.device.cuda.empty_cache()
def report_compare_error(
self,
err,
phase,
default_log_type="paddle_accuracy",
*,
tensor_position=None,
):
log_type, fatal = self.report_runtime_error(
err,
default_log_type,
phase,
tensor_position=tensor_position,
)
if fatal:
raise err
return log_type, fatal
@contextlib.contextmanager
def disable_paddle_nan_inf_check_if_needed(self):
if not _contains_non_finite_scalar(
self.api_config.args
) and not _contains_non_finite_scalar(self.api_config.kwargs):
yield
return
flag_name = "FLAGS_check_nan_inf"
original_flags = None
try:
original_flags = paddle.get_flags([flag_name])
except Exception:
original_flags = None
if original_flags and flag_name in original_flags:
try:
paddle.set_flags({flag_name: False})
except Exception:
original_flags = None
try:
yield
finally:
if original_flags and flag_name in original_flags:
try:
paddle.set_flags({flag_name: original_flags[flag_name]})
except Exception:
pass
def need_skip(self, paddle_only=False):
# not support
if "sparse" in self.api_config.api_name:
return True
# if self.api_config.api_name in not_support_api:
# return True
# if not paddle_only and self.api_config.api_name in rand_apis:
# return True
# if not paddle_only and self.api_config.api_name in stochastic_behavior_apis:
# return True
if not paddle_only and self.api_config.config in torch_error_skip:
return True
# float8 dtypes are handled by TensorConfig / paddle_to_torch Rules;
# do not skip accuracy-mode comparison solely because of float8 inputs.
return False
def _has_float8_tensor_config(self):
"""True if any TensorConfig arg/kwarg uses float8 dtype."""
float8 = ("float8_e5m2", "float8_e4m3fn")
def _check(obj):
if isinstance(obj, TensorConfig):
return obj.dtype in float8
if isinstance(obj, (list, tuple)):
return any(_check(x) for x in obj)
return False
if any(_check(a) for a in self.api_config.args):
return True
return any(_check(v) for v in self.api_config.kwargs.values())
def need_check_grad(self):
if self.is_forward_only():
return False
# float8 autograd / numpy grad path is unsupported in current torch tooling
if self._has_float8_tensor_config():
return False
if self.api_config.api_name == "paddle.assign":
has_list_arg = len(self.paddle_args_config) and isinstance(
self.paddle_args_config[0], list
)
has_second_arg = (
len(self.paddle_args_config) > 1 and self.paddle_args_config[1] is not None
)
has_output_kwarg = self.paddle_kwargs_config.get("output") is not None
if has_list_arg or has_second_arg or has_output_kwarg:
return False
return True
# This part seems unused in any case:
#
# valid_dtypes = {'float32', 'float64', 'float16', 'complex64', 'complex128', 'bfloat16'}
# if len(self.api_config.args) > 0 and isinstance(self.api_config.args[0], TensorConfig):
# dtype = self.api_config.args[0].dtype
# if dtype in valid_dtypes:
# return True
# return True
# Original implementation:
#
# if not self.is_forward_only() and not (self.api_config.api_name == "paddle.assign" and len(self.paddle_args_config) and isinstance(self.paddle_args_config[0], list)) and not (self.api_config.api_name == "paddle.assign" and len(self.paddle_args_config) > 1 and self.paddle_args_config[1] is not None):
# if len(self.api_config.args) > 0 and isinstance(self.api_config.args[0], TensorConfig):
# dtype = self.api_config.args[0].dtype
# if dtype in ['float32', 'float64', 'float16', 'complex64', 'complex128', 'bfloat16']:
# return True
# return True
# return False
def ana_api_info(self):
return self.ana_paddle_api_info() and self.ana_torch_api_info()
def ana_paddle_api_info(self):
self.api_config.args, self.api_config.kwargs = normalize_api_arguments(
self.api_config.api_name, self.api_config.args, self.api_config.kwargs
)
self.paddle_api = eval(self.api_config.api_name)
self.paddle_args_config = self.api_config.args
self.paddle_kwargs_config = self.api_config.kwargs
return True
def ana_torch_api_info(self):
self.api_config.args, self.api_config.kwargs = normalize_api_arguments(
self.api_config.api_name, self.api_config.args, self.api_config.kwargs
)
self.torch_args_config = []
self.torch_kwargs_config = collections.OrderedDict()
self.paddle_merged_kwargs_config = collections.OrderedDict()
def finish(paddle_args_dict):
self.paddle_merged_kwargs_config = paddle_args_dict
self.torch_kwargs_config.update(paddle_args_dict)
self.torch_kwargs_config.pop("name", None)
return True
signature_cache = getattr(APITestBase.ana_torch_api_info, "_signature_cache", None)
if signature_cache is None:
signature_cache = {}
APITestBase.ana_torch_api_info._signature_cache = signature_cache
def get_signature(cache_key, api):
if cache_key not in signature_cache:
try:
signature_cache[cache_key] = inspect.signature(api)
except ValueError:
signature_cache[cache_key] = None
return signature_cache[cache_key]
api_name = self.api_config.api_name
if api_name in ("paddle.Tensor.__getitem__", "paddle.Tensor.__setitem__"):
self.torch_args_config = self.api_config.args
return True
if api_name in ("paddle.Tensor.view", "paddle.view"):
# paddle.view supports variadic int args: view(-1, 4096) in addition to view([-1, 4096])
# inspect.bind incorrectly maps the second int to `name` param, so handle manually.
args = self.api_config.args
rest = args[1:]
if len(rest) > 1 and all(isinstance(arg, int) for arg in rest):
return finish({"x": args[0], "shape_or_dtype": list(rest)})
paddle_sig = get_signature(api_name, self.paddle_api)
if paddle_sig is None:
raise ValueError(f"API {api_name} has no inspectable signature")
paddle_bound_args = paddle_sig.bind(*args, **self.api_config.kwargs)
return finish(paddle_bound_args.arguments)
if api_name in ("paddle.Tensor.reshape", "paddle.reshape"):
# paddle.reshape supports variadic int args: reshape(1, 2048, -1) in addition to reshape([1, 2048, -1])
# Tensor.reshape signature is (x, shape, name=None), so bind() rejects multiple ints.
args = self.api_config.args
rest = args[1:]
if len(rest) >= 1 and all(isinstance(arg, int) for arg in rest):
return finish({"x": args[0], "shape": list(rest)})
if api_name in no_signature_api_mappings:
# For APIs without signatures, use the external mapping dict
mapping = no_signature_api_mappings[api_name]
return finish(
{key: get_value_func(self.api_config) for key, get_value_func in mapping.items()}
)
# For APIs with signatures, use paddle_sig.bind to get arguments.
paddle_sig = get_signature(api_name, self.paddle_api)
if paddle_sig is None:
# _C_ops builtins have no inspectable signature. If the op has a public
# API counterpart with the same params, use its signature.
public_api_name = _COPS_API_PUBLIC_ALIAS.get(api_name)
if public_api_name is None:
# No alias and no manual mapping — forward-only, skip torch comparison.
return True
paddle_sig = get_signature(public_api_name, eval(public_api_name))
if paddle_sig is None:
raise ValueError(f"API {public_api_name} has no inspectable signature")
positional_count = sum(
1
for param in paddle_sig.parameters.values()
if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD)
)
valid_names = set(paddle_sig.parameters)
filtered_kwargs = {
key: value for key, value in self.api_config.kwargs.items() if key in valid_names
}
paddle_bound_args = paddle_sig.bind(
*self.api_config.args[:positional_count], **filtered_kwargs
)
return finish(paddle_bound_args.arguments)
paddle_bound_args = paddle_sig.bind(*self.api_config.args, **self.api_config.kwargs)
paddle_args_dict = paddle_bound_args.arguments
# fix paddle.arange wrong binding
if api_name == "paddle.arange":
# if end is not provided, use the 'start' kwargs as end
if "end" not in paddle_args_dict:
paddle_args_dict["end"] = paddle_args_dict["start"]
paddle_args_dict["start"] = 0
return finish(paddle_args_dict)
def _handle_list_or_tuple(
self, config_items, is_tuple=False, index=None, key=None, list_index=None
):
"""处理 list 或 tuple"""
if list_index is None:
list_index = []
need_axes_handling = self.api_config.api_name in handle_axes_api
need_indices_handling = self.api_config.api_name == "paddle.index_put"
if need_indices_handling and (index == 1 or key == "indices"):
return self._handle_indices_arg(config_items, is_tuple)
elif need_axes_handling and (index == 1 or key == "axis"):
return self._handle_axis_arg(config_items, is_tuple)
tmp = []
for i, item in enumerate(config_items):
current_list_index = [*list_index, i]
if isinstance(item, (list, tuple)):
is_nested_tuple = isinstance(item, tuple)
processed_item = self._handle_list_or_tuple(
item,
is_tuple=is_nested_tuple,
index=index,
key=key,
list_index=current_list_index,
)
elif isinstance(item, TensorConfig):
processed_item = item.get_numpy_tensor(
self.api_config, index=index, key=key, list_index=current_list_index
)
else:
processed_item = item
tmp.append(processed_item)
return tuple(tmp) if is_tuple else tmp
def _handle_axis_arg(self, config_items, is_tuple=False):
"""处理 axis 参数"""
x = (
self.paddle_args_config[0]
if len(self.paddle_args_config) > 0
else self.paddle_kwargs_config["x"]
)
max_dim = max(len(x.shape), 1) # scalar
tmp = []
used_axes = set()
tensor_configs = []
for item in config_items:
if isinstance(item, TensorConfig):
if item.shape not in [[], [1]] or item.dtype not in ["int32", "int64"]:
raise ValueError(
f"Invalid TensorConfig for axis: shape {item.shape} or dtype {item.dtype}"
)
tensor_configs.append(item)
tmp.append(0) # placeholder
elif isinstance(item, int):
if not (-max_dim <= item < max_dim):
raise ValueError(f"Axis value {item} out of range [-{max_dim}, {max_dim})")
positive_axis = item + max_dim if item < 0 else item
if positive_axis in used_axes:
raise ValueError(f"Duplicate axis value: {item}")
used_axes.add(positive_axis)
tmp.append(item)
else:
raise ValueError(f"Invalid item type for axis: {type(item)}")
if tensor_configs:
available_dims = list(set(range(max_dim)) - used_axes)
if len(available_dims) < len(tensor_configs):
raise ValueError(
f"Not enough available dimensions ({len(available_dims)}) for {len(tensor_configs)} TensorConfig items"
)
selected_dims = numpy.random.choice(
available_dims, size=len(tensor_configs), replace=False
)
mask = numpy.random.randint(0, 2, size=len(tensor_configs)).astype(bool)
final_dims = numpy.where(mask, selected_dims - max_dim, selected_dims)
tensor_idx = 0
for i, item in enumerate(config_items):
if isinstance(item, TensorConfig):
item.fill_numpy_tensor(final_dims[tensor_idx])
tmp[i] = item.get_numpy_tensor(self.api_config)
tensor_idx += 1
return tuple(tmp) if is_tuple else tmp
def _generate_int_indices(self, item_shape, dim_size):
num_elements = numpy.prod(item_shape).item()
if num_elements > dim_size:
indices_flat = numpy.random.randint(-dim_size, dim_size, size=num_elements)
else:
indices_flat = numpy.random.choice(dim_size, size=num_elements, replace=False)
return indices_flat.reshape(item_shape)
def _generate_constrained_bool_mask(self, shape, num_true):
mask_size = numpy.prod(shape).item()
if mask_size < num_true:
raise ValueError(
f"Cannot generate a mask with {num_true} true values in a {mask_size} element mask"
)
mask_flat = numpy.zeros(mask_size, dtype="bool")
true_indices = numpy.random.choice(mask_size, num_true, replace=False)
mask_flat[true_indices] = True
return mask_flat.reshape(shape)
def _broadcast_or_raise(self, shapes):
return numpy.broadcast_shapes(*[tuple(s) for s in shapes])
def _handle_indices_arg(self, config_items, is_tuple=False):
x = (
self.paddle_args_config[0]
if len(self.paddle_args_config) > 0
else self.paddle_kwargs_config["x"]
)
value = (
self.paddle_args_config[2]
if len(self.paddle_args_config) > 2
else self.paddle_kwargs_config["value"]
)
x_shape = x.shape
value_shape = value.shape
int_index_shapes = []
has_bool_index = False
dims_consumed = 0
for item in config_items:
if item.dtype == "bool":
b_rank = len(item.shape)
has_bool_index = True
dims_consumed += b_rank
else:
int_index_shapes.append(tuple(item.shape))
dims_consumed += 1
if dims_consumed > len(x_shape):
raise ValueError(
f"Too many indices: consume {dims_consumed} dims but x has {len(x_shape)} dims"
)
num_true_needed = -1
num_remaining_dims = len(x_shape) - dims_consumed
advanced_shape = ()
if int_index_shapes:
try:
advanced_shape = self._broadcast_or_raise(int_index_shapes)
# give a default 1
if (
has_bool_index
and len(value_shape) > num_remaining_dims
and advanced_shape[-1] == 1
and value_shape[-num_remaining_dims - 1] != 1
):
advanced_shape = (
*advanced_shape[:-1],
value_shape[-num_remaining_dims - 1],
)
num_true_needed = advanced_shape[-1]
except Exception:
raise ValueError(
f"Incompatible integer index shapes for broadcasting: {int_index_shapes}"
)
elif has_bool_index:
if len(value_shape) > num_remaining_dims: