-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
op_test.py
4117 lines (3751 loc) · 161 KB
/
op_test.py
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
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import inspect
import os
import pathlib
import random
import struct
import sys
import unittest
import warnings
from collections import defaultdict
from contextlib import contextmanager
from copy import copy
import numpy as np
from auto_parallel_op_test import (
dump_test_info,
gen_auto_parallel_test_file,
get_subprocess_command,
get_subprocess_runtime_envs,
get_test_info_and_generated_test_path,
is_ban_auto_parallel_test,
run_subprocess,
)
from op import Operator
from prim_op_test import OpTestUtils, PrimForwardChecker, PrimGradChecker
from testsuite import append_input_output, append_loss_ops, create_op, set_input
# Add test/legacy and test to sys.path
legacy_test_dir = pathlib.Path(__file__).parent # test/legacy_test
test_dir = legacy_test_dir.parent # test
sys.path.append(str(legacy_test_dir.absolute()))
sys.path.append(str(test_dir.absolute()))
from utils import pir_executor_guard, static_guard
from white_list import (
check_shape_white_list,
compile_vs_runtime_white_list,
no_check_set_white_list,
no_grad_set_white_list,
op_accuracy_white_list,
op_threshold_white_list,
)
import paddle
from paddle import base
from paddle.autograd.ir_backward import grad as ir_grad
from paddle.base import Scope, core, unique_name
from paddle.base.backward import append_backward
from paddle.base.executor import Executor, scope_guard
from paddle.base.framework import (
OpProtoHolder,
Program,
_current_expected_place,
canonicalize_attrs,
get_flags,
set_flags,
)
from paddle.base.wrapped_decorator import signature_safe_contextmanager
@signature_safe_contextmanager
def paddle_static_guard():
try:
paddle.enable_static()
yield
finally:
paddle.disable_static()
def check_out_dtype(api_fn, in_specs, expect_dtypes, target_index=0, **configs):
"""
Determines whether dtype of output tensor is as expected.
Args:
api_fn(callable): paddle api function
in_specs(list[tuple]): list of shape and dtype information for constructing input tensor of api_fn, such as [(shape, dtype), (shape, dtype)].
expect_dtypes(list[str]): expected dtype of output tensor.
target_index(int): indicate which one from in_specs to infer the dtype of output.
config(dict): other arguments of paddle api function
Example:
check_out_dtype(base.layers.pad_constant_like, [([2,3,2,3], 'float64'), ([1, 3, 1,3], )], ['float32', 'float64', 'int64'], target_index=1, pad_value=0.)
"""
with paddle.pir_utils.OldIrGuard():
for i, expect_dtype in enumerate(expect_dtypes):
with paddle.static.program_guard(paddle.static.Program()):
input_t = []
for index, spec in enumerate(in_specs):
if len(spec) == 1:
shape = spec[0]
dtype = (
expect_dtype if target_index == index else 'float32'
)
elif len(spec) == 2:
shape, dtype = spec
else:
raise ValueError(
f"Value of in_specs[{index}] should contains two elements: [shape, dtype]"
)
input_t.append(
paddle.static.data(
name=f'data_{index}', shape=shape, dtype=dtype
)
)
out = api_fn(*input_t, **configs)
out_dtype = base.data_feeder.convert_dtype(out.dtype)
if out_dtype != expect_dtype:
raise ValueError(
f"Expected out.dtype is {expect_dtype}, but got {out_dtype} from {api_fn.__name__}."
)
def _set_use_system_allocator(value=None):
USE_SYSTEM_ALLOCATOR_FLAG = "FLAGS_use_system_allocator"
old_value = core.globals()[USE_SYSTEM_ALLOCATOR_FLAG]
value = old_value if value is None else value
core.globals()[USE_SYSTEM_ALLOCATOR_FLAG] = value
return old_value
def randomize_probability(batch_size, class_num, dtype='float32'):
prob = np.random.uniform(0.1, 1.0, size=(batch_size, class_num)).astype(
dtype
)
prob_sum = prob.sum(axis=1)
for i in range(len(prob)):
prob[i] /= prob_sum[i]
return prob
def get_numeric_gradient(
place,
scope,
op,
inputs,
input_to_check,
output_names,
delta=0.005,
in_place=False,
):
# FIXME: change this method by compile time concepts
set_input(scope, op, inputs, place)
def product(dim):
return functools.reduce(lambda a, b: a * b, dim, 1)
tensor_to_check = scope.find_var(input_to_check).get_tensor()
tensor_size = product(tensor_to_check.shape())
tensor_to_check_dtype = tensor_to_check._dtype()
if tensor_to_check_dtype == paddle.float32:
tensor_to_check_dtype = np.float32
elif tensor_to_check_dtype == paddle.float64:
tensor_to_check_dtype = np.float64
elif tensor_to_check_dtype == paddle.float16:
tensor_to_check_dtype = np.float16
# set delta as np.float16, will automatic convert to float32, float64
delta = np.array(delta).astype(np.float16)
elif tensor_to_check_dtype == paddle.bfloat16:
tensor_to_check_dtype = np.float32
elif tensor_to_check_dtype == paddle.complex64:
tensor_to_check_dtype = np.complex64
elif tensor_to_check_dtype == paddle.complex128:
tensor_to_check_dtype = np.complex128
else:
raise ValueError(
"Not supported data type "
+ str(tensor_to_check_dtype)
+ ", tensor name : "
+ str(input_to_check)
)
def get_output():
sum = []
op.run(scope, place)
for output_name in output_names:
output_numpy = np.array(scope.find_var(output_name).get_tensor())
# numpy.dtype does not have bfloat16, thus we use numpy.uint16 to
# store bfloat16 data, and need to be converted to float to check
# the floating precision.
if tensor_to_check._dtype() == paddle.bfloat16:
output_numpy = convert_uint16_to_float(output_numpy)
sum.append(output_numpy.astype(tensor_to_check_dtype).mean())
return tensor_to_check_dtype(np.array(sum).sum() / len(output_names))
gradient_flat = np.zeros(shape=(tensor_size,), dtype=tensor_to_check_dtype)
def __get_elem__(tensor, i):
if tensor_to_check_dtype == np.float16:
numpy_tensor = np.array(tensor).astype(np.float16)
numpy_tensor = numpy_tensor.flatten()
return numpy_tensor[i]
elif tensor_to_check._dtype() == paddle.bfloat16:
numpy_tensor = np.array(tensor).astype(np.uint16)
numpy_tensor = numpy_tensor.flatten()
return struct.unpack(
'<f',
struct.pack('<I', np.uint32(numpy_tensor[i]) << np.uint32(16)),
)[0]
elif tensor_to_check_dtype == np.float32:
return tensor._get_float_element(i)
elif tensor_to_check_dtype == np.float64:
return tensor._get_double_element(i)
elif tensor_to_check_dtype == np.complex64:
return tensor._get_complex64_element(i)
elif tensor_to_check_dtype == np.complex128:
return tensor._get_complex128_element(i)
else:
raise TypeError(
f"Unsupported test data type {tensor_to_check_dtype}."
)
def __set_elem__(tensor, i, e):
if tensor_to_check_dtype == np.float16:
numpy_tensor = np.array(tensor).astype(np.float16)
shape = numpy_tensor.shape
numpy_tensor = numpy_tensor.flatten()
numpy_tensor[i] = e
numpy_tensor = numpy_tensor.reshape(shape)
tensor.set(numpy_tensor, place)
elif tensor_to_check._dtype() == paddle.bfloat16:
numpy_tensor = np.array(tensor).astype(np.uint16)
shape = numpy_tensor.shape
numpy_tensor = numpy_tensor.flatten()
numpy_tensor[i] = np.uint16(copy_bits_from_float_to_uint16(e))
numpy_tensor = numpy_tensor.reshape(shape)
tensor.set(numpy_tensor, place)
elif tensor_to_check_dtype == np.float32:
tensor._set_float_element(i, e)
elif tensor_to_check_dtype == np.float64:
tensor._set_double_element(i, e)
elif tensor_to_check_dtype == np.complex64:
return tensor._set_complex64_element(i, e)
elif tensor_to_check_dtype == np.complex128:
return tensor._set_complex128_element(i, e)
else:
raise TypeError(
f"Unsupported test data type {tensor_to_check_dtype}."
)
# we only compute gradient of one element each time.
# we use a for loop to compute the gradient of every element.
for i in range(tensor_size):
if in_place:
set_input(scope, op, inputs, place)
# get one input element throw it's index i.
origin = __get_elem__(tensor_to_check, i)
# add delta to it, run op and then get the sum of the result tensor.
x_pos = origin + delta
__set_elem__(tensor_to_check, i, x_pos)
y_pos = get_output()
if tensor_to_check_dtype in [np.complex64, np.complex128]:
if in_place:
set_input(scope, op, inputs, place)
x_pos_j = origin + 1j * delta
__set_elem__(tensor_to_check, i, x_pos_j)
y_pos_j = get_output()
if in_place:
set_input(scope, op, inputs, place)
x_neg = origin - delta
__set_elem__(tensor_to_check, i, x_neg)
y_neg = get_output()
if tensor_to_check_dtype in [np.complex64, np.complex128]:
if in_place:
set_input(scope, op, inputs, place)
x_neg_j = origin - 1j * delta
__set_elem__(tensor_to_check, i, x_neg_j)
y_neg_j = get_output()
__set_elem__(tensor_to_check, i, origin)
if tensor_to_check_dtype in [np.complex64, np.complex128]:
# always assume real output, because this function has
# no input for dl/di, though it should do. so there di will be zero
# TODO: Here is a trick to be consistent with the existing OpTest, it
# need to support variable gradients input
f_ajoint = np.array(1 + 0j)
df_over_dr = (y_pos - y_neg) / delta / 2
df_over_di = (y_pos_j - y_neg_j) / delta / 2
dl_over_du, dl_over_dv = f_ajoint.real, f_ajoint.imag
du_over_dr, dv_over_dr = df_over_dr.real, df_over_dr.imag
du_over_di, dv_over_di = df_over_di.real, df_over_di.imag
dl_over_dr = np.sum(
dl_over_du * du_over_dr + dl_over_dv * dv_over_dr
)
dl_over_di = np.sum(
dl_over_du * du_over_di + dl_over_dv * dv_over_di
)
gradient_flat[i] = dl_over_dr + 1j * dl_over_di
else:
df_over_dr = y_pos - y_neg
gradient_flat[i] = df_over_dr / delta / 2
__set_elem__(tensor_to_check, i, origin)
return gradient_flat.reshape(tensor_to_check.shape())
def skip_check_grad_ci(reason=None):
"""Decorator to skip check_grad CI.
Check_grad is required for Op test cases. However, there are some special
cases that do not need to do check_grad. This decorator is used to skip the
check_grad of the above cases.
Note: the execution of unit test will not be skipped. It just avoids check_grad
checking in tearDownClass method by setting a `no_need_check_grad` flag.
Example:
@skip_check_grad_ci(reason="For inference, check_grad is not required.")
class TestInference(OpTest):
"""
if not isinstance(reason, str):
raise AssertionError("The reason for skipping check_grad is required.")
def wrapper(cls):
cls.no_need_check_grad = True
return cls
return wrapper
def skip_check_inplace_ci(reason=None):
if not isinstance(reason, str):
raise AssertionError(
"The reason for skipping check_inplace is required."
)
def wrapper(cls):
cls.no_need_check_inplace = True
return cls
return wrapper
def copy_bits_from_float_to_uint16(f):
return struct.unpack('<I', struct.pack('<f', f))[0] >> 16
def convert_float_to_uint16(float_list, data_format="NCHW"):
if data_format == "NHWC":
float_list = np.transpose(float_list, [0, 3, 1, 2])
new_output = []
for x in np.nditer(float_list):
new_output.append(np.uint16(copy_bits_from_float_to_uint16(x)))
new_output = np.reshape(new_output, float_list.shape).view(np.uint16)
if data_format == "NHWC":
new_output = np.transpose(new_output, [0, 2, 3, 1])
return new_output
def convert_uint16_to_float(in_list):
in_list = np.asarray(in_list)
out = np.vectorize(
lambda x: struct.unpack(
'<f', struct.pack('<I', np.uint32(x) << np.uint32(16))
)[0],
otypes=[np.float32],
)(in_list.flat)
return np.reshape(out, in_list.shape)
@contextmanager
def auto_parallel_test_guard(test_info_path, generated_test_file_path):
test_info_file, generated_test_file = None, None
if os.path.exists(test_info_path):
raise OSError(
f"{test_info_path} which stores test info should not exist. Please delete it firstly."
)
if os.path.exists(generated_test_file_path):
raise OSError(
f"{generated_test_file_path} which stores test code should not exist. Please delete it firstly."
)
test_info_file = open(test_info_path, "wb")
generated_test_file = open(generated_test_file_path, "wb")
try:
yield
finally:
if test_info_file is not None:
test_info_file.close()
if generated_test_file is not None:
generated_test_file.close()
if os.path.exists(test_info_path):
os.remove(test_info_path)
if os.path.exists(generated_test_file_path):
os.remove(generated_test_file_path)
class OpTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
'''Fix random seeds to remove randomness from tests'''
cls._np_rand_state = np.random.get_state()
cls._py_rand_state = random.getstate()
cls.call_once = False
cls.dtype = None
cls.outputs = {}
cls.input_shape_is_large = True
cls.is_calc_ref = False
cls.check_prim = False
cls.check_prim_pir = False
cls._check_cinn = False
cls.check_pir_onednn = False
# Todo(CZ): to be removed in future
core._clear_prim_vjp_skip_default_ops()
np.random.seed(123)
random.seed(124)
cls._use_system_allocator = _set_use_system_allocator(True)
@classmethod
def tearDownClass(cls):
"""Restore random seeds"""
np.random.set_state(cls._np_rand_state)
random.setstate(cls._py_rand_state)
_set_use_system_allocator(cls._use_system_allocator)
if hasattr(cls, 'check_prim') and os.getenv('FLAGS_prim_test_log'):
print("check prim end!")
def is_empty_grad_op(op_type):
all_op_kernels = core._get_all_register_op_kernels()
grad_op = op_type + '_grad'
if grad_op in all_op_kernels.keys():
if is_mkldnn_op_test():
grad_op_kernels = all_op_kernels[grad_op]
for grad_op_kernel in grad_op_kernels:
if 'MKLDNN' in grad_op_kernel:
return False
else:
return False
return True
def is_xpu_op_test():
return hasattr(cls, "use_xpu") and cls.use_xpu
def is_mkldnn_op_test():
return hasattr(cls, "use_mkldnn") and cls.use_mkldnn
def is_rocm_op_test():
return core.is_compiled_with_rocm()
def is_custom_device_op_test():
return hasattr(cls, "use_custom_device") and cls.use_custom_device
def is_complex_test():
return (
hasattr(cls, "test_complex")
and cls.test_complex
or (cls.dtype in [np.complex64, np.complex128])
)
if not hasattr(cls, "op_type"):
raise AssertionError(
"This test do not have op_type in class attrs, "
"please set self.__class__.op_type=the_real_op_type manually."
)
# case in NO_FP64_CHECK_GRAD_CASES and op in NO_FP64_CHECK_GRAD_OP_LIST should be fixed
if (
not hasattr(cls, "no_need_check_grad")
and not is_empty_grad_op(cls.op_type)
and not is_complex_test()
):
if cls.dtype is None or (
cls.dtype == np.float16
and cls.op_type
not in op_accuracy_white_list.NO_FP16_CHECK_GRAD_OP_LIST
and not hasattr(cls, "exist_check_grad")
):
raise AssertionError(
f"This test of {cls.op_type} op needs check_grad."
)
# check for op test with fp64 precision, but not check onednn op test for now
if (
cls.dtype in [np.float32, np.float64]
and cls.op_type
not in op_accuracy_white_list.NO_FP64_CHECK_GRAD_OP_LIST
and not hasattr(cls, 'exist_fp64_check_grad')
and not is_xpu_op_test()
and not is_mkldnn_op_test()
and not is_rocm_op_test()
and not is_custom_device_op_test()
and not cls.check_prim
and not cls.check_prim_pir
):
raise AssertionError(
f"This test of {cls.op_type} op needs check_grad with fp64 precision."
)
if (
not cls.input_shape_is_large
and cls.op_type
not in check_shape_white_list.NEED_TO_FIX_OP_LIST
):
raise AssertionError(
"Number of element(s) of input should be large than or equal to 100 for "
+ cls.op_type
+ " Op."
)
def try_call_once(self, data_type):
if not self.call_once:
self.call_once = True
self.dtype = data_type
def is_bfloat16_op(self):
# self.dtype is the dtype of inputs, and is set in infer_dtype_from_inputs_outputs.
# Make sure this function is called after calling infer_dtype_from_inputs_outputs.
return (
self.dtype == np.uint16
or (
hasattr(self, 'output_dtype') and self.output_dtype == np.uint16
)
or (
hasattr(self, 'mkldnn_data_type')
and self.mkldnn_data_type == "bfloat16"
)
or (
hasattr(self, 'attrs')
and 'mkldnn_data_type' in self.attrs
and self.attrs['mkldnn_data_type'] == 'bfloat16'
)
)
def is_float16_op(self):
# self.dtype is the dtype of inputs, and is set in infer_dtype_from_inputs_outputs.
# Make sure this function is called after calling infer_dtype_from_inputs_outputs.
return (
self.dtype == np.float16
or self.dtype == "float16"
or (
hasattr(self, 'output_dtype')
and self.output_dtype == np.float16
)
or (
hasattr(self, 'mkldnn_data_type')
and self.mkldnn_data_type == "float16"
)
or (
hasattr(self, 'attrs')
and 'mkldnn_data_type' in self.attrs
and self.attrs['mkldnn_data_type'] == 'float16'
)
)
def is_mkldnn_op(self):
return (hasattr(self, "use_mkldnn") and self.use_mkldnn) or (
hasattr(self, "attrs")
and "use_mkldnn" in self.attrs
and self.attrs["use_mkldnn"]
)
def is_xpu_op(self):
return (hasattr(self, "use_xpu") and self.use_xpu) or (
hasattr(self, "attrs")
and "use_xpu" in self.attrs
and self.attrs["use_xpu"]
)
def is_fp16_compared_with_fp32(self):
return self.is_float16_op() and (
self.op_type
not in op_accuracy_white_list.NO_FP16_COMPARED_WITH_FP32_OP_LIST
)
def is_bf16_compared_with_fp32(self):
return self.is_bfloat16_op() and (
self.op_type
not in op_accuracy_white_list.NO_BF16_COMPARED_WITH_FP32_OP_LIST
)
def is_compared_with_fp32(self):
return (
self.is_fp16_compared_with_fp32()
or self.is_bf16_compared_with_fp32()
)
def enable_cal_ref_output(self):
self.is_calc_ref = True
def disable_cal_ref_output(self):
self.is_calc_ref = False
def _enable_check_cinn_test(self, place, inputs, outputs):
# if the test not run in cuda or the paddle not compile with CINN, skip cinn test
if (
not core.is_compiled_with_cinn()
or not core.is_compiled_with_cuda()
or not isinstance(place, base.CUDAPlace)
):
return False
# CINN not support bfloat16 now, skip cinn test
if self.is_bfloat16_op():
return False
# CINN not support 0D-tensor now, skip cinn test
for var in inputs.values():
if len(var.shape()) == 0:
return False
for var in outputs.values():
if len(var.shape) == 0:
return False
# CINN not support dynamic shape now, skip cinn test
# TODO(thisjiang): cannot check dynamic shape op automatic, should do manually now
return True
# set the self.output_dtype .
def infer_dtype_from_inputs_outputs(self, inputs, outputs):
def is_np_data(input):
return isinstance(input, (np.ndarray, np.generic))
def infer_dtype(numpy_dict, dtype_set):
assert isinstance(
numpy_dict, dict
), "self.inputs, self.outputs must be numpy_dict"
# the inputs are as follows:
# case 1: inputs = {'X': x}
# case 2: inputs = {'X': (x, x_lod)}
# case 3: inputs = {"X": [("x0", x0), ("x1", x1), ("x2", x2)]}
# case 4: inputs = {'X': [("x1", (x1, [x1_lod1])), ("x2", (x2, [x2_.lod2]))]}
# TODO(juncaipeng) infer dtype from inputs maybe obtain wrong type.
for _, var_value in numpy_dict.items():
if is_np_data(var_value): # case 1
dtype_set.add(var_value.dtype)
elif isinstance(var_value, (list, tuple)): # case 2, 3, 4
for sub_val_value in var_value:
if is_np_data(sub_val_value): # case 2
dtype_set.add(sub_val_value.dtype)
elif len(sub_val_value) > 1 and is_np_data(
sub_val_value[1]
): # case 3
dtype_set.add(sub_val_value[1].dtype)
elif (
len(sub_val_value) > 1
and isinstance(sub_val_value[1], (list, tuple))
and is_np_data(sub_val_value[1][0])
): # case 4
dtype_set.add(sub_val_value[1][0].dtype)
# infer dtype from inputs, and dtype means the precision of the test
# collect dtype of all inputs
input_dtype_set = set()
infer_dtype(inputs, input_dtype_set)
dtype_list = [
np.dtype(np.complex128),
np.dtype(np.complex64),
np.dtype(np.float64),
np.dtype(np.float32),
np.dtype(np.float16),
np.dtype(np.int64),
np.dtype(np.int32),
np.dtype(np.uint16),
np.dtype(np.int16),
np.dtype(np.int8),
np.dtype(np.uint8),
np.dtype(np.bool_),
]
# check the dtype in dtype_list in order, select the first dtype that in dtype_set
for dtype in dtype_list:
if dtype in input_dtype_set:
self.dtype = dtype
break
# save input dtype in class attr
self.__class__.dtype = self.dtype
# infer dtype of outputs
output_dtype_set = set()
infer_dtype(outputs, output_dtype_set)
for dtype in dtype_list:
if dtype in output_dtype_set:
self.output_dtype = dtype
break
def feed_var(self, input_vars, place):
feed_map = {}
for var_name in input_vars:
if isinstance(input_vars[var_name], list):
for name, np_value in self.inputs[var_name]:
tensor = core.LoDTensor()
if isinstance(np_value, tuple):
tensor.set(np_value[0], place)
dtype = np.array(np_value[1]).dtype
if self.is_calc_ref:
# convert the float16 to float by numpy.astype
if dtype == np.float16:
if isinstance(np_value[1], list):
tensor.set_recursive_sequence_lengths(
np.array(np_value[1]).astype(np.float32)
)
else:
tensor.set_recursive_sequence_lengths(
np_value[1].astype(np.float32)
)
# convert the bfloat16 to float by convert_uint16_to_float
# provided in this file
elif dtype == np.uint16:
if isinstance(np_value[1], list):
tensor.set_recursive_sequence_lengths(
convert_uint16_to_float(
np.array(np_value[1])
)
)
else:
tensor.set_recursive_sequence_lengths(
convert_uint16_to_float(np_value[1])
)
else:
tensor.set_recursive_sequence_lengths(
np_value[1]
)
else:
tensor.set_recursive_sequence_lengths(np_value[1])
else:
if self.is_calc_ref:
if np_value.dtype == np.float16:
tensor.set(np_value.astype(np.float32), place)
elif np_value.dtype == np.uint16:
tensor.set(
convert_uint16_to_float(np_value), place
)
else:
tensor.set(np_value, place)
else:
tensor.set(np_value, place)
feed_map[name] = tensor
else:
tensor = core.LoDTensor()
if isinstance(self.inputs[var_name], tuple):
tensor.set(self.inputs[var_name][0], place)
if self.is_calc_ref:
if isinstance(self.inputs[var_name][1], list):
dtype = np.array(self.inputs[var_name][1]).dtype
if dtype == np.float16:
tensor.set_recursive_sequence_lengths(
np.array(self.inputs[var_name][1]).astype(
np.float32
)
)
elif dtype == np.uint16:
tensor.set_recursive_sequence_lengths(
convert_uint16_to_float(
np.array(self.inputs[var_name][1])
)
)
else:
tensor.set_recursive_sequence_lengths(
self.inputs[var_name][1]
)
elif self.inputs[var_name][1].dtype == np.float16:
tensor.set_recursive_sequence_lengths(
self.inputs[var_name][1].astype(np.float32)
)
elif self.inputs[var_name][1].dtype == np.uint16:
tensor.set_recursive_sequence_lengths(
convert_uint16_to_float(
self.inputs[var_name][1]
)
)
else:
tensor.set_recursive_sequence_lengths(
self.inputs[var_name][1]
)
else:
tensor.set_recursive_sequence_lengths(
self.inputs[var_name][1]
)
else:
if self.is_calc_ref:
if self.inputs[var_name].dtype == np.float16:
tensor.set(
self.inputs[var_name].astype(np.float32), place
)
elif self.inputs[var_name].dtype == np.uint16:
tensor.set(
convert_uint16_to_float(self.inputs[var_name]),
place,
)
else:
tensor.set(self.inputs[var_name], place)
else:
tensor.set(self.inputs[var_name], place)
feed_map[var_name] = tensor
return feed_map
def _append_ops(self, block):
self.__class__.op_type = (
self.op_type
) # for ci check, please not delete it for now
if self.is_mkldnn_op():
self.__class__.use_mkldnn = True
if self.is_xpu_op():
self.__class__.use_xpu = True
op_proto = OpProtoHolder.instance().get_op_proto(self.op_type)
# "infer datatype from inputs and outputs for this test case"
if self.is_float16_op():
self.dtype = np.float16
self.__class__.dtype = self.dtype
self.output_dtype = np.float16
elif self.is_bfloat16_op():
self.dtype = np.uint16
self.__class__.dtype = self.dtype
self.output_dtype = np.uint16
else:
self.infer_dtype_from_inputs_outputs(self.inputs, self.outputs)
inputs = append_input_output(
block, op_proto, self.inputs, True, self.dtype, self.is_calc_ref
)
outputs = append_input_output(
block, op_proto, self.outputs, False, self.dtype, self.is_calc_ref
)
if hasattr(self, "cache_name_list"):
for name in self.cache_name_list:
inputs[name] = block.create_var(
name=name,
persistable=True,
type=core.VarDesc.VarType.RAW,
stop_gradient=True,
)
op = block.append_op(
type=self.op_type,
inputs=inputs,
outputs=outputs,
attrs=copy(self.attrs) if hasattr(self, "attrs") else {},
)
# infer variable type and infer shape in compile-time
op.desc.infer_var_type(block.desc)
op.desc.infer_shape(block.desc)
return op
def _get_io_vars(self, block, numpy_inputs):
inputs = {}
for name, value in numpy_inputs.items():
if isinstance(value, list):
var_list = [
block.var(sub_name) for sub_name, sub_value in value
]
inputs[name] = var_list
else:
inputs[name] = block.var(name)
return inputs
def _get_inputs(self, block):
return self._get_io_vars(block, self.inputs)
def _get_outputs(self, block):
return self._get_io_vars(block, self.outputs)
def calc_output(self, place):
outs, _ = self._calc_output(place)
return outs
def _create_var_from_numpy(self, value):
if isinstance(value, tuple):
data = value[0]
lod = value[1]
v = paddle.to_tensor(data)
v.value().get_tensor().set_recursive_sequence_lengths(lod)
return v
else:
return paddle.to_tensor(value)
def get_sequence_batch_size_1_input(self, lod=None, shape=None):
"""Get LoD input data whose batch size is 1.
All sequence related OP unittests should call this function to contain the case of batch size = 1.
Args:
lod (list[list of int], optional): Length-based LoD, length of lod[0] should be 1. Default: [[13]].
shape (list, optional): Shape of input, shape[0] should be equals to lod[0][0]. Default: [13, 23].
Returns:
tuple (ndarray, lod) : LoD input data whose batch size is 1.
"""
if lod is None:
lod = [[13]]
if shape is None:
shape = [13, 23]
assert len(lod[0]) == 1
assert lod[0][0] == shape[0]
x = np.random.uniform(0.1, 1, shape).astype('float32')
return (x, lod)
def lod_has_single_zero(self, lod):
for i in range(len(lod) - 2):
if lod[i] != 0 and lod[i + 1] == 0 and lod[i + 2] != 0:
return True
return False
def lod_has_continuous_zero(self, lod):
for i in range(len(lod) - 3):
if (
lod[i] != 0
and lod[i + 1] == 0
and lod[i + 2] == 0
and lod[i + 3] != 0
):
return True
return False
def get_sequence_instance_size_0_input(self, lod=None, shape=None):
"""Get LoD input data whose instance size is 0.
All sequence related OP unittests should call this function to contain the case of instance size is 0.
Args:
lod (list[list of int], optional): Length-based LoD, lod[0]'s size must at least eight, lod[0] must at least two zeros at the beginning and at least two zeros at the end, the middle position of lod[0] contains a single zero and multiple zero. Default: [[0, 0, 4, 0, 3, 0, 0, 5, 0, 0]].
shape (list, optional): Shape of input, shape[0] should be equals to lod[0][0]. Default: [13, 23].
Returns:
tuple (ndarray, lod): LoD input data whose instance size is 0.
"""
if lod is None:
lod = [[0, 0, 4, 0, 3, 0, 0, 5, 0, 0]]
if shape is None:
shape = [12, 10]
assert len(lod[0]) >= 8
assert (
lod[0][0] == 0
and lod[0][1] == 0
and lod[0][-1] == 0
and lod[0][-2] == 0
)
assert self.lod_has_single_zero(lod[0]) is True
assert self.lod_has_continuous_zero(lod[0]) is True
assert sum(lod[0]) == shape[0]
x = np.random.uniform(0.1, 1, shape).astype('float32')
return (x, lod)
def append_input_output_for_dygraph(
self, op_proto, np_list, is_input, if_return_inputs_grad_dict, block
):
def create_var(
np_value,
name,
is_input,
if_return_inputs_grad_dict,
is_calc_ref=False,
):
np_value_temp = np_value
has_lod = False
lod_temp = None
if isinstance(np_value, tuple):
np_value_temp = np_value[0]
has_lod = True
lod_temp = np_value[1]
if is_input:
if self.is_calc_ref and np_value_temp.dtype == np.float16:
v = self._create_var_from_numpy(
np_value_temp.astype(np.float32)
)
else:
v = self._create_var_from_numpy(np_value_temp)
if if_return_inputs_grad_dict:
v.stop_gradient = False
v.retain_grads()
if has_lod:
v.value().get_tensor().set_recursive_sequence_lengths(
lod_temp
)
else: