-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathfunction_testing.py
2810 lines (2561 loc) · 94.2 KB
/
function_testing.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
# global
import copy
import time
from typing import Union, List, Optional
import numpy as np
import types
import importlib
import inspect
from collections import OrderedDict
from .globals import mod_backend
try:
import tensorflow as tf
except ImportError:
tf = types.SimpleNamespace()
tf.TensorShape = None
# local
from .pipeline_helper import BackendHandler, BackendHandlerMode, get_frontend_config
import ivy
from ivy_tests.test_ivy.helpers.test_parameter_flags import FunctionTestFlags
import ivy_tests.test_ivy.helpers.test_parameter_flags as pf
import ivy_tests.test_ivy.helpers.globals as t_globals
from ivy.functional.ivy.data_type import _get_function_list, _get_functions_from_string
from ivy_tests.test_ivy.test_frontends import NativeClass
from ivy_tests.test_ivy.helpers.structs import FrontendMethodData
from ivy_tests.test_ivy.helpers.testing_helpers import _create_transpile_report
from .assertions import (
value_test,
assert_same_type,
check_unsupported_dtype,
)
# Temporary (.so) configuration
def traced_if_required(
backend: str, fn, test_trace=False, test_trace_each=False, args=None, kwargs=None
):
with BackendHandler.update_backend(backend) as ivy_backend:
try:
if test_trace:
if (
t_globals.CURRENT_RUNNING_TEST.fn_name
in t_globals.CURRENT_TRACED_DATA
and backend
not in t_globals.CURRENT_TRACED_DATA[
t_globals.CURRENT_RUNNING_TEST.fn_name
]
):
t_globals.CURRENT_TRACED_DATA[
t_globals.CURRENT_RUNNING_TEST.fn_name
][backend] = ivy_backend.trace_graph(
fn, args=args, kwargs=kwargs, backend_compile=True
)
elif (
t_globals.CURRENT_RUNNING_TEST.fn_name
not in t_globals.CURRENT_TRACED_DATA
):
t_globals.CURRENT_TRACED_DATA[
t_globals.CURRENT_RUNNING_TEST.fn_name
] = {}
t_globals.CURRENT_TRACED_DATA[
t_globals.CURRENT_RUNNING_TEST.fn_name
][backend] = ivy_backend.trace_graph(
fn, args=args, kwargs=kwargs, backend_compile=True
)
fn = t_globals.CURRENT_TRACED_DATA[
t_globals.CURRENT_RUNNING_TEST.fn_name
][backend]
if test_trace_each:
fn = ivy_backend.trace_graph(
fn, args=args, kwargs=kwargs, backend_compile=True
)
except Exception:
import logging
logging.warning("API key is invalid, test_trace is skipped.")
return fn
# Ivy Function testing ##########################
# Test Function Helpers ###############
def _find_instance_in_args(backend: str, args, array_indices, mask):
"""Find the first element in the arguments that is considered to be an
instance of Array or Container class.
Parameters
----------
args
Arguments to iterate over
array_indices
Indices of arrays that exists in the args
mask
Boolean mask for whether the corresponding element in (args) has a
generated test_flags.native_array as False or test_flags.container as
true
Returns
-------
First found instance in the arguments and the updates arguments not
including the instance
"""
i = 0
for i, a in enumerate(mask):
if a:
break
instance_idx = array_indices[i]
with BackendHandler.update_backend(backend) as ivy_backend:
instance = ivy_backend.index_nest(args, instance_idx)
new_args = ivy_backend.copy_nest(args, to_mutable=False)
ivy_backend.prune_nest_at_index(new_args, instance_idx)
return instance, new_args
def _get_frontend_submodules(fn_tree: str, gt_fn_tree: str):
split_index = fn_tree.rfind(".")
frontend_submods, fn_name = fn_tree[:split_index], fn_tree[split_index + 1 :]
# if gt_fn_tree and gt_fn_name are different from our frontend structure
if gt_fn_tree is not None:
split_index = gt_fn_tree.rfind(".")
gt_frontend_submods, gt_fn_name = (
gt_fn_tree[:split_index],
gt_fn_tree[split_index + 1 :],
)
else:
gt_frontend_submods, gt_fn_name = fn_tree[25 : fn_tree.rfind(".")], fn_name
return frontend_submods, fn_name, gt_frontend_submods, gt_fn_name
def test_function_backend_computation(
fw, test_flags, all_as_kwargs_np, input_dtypes, on_device, fn_name
):
# split the arguments into their positional and keyword components
args_np, kwargs_np = kwargs_to_args_n_kwargs(
num_positional_args=test_flags.num_positional_args, kwargs=all_as_kwargs_np
)
# Extract all arrays from the arguments and keyword arguments
arg_np_arrays, arrays_args_indices, n_args_arrays = _get_nested_np_arrays(args_np)
kwarg_np_arrays, arrays_kwargs_indices, n_kwargs_arrays = _get_nested_np_arrays(
kwargs_np
)
# Make all array-specific test flags and dtypes equal in length
total_num_arrays = n_args_arrays + n_kwargs_arrays
if len(input_dtypes) < total_num_arrays:
input_dtypes = [input_dtypes[0] for _ in range(total_num_arrays)]
if len(test_flags.as_variable) < total_num_arrays:
test_flags.as_variable = [
test_flags.as_variable[0] for _ in range(total_num_arrays)
]
if len(test_flags.native_arrays) < total_num_arrays:
test_flags.native_arrays = [
test_flags.native_arrays[0] for _ in range(total_num_arrays)
]
if len(test_flags.container) < total_num_arrays:
test_flags.container = [
test_flags.container[0] for _ in range(total_num_arrays)
]
if test_flags.test_cython_wrapper:
ivy.set_cython_wrappers_mode(True)
else:
ivy.set_cython_wrappers_mode(False)
with BackendHandler.update_backend(fw) as ivy_backend:
# Update variable flags to be compatible with float dtype and with_out args
test_flags.as_variable = [
v if ivy_backend.is_float_dtype(d) and not test_flags.with_out else False
for v, d in zip(test_flags.as_variable, input_dtypes)
]
# update instance_method flag to only be considered if the
# first term is either an ivy.Array or ivy.Container
instance_method = test_flags.instance_method and (
not test_flags.native_arrays[0] or test_flags.container[0]
)
args, kwargs = create_args_kwargs(
backend=fw,
args_np=args_np,
arg_np_vals=arg_np_arrays,
args_idxs=arrays_args_indices,
kwargs_np=kwargs_np,
kwarg_np_vals=kwarg_np_arrays,
kwargs_idxs=arrays_kwargs_indices,
input_dtypes=input_dtypes,
test_flags=test_flags,
on_device=on_device,
)
# If function doesn't have an out argument but an out argument is given
# or a test with out flag is True
if ("out" in kwargs or test_flags.with_out) and "out" not in inspect.signature(
getattr(ivy, fn_name)
).parameters:
raise RuntimeError(f"Function {fn_name} does not have an out parameter")
# Run either as an instance method or from the API directly
with BackendHandler.update_backend(fw) as ivy_backend:
instance = None
if instance_method:
array_or_container_mask = [
(not native_flag) or container_flag
for native_flag, container_flag in zip(
test_flags.native_arrays, test_flags.container
)
]
# Boolean mask for args and kwargs True if an entry's
# test Array flag is True or test Container flag is true
args_instance_mask = array_or_container_mask[
: test_flags.num_positional_args
]
kwargs_instance_mask = array_or_container_mask[
test_flags.num_positional_args :
]
if any(args_instance_mask):
instance, args = _find_instance_in_args(
fw, args, arrays_args_indices, args_instance_mask
)
else:
instance, kwargs = _find_instance_in_args(
fw, kwargs, arrays_kwargs_indices, kwargs_instance_mask
)
if test_flags.test_trace or test_flags.test_trace_each:
def target_fn(instance, *args, **kwargs):
return instance.__getattribute__(fn_name)(*args, **kwargs)
args = [instance, *args]
else:
target_fn = instance.__getattribute__(fn_name)
else:
target_fn = ivy_backend.__dict__[fn_name]
# Make copy of arguments for functions that might use inplace update by default
copy_kwargs = copy.deepcopy(kwargs)
copy_args = copy.deepcopy(args)
ret_from_target, ret_np_flat_from_target = get_ret_and_flattened_np_array(
fw,
target_fn,
*copy_args,
test_trace=test_flags.test_trace,
test_trace_each=test_flags.test_trace_each,
precision_mode=test_flags.precision_mode,
**copy_kwargs,
)
assert ivy_backend.nested_map(
lambda x: ivy_backend.is_ivy_array(x) if ivy_backend.is_array(x) else True,
ret_from_target,
), f"Ivy function returned non-ivy arrays: {ret_from_target}"
# Assert indices of return if the indices of the out array provided
if test_flags.with_out and not (
test_flags.test_trace or test_flags.test_trace_each
):
test_ret = (
ret_from_target[getattr(ivy_backend.__dict__[fn_name], "out_index")]
if hasattr(ivy_backend.__dict__[fn_name], "out_index")
else ret_from_target
)
out = ivy_backend.nested_map(
ivy_backend.zeros_like, test_ret, to_mutable=True, include_derived=True
)
if instance_method:
(
ret_from_target,
ret_np_flat_from_target,
) = get_ret_and_flattened_np_array(
fw,
instance.__getattribute__(fn_name),
*args,
**kwargs,
out=out,
precision_mode=test_flags.precision_mode,
)
else:
(
ret_from_target,
ret_np_flat_from_target,
) = get_ret_and_flattened_np_array(
fw,
ivy_backend.__dict__[fn_name],
*args,
**kwargs,
out=out,
precision_mode=test_flags.precision_mode,
)
test_ret = (
ret_from_target[getattr(ivy_backend.__dict__[fn_name], "out_index")]
if hasattr(ivy_backend.__dict__[fn_name], "out_index")
else ret_from_target
)
assert not ivy_backend.nested_any(
ivy_backend.nested_multi_map(
lambda x, _: x[0] is x[1], [test_ret, out]
),
lambda x: not x,
), "the array in out argument does not contain same value as the returned"
if not max(test_flags.container) and ivy_backend.native_inplace_support:
# these backends do not always support native inplace updates
assert not ivy_backend.nested_any(
ivy_backend.nested_multi_map(
lambda x, _: x[0].data is x[1].data, [test_ret, out]
),
lambda x: not x,
), (
"the array in out argument does not contain same value as the"
" returned"
)
if test_flags.with_copy:
array_fn = ivy_backend.is_array
if "copy" in list(inspect.signature(target_fn).parameters.keys()):
kwargs["copy"] = True
if instance_method:
first_array = instance
else:
first_array = ivy_backend.func_wrapper._get_first_array(
*args, array_fn=array_fn, **kwargs
)
ret_, ret_np_flat_ = get_ret_and_flattened_np_array(
fw,
target_fn,
*args,
test_trace=test_flags.test_trace,
test_trace_each=test_flags.test_trace_each,
precision_mode=test_flags.precision_mode,
**kwargs,
)
first_array = ivy_backend.stop_gradient(first_array).to_numpy()
ret_ = ivy_backend.stop_gradient(ret_).to_numpy()
assert not np.may_share_memory(first_array, ret_)
ret_device = None
if isinstance(ret_from_target, ivy_backend.Array): # TODO use str for now
ret_device = ivy_backend.dev(ret_from_target)
return (
ret_from_target,
ret_np_flat_from_target,
ret_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
test_flags,
input_dtypes,
)
def test_function_ground_truth_computation(
ground_truth_backend,
on_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
input_dtypes,
test_flags,
fn_name,
):
with BackendHandler.update_backend(ground_truth_backend) as gt_backend:
gt_backend.set_default_device(on_device) # TODO remove
args, kwargs = create_args_kwargs(
backend=test_flags.ground_truth_backend,
args_np=args_np,
arg_np_vals=arg_np_arrays,
args_idxs=arrays_args_indices,
kwargs_np=kwargs_np,
kwargs_idxs=arrays_kwargs_indices,
kwarg_np_vals=kwarg_np_arrays,
input_dtypes=input_dtypes,
test_flags=test_flags,
on_device=on_device,
)
ret_from_gt, ret_np_from_gt_flat = get_ret_and_flattened_np_array(
test_flags.ground_truth_backend,
gt_backend.__dict__[fn_name],
*args,
test_trace=test_flags.test_trace,
test_trace_each=test_flags.test_trace_each,
precision_mode=test_flags.precision_mode,
**kwargs,
)
assert gt_backend.nested_map(
lambda x: gt_backend.is_ivy_array(x) if gt_backend.is_array(x) else True,
ret_from_gt,
), f"Ground-truth function returned non-ivy arrays: {ret_from_gt}"
if test_flags.with_out and not (
test_flags.test_trace or test_flags.test_trace_each
):
test_ret_from_gt = (
ret_from_gt[getattr(gt_backend.__dict__[fn_name], "out_index")]
if hasattr(gt_backend.__dict__[fn_name], "out_index")
else ret_from_gt
)
out_from_gt = gt_backend.nested_map(
gt_backend.zeros_like,
test_ret_from_gt,
to_mutable=True,
include_derived=True,
)
ret_from_gt, ret_np_from_gt_flat = get_ret_and_flattened_np_array(
test_flags.ground_truth_backend,
gt_backend.__dict__[fn_name],
*args,
test_trace=test_flags.test_trace,
test_trace_each=test_flags.test_trace_each,
precision_mode=test_flags.precision_mode,
**kwargs,
out=out_from_gt,
)
# TODO enable
fw_list = gradient_unsupported_dtypes(fn=gt_backend.__dict__[fn_name])
ret_from_gt_device = None
if isinstance(ret_from_gt, gt_backend.Array): # TODO use str for now
ret_from_gt_device = gt_backend.dev(ret_from_gt)
return (ret_from_gt, ret_np_from_gt_flat, ret_from_gt_device, test_flags, fw_list)
def test_function(
*,
input_dtypes: Union[ivy.Dtype, List[ivy.Dtype]],
test_flags: FunctionTestFlags,
fn_name: str,
rtol_: Optional[float] = None,
atol_: float = 1e-06,
tolerance_dict: Optional[dict] = None,
test_values: bool = True,
xs_grad_idxs=None,
ret_grad_idxs=None,
backend_to_test: str,
on_device: str,
return_flat_np_arrays: bool = False,
**all_as_kwargs_np,
):
"""Test a function that consumes (or returns) arrays for the current
backend by comparing the result with numpy.
Parameters
----------
input_dtypes
data types of the input arguments in order.
test_flags
FunctionTestFlags object that stores all testing flags, including:
num_positional_args, with_out, instance_method, as_variable,
native_arrays, container, gradient
fw
current backend (framework).
fn_name
name of the function to test.
rtol_
relative tolerance value.
atol_
absolute tolerance value.
test_values
if True, test for the correctness of the resulting values.
xs_grad_idxs
Indices of the input arrays to compute gradients with respect to. If None,
gradients are returned with respect to all input arrays. (Default value = None)
ret_grad_idxs
Indices of the returned arrays for which to return computed gradients. If None,
gradients are returned for all returned arrays. (Default value = None)
on_device
The device on which to create arrays
return_flat_np_arrays
If test_values is False, this flag dictates whether the original returns are
returned, or whether the flattened numpy arrays are returned.
all_as_kwargs_np
input arguments to the function as keyword arguments.
Returns
-------
ret
optional, return value from the function
ret_gt
optional, return value from the Ground Truth function
Examples
--------
>>> input_dtypes = 'float64'
>>> as_variable_flags = False
>>> with_out = False
>>> num_positional_args = 0
>>> native_array_flags = False
>>> container_flags = False
>>> instance_method = False
>>> test_flags = FunctionTestFlags(num_positional_args, with_out,
instance_method,
as_variable,
native_arrays,
container_flags,
none)
>>> fw = "torch"
>>> fn_name = "abs"
>>> x = np.array([-1])
>>> test_function(input_dtypes, test_flags, fw, fn_name, x=x)
>>> input_dtypes = ['float64', 'float32']
>>> as_variable_flags = [False, True]
>>> with_out = False
>>> num_positional_args = 1
>>> native_array_flags = [True, False]
>>> container_flags = [False, False]
>>> instance_method = False
>>> test_flags = FunctionTestFlags(num_positional_args, with_out,
instance_method,
as_variable,
native_arrays,
container_flags,
none)
>>> fw = "numpy"
>>> fn_name = "add"
>>> x1 = np.array([1, 3, 4])
>>> x2 = np.array([-3, 15, 24])
>>> test_function(input_dtypes, test_flags, fw, fn_name, x1=x1, x2=x2)
"""
_switch_backend_context(
test_flags.test_trace or test_flags.test_trace_each or test_flags.transpile
)
ground_truth_backend = test_flags.ground_truth_backend
if test_flags.container[0]:
test_flags.with_copy = False
if test_flags.with_copy is True:
test_flags.with_out = False
if mod_backend[backend_to_test]:
# multiprocessing
proc, input_queue, output_queue = mod_backend[backend_to_test]
input_queue.put(
(
"function_backend_computation",
backend_to_test,
test_flags,
all_as_kwargs_np,
input_dtypes,
on_device,
fn_name,
)
)
(
ret_from_target,
ret_np_flat_from_target,
ret_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
test_flags,
input_dtypes,
) = output_queue.get()
else:
(
ret_from_target,
ret_np_flat_from_target,
ret_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
test_flags,
input_dtypes,
) = test_function_backend_computation(
backend_to_test,
test_flags,
all_as_kwargs_np,
input_dtypes,
on_device,
fn_name,
)
# compute the return with a Ground Truth backend
if mod_backend[ground_truth_backend]:
proc, input_queue, output_queue = mod_backend[ground_truth_backend]
input_queue.put(
(
"function_ground_truth_computation",
ground_truth_backend,
on_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
input_dtypes,
test_flags,
fn_name,
)
)
(
ret_from_gt,
ret_np_from_gt_flat,
ret_from_gt_device,
test_flags,
fw_list,
) = output_queue.get()
else:
(
ret_from_gt,
ret_np_from_gt_flat,
ret_from_gt_device,
test_flags,
fw_list,
) = test_function_ground_truth_computation(
ground_truth_backend,
on_device,
args_np,
arg_np_arrays,
arrays_args_indices,
kwargs_np,
arrays_kwargs_indices,
kwarg_np_arrays,
input_dtypes,
test_flags,
fn_name,
)
if test_flags.transpile:
if mod_backend[backend_to_test]:
proc, input_queue, output_queue = mod_backend[backend_to_test]
input_queue.put(
(
"transpile_if_required_backend",
backend_to_test,
fn_name,
args_np,
kwargs_np,
)
)
else:
_transpile_if_required_backend(
backend_to_test, fn_name, args=args_np, kwargs=kwargs_np
)
# Gradient test
# TODO enable back , ADD backend_to_test to the call below
if (
test_flags.test_gradients
and not test_flags.instance_method
and "bool" not in input_dtypes
and not any(d in ["complex64", "complex128"] for d in input_dtypes)
):
if backend_to_test not in fw_list or not ivy.nested_argwhere(
all_as_kwargs_np,
lambda x: (
x.dtype in fw_list[backend_to_test]
if isinstance(x, np.ndarray)
else None
),
):
gradient_test(
fn=fn_name,
all_as_kwargs_np=all_as_kwargs_np,
args_np=args_np,
kwargs_np=kwargs_np,
input_dtypes=input_dtypes,
test_flags=test_flags,
rtol_=rtol_,
atol_=atol_,
xs_grad_idxs=xs_grad_idxs,
ret_grad_idxs=ret_grad_idxs,
ground_truth_backend=ground_truth_backend,
backend_to_test=backend_to_test,
on_device=on_device,
)
# assuming value test will be handled manually in the test function
if not test_values:
if return_flat_np_arrays:
return ret_np_flat_from_target, ret_np_from_gt_flat
return ret_from_target, ret_from_gt
if isinstance(rtol_, dict):
rtol_ = _get_framework_rtol(rtol_, backend_to_test)
if isinstance(atol_, dict):
atol_ = _get_framework_atol(atol_, backend_to_test)
# value test
value_test(
ret_np_flat=ret_np_flat_from_target,
ret_np_from_gt_flat=ret_np_from_gt_flat,
rtol=rtol_,
atol=atol_,
specific_tolerance_dict=tolerance_dict,
backend=backend_to_test,
ground_truth_backend=test_flags.ground_truth_backend,
)
if not (test_flags.test_trace or test_flags.test_trace_each):
assert_same_type(
ret_from_target,
ret_from_gt,
backend_to_test,
test_flags.ground_truth_backend,
)
assert ret_device == ret_from_gt_device, (
f"ground truth backend ({test_flags.ground_truth_backend}) returned array on"
f" device {ret_from_gt_device} but target backend ({backend_to_test})"
f" returned array on device {ret_device}"
)
if ret_device is not None:
assert ret_device == on_device, (
f"device is set to {on_device}, but ground truth produced array on"
f" {ret_device}"
)
def _assert_frontend_ret(ret, for_fn=True):
fn_or_method = "function" if for_fn else "method"
if not inspect.isclass(ret):
is_ret_tuple = issubclass(ret.__class__, tuple)
else:
is_ret_tuple = issubclass(ret, tuple)
if is_ret_tuple:
non_frontend_idxs = ivy.nested_argwhere(
ret, lambda _x: not _is_frontend_array(_x) if ivy.is_array(_x) else False
)
assert not non_frontend_idxs, (
f"Frontend {fn_or_method} return contains non-frontend arrays at positions"
f" {non_frontend_idxs} (zero-based):"
f" {ivy.multi_index_nest(ret, non_frontend_idxs)}"
)
elif ivy.is_array(ret):
assert _is_frontend_array(
ret
), f"Frontend {fn_or_method} returned non-frontend array: {ret}"
def _transpile_if_required_backend(backend: str, fn_name: str, args=None, kwargs=None):
iterations = 1
with BackendHandler.update_backend(backend) as ivy_backend:
args, kwargs = ivy_backend.args_to_ivy(*args, **kwargs)
backend_fn = ivy.__dict__[fn_name]
backend_traced_fn = traced_if_required(
backend, backend_fn, test_trace_each=True, args=args, kwargs=kwargs
)
func_timings = []
for i in range(0, iterations):
# timing the traced_fn
start = time.time()
backend_traced_fn(*args, **kwargs)
end = time.time()
func_timings.append(end - start)
func_time = np.mean(func_timings).item()
backend_nodes = len(backend_traced_fn._functions)
data = {
"fn_name": fn_name,
"args": str(args),
"kwargs": str(kwargs),
"time": func_time,
"nodes": backend_nodes,
}
_create_transpile_report(data, backend, "report.json", True)
def test_frontend_function(
*,
input_dtypes: Union[ivy.Dtype, List[ivy.Dtype]],
test_flags: pf.frontend_function_flags,
backend_to_test: str,
on_device="cpu",
frontend: str,
fn_tree: str,
gt_fn_tree: Optional[str] = None,
rtol: Optional[float] = None,
atol: float = 1e-06,
tolerance_dict: Optional[dict] = None,
test_values: bool = True,
**all_as_kwargs_np,
):
"""Test a frontend function for the current backend by comparing the result
with the function in the associated framework.
Parameters
----------
input_dtypes
data types of the input arguments in order.
test_flags
FunctionTestFlags object that stores all testing flags, including:
num_positional_args, with_out, instance_method, as_variable,
native_arrays, container, gradient, precision_mode
frontend
current frontend (framework).
fn_tree
Path to function in frontend framework namespace.
gt_fn_tree
Path to function in ground truth framework namespace.
rtol
relative tolerance value.
atol
absolute tolerance value.
tolerance_dict
dictionary of tolerance values for specific dtypes.
test_values
if True, test for the correctness of the resulting values.
all_as_kwargs_np
input arguments to the function as keyword arguments.
If an input argument has the same name as any other parameter
of this function, add "arg_" before the argument name.
Returns
-------
ret
optional, return value from the function
ret_np
optional, return value from the Numpy function
"""
# ToDo add with_backend refactor in GC
_switch_backend_context(
test_flags.test_trace or test_flags.test_trace_each or test_flags.transpile
)
assert (
not test_flags.with_out or not test_flags.inplace
), "only one of with_out or with_inplace can be set as True"
if test_flags.with_copy is True:
test_flags.with_out = False
test_flags.inplace = False
if test_flags.test_trace or test_flags.test_trace_each:
test_flags.with_out = test_flags.inplace = False
all_as_kwargs_np = {
k[4:] if k.startswith("arg_") else k: v for k, v in all_as_kwargs_np.items()
}
# split the arguments into their positional and keyword components
args_np, kwargs_np = kwargs_to_args_n_kwargs(
num_positional_args=test_flags.num_positional_args, kwargs=all_as_kwargs_np
)
# extract all arrays from the arguments and keyword arguments
arg_np_vals, args_idxs, c_arg_vals = _get_nested_np_arrays(args_np)
kwarg_np_vals, kwargs_idxs, c_kwarg_vals = _get_nested_np_arrays(kwargs_np)
# make all lists equal in length
num_arrays = c_arg_vals + c_kwarg_vals
if len(input_dtypes) < num_arrays:
input_dtypes = [input_dtypes[0] for _ in range(num_arrays)]
if len(test_flags.as_variable) < num_arrays:
test_flags.as_variable = [test_flags.as_variable[0] for _ in range(num_arrays)]
if len(test_flags.native_arrays) < num_arrays:
test_flags.native_arrays = [
test_flags.native_arrays[0] for _ in range(num_arrays)
]
with BackendHandler.update_backend(backend_to_test) as ivy_backend:
# update var flags to be compatible with float dtype and with_out args
test_flags.as_variable = [
v if ivy_backend.is_float_dtype(d) and not test_flags.with_out else False
for v, d in zip(test_flags.as_variable, input_dtypes)
]
local_importer = ivy_backend.utils.dynamic_import
# strip the decorator to get an Ivy array
# TODO, fix testing for jax frontend for x32
if frontend == "jax":
local_importer.import_module("ivy.functional.frontends.jax").config.update(
"jax_enable_x64", True
)
(
frontend_submods,
fn_name,
gt_frontend_submods,
gt_fn_name,
) = _get_frontend_submodules(fn_tree, gt_fn_tree)
function_module = local_importer.import_module(frontend_submods)
frontend_fn = getattr(function_module, fn_name)
# apply test flags etc.
args, kwargs = create_args_kwargs(
backend=backend_to_test,
args_np=args_np,
arg_np_vals=arg_np_vals,
args_idxs=args_idxs,
kwargs_np=kwargs_np,
kwarg_np_vals=kwarg_np_vals,
kwargs_idxs=kwargs_idxs,
input_dtypes=input_dtypes,
test_flags=test_flags,
on_device=on_device,
)
# Make copy for arguments for functions that might use
# inplace update by default
copy_kwargs = copy.deepcopy(kwargs)
copy_args = copy.deepcopy(args)
# Frontend array generation
create_frontend_array = local_importer.import_module(
f"ivy.functional.frontends.{frontend}"
)._frontend_array
if test_flags.generate_frontend_arrays:
args_for_test, kwargs_for_test = args_to_frontend(
backend_to_test,
*args,
frontend_array_fn=create_frontend_array,
**kwargs,
)
copy_args, copy_kwargs = args_to_frontend(
backend_to_test,
*args,
frontend_array_fn=create_frontend_array,
**kwargs,
)
else:
args_for_test = copy.deepcopy(args)
kwargs_for_test = copy.deepcopy(kwargs)
ret = get_frontend_ret(
backend_to_test,
frontend_fn,
*args_for_test,
test_trace=test_flags.test_trace,
test_trace_each=test_flags.test_trace_each,
frontend_array_function=(
create_frontend_array
if test_flags.test_trace or test_flags.test_trace_each
else None
),
precision_mode=test_flags.precision_mode,
**kwargs_for_test,
)
# test if return is frontend
_assert_frontend_ret(ret)
if test_flags.with_out and "out" in list(
inspect.signature(frontend_fn).parameters.keys()
):
if not inspect.isclass(ret):
is_ret_tuple = issubclass(ret.__class__, tuple)
else:
is_ret_tuple = issubclass(ret, tuple)
out = ret
if is_ret_tuple:
flatten_ret = flatten_frontend(
ret=ret,
backend=backend_to_test,
frontend_array_fn=create_frontend_array,
)
flatten_out = flatten_frontend(
ret=out,
backend=backend_to_test,
frontend_array_fn=create_frontend_array,
)
for ret_array, out_array in zip(flatten_ret, flatten_out):
if ivy_backend.native_inplace_support and not any(
(ivy_backend.isscalar(ret), ivy_backend.isscalar(out))
):
assert ret_array.ivy_array.data is out_array.ivy_array.data
assert ret_array is out_array
else:
if ivy_backend.native_inplace_support and not any(
(ivy_backend.isscalar(ret), ivy_backend.isscalar(out))
):
assert ret.ivy_array.data is out.ivy_array.data
assert ret is out
elif test_flags.with_copy:
assert _is_frontend_array(ret)
if "copy" in list(inspect.signature(frontend_fn).parameters.keys()):
copy_kwargs["copy"] = True
first_array = ivy_backend.func_wrapper._get_first_array(
*copy_args,
array_fn=(
_is_frontend_array
if test_flags.generate_frontend_arrays
else ivy_backend.is_array
),