/
_helper.py
1526 lines (1247 loc) · 56.5 KB
/
_helper.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
import contextlib
import functools
import inspect
import os
import random
import traceback
import unittest
from unittest import mock
import warnings
import numpy
import cupy
from cupy._core import internal
from cupy.testing import _array
from cupy.testing import _parameterized
import cupyx
import cupyx.scipy.sparse
try:
import pytest
import _pytest.outcomes
except ImportError:
_is_pytest_available = False
_skip_classes = unittest.SkipTest,
_skipif = unittest.skipIf
else:
_is_pytest_available = True
_skip_classes = unittest.SkipTest, _pytest.outcomes.Skipped
_skipif = pytest.mark.skipif
def _format_exception(exc):
if exc is None:
return None
# TODO(kataoka): Use traceback.format_exception(exc) in Python 3.10
return ''.join(traceback.TracebackException.from_exception(exc).format())
def _call_func(self, impl, args, kw):
# Note that `_pytest.outcomes.Skipped` is derived from BaseException.
exceptions = Exception,
if _is_pytest_available:
exceptions += _pytest.outcomes.Skipped,
try:
result = impl(self, *args, **kw)
error = None
except exceptions as e:
tb = e.__traceback__
if tb.tb_next is None:
# failed before impl is called, e.g. invalid kw
raise e
result = None
error = e
return result, error
def _call_func_cupy(self, impl, args, kw, name, sp_name, scipy_name):
assert isinstance(name, str)
assert sp_name is None or isinstance(sp_name, str)
assert scipy_name is None or isinstance(scipy_name, str)
kw = kw.copy()
# Run cupy
if sp_name:
kw[sp_name] = cupyx.scipy.sparse
if scipy_name:
kw[scipy_name] = cupyx.scipy
kw[name] = cupy
result, error = _call_func(self, impl, args, kw)
return result, error
def _call_func_numpy(self, impl, args, kw, name, sp_name, scipy_name):
assert isinstance(name, str)
assert sp_name is None or isinstance(sp_name, str)
assert scipy_name is None or isinstance(scipy_name, str)
kw = kw.copy()
# Run numpy
kw[name] = numpy
if sp_name:
import scipy.sparse
kw[sp_name] = scipy.sparse
if scipy_name:
import scipy
kw[scipy_name] = scipy
result, error = _call_func(self, impl, args, kw)
return result, error
def _call_func_numpy_cupy(self, impl, args, kw, name, sp_name, scipy_name):
# Run cupy
cupy_result, cupy_error = _call_func_cupy(
self, impl, args, kw, name, sp_name, scipy_name)
# Run numpy
numpy_result, numpy_error = _call_func_numpy(
self, impl, args, kw, name, sp_name, scipy_name)
return (
cupy_result, cupy_error,
numpy_result, numpy_error)
_numpy_errors = [
AttributeError, Exception, IndexError, TypeError, ValueError,
NotImplementedError, DeprecationWarning,
numpy.AxisError, numpy.linalg.LinAlgError,
]
def _check_numpy_cupy_error_compatible(cupy_error, numpy_error):
"""Checks if try/except blocks are equivalent up to public error classes
"""
return all(isinstance(cupy_error, err) == isinstance(numpy_error, err)
for err in _numpy_errors)
def _fail_test_with_unexpected_errors(
tb, msg_format, cupy_error, numpy_error):
# Fails the test due to unexpected errors raised from the test.
# msg_format may include format placeholders:
# '{cupy_error}' '{numpy_error}'
msg = msg_format.format(
cupy_error=_format_exception(cupy_error),
numpy_error=_format_exception(numpy_error))
# Fail the test with the traceback of the error (for pytest --pdb)
raise AssertionError(msg).with_traceback(tb)
def _check_cupy_numpy_error(cupy_error, numpy_error,
accept_error=False):
# Skip the test if both raised SkipTest.
if (isinstance(cupy_error, _skip_classes)
and isinstance(numpy_error, _skip_classes)):
if cupy_error.__class__ is not numpy_error.__class__:
raise AssertionError(
'Both numpy and cupy were skipped but with different '
'exceptions.')
if cupy_error.args != numpy_error.args:
raise AssertionError(
'Both numpy and cupy were skipped but with different causes.')
raise numpy_error # reraise SkipTest
# Check if the error was not raised from test code.
if os.environ.get('CUPY_CI', '') != '' and cupy_error is not None:
frame = traceback.extract_tb(cupy_error.__traceback__)[-1]
filename = os.path.basename(frame.filename)
if filename == 'test_helper.py':
# Allows errors from the test code for testing helpers.
pass
elif filename.startswith('test_'):
_fail_test_with_unexpected_errors(
cupy_error.__traceback__,
'Error was raised from test code.\n\n{cupy_error}',
cupy_error, None)
# For backward compatibility
if accept_error is True:
accept_error = Exception
elif not accept_error:
accept_error = ()
# TODO(oktua): expected_regexp like numpy.testing.assert_raises_regex
if cupy_error is None and numpy_error is None:
raise AssertionError(
'Both cupy and numpy are expected to raise errors, but not')
elif cupy_error is None:
_fail_test_with_unexpected_errors(
numpy_error.__traceback__,
'Only numpy raises error\n\n{numpy_error}',
None, numpy_error)
elif numpy_error is None:
_fail_test_with_unexpected_errors(
cupy_error.__traceback__,
'Only cupy raises error\n\n{cupy_error}',
cupy_error, None)
elif not _check_numpy_cupy_error_compatible(cupy_error, numpy_error):
_fail_test_with_unexpected_errors(
cupy_error.__traceback__,
'''Different types of errors occurred
cupy
{cupy_error}
numpy
{numpy_error}
''',
cupy_error, numpy_error)
elif not (isinstance(cupy_error, accept_error)
and isinstance(numpy_error, accept_error)):
_fail_test_with_unexpected_errors(
cupy_error.__traceback__,
'''Both cupy and numpy raise exceptions
cupy
{cupy_error}
numpy
{numpy_error}
''',
cupy_error, numpy_error)
def _signed_counterpart(dtype):
return numpy.dtype(numpy.dtype(dtype).char.lower()).type
def _make_positive_mask(self, impl, args, kw, name, sp_name, scipy_name):
# Returns a mask of output arrays that indicates valid elements for
# comparison. See the comment at the caller.
ks = [k for k, v in kw.items() if v in _unsigned_dtypes]
for k in ks:
kw[k] = _signed_counterpart(kw[k])
result, error = _call_func_cupy(
self, impl, args, kw, name, sp_name, scipy_name)
assert error is None
return cupy.asnumpy(result) >= 0
def _contains_signed_and_unsigned(kw):
vs = set(kw.values())
return any(d in vs for d in _unsigned_dtypes) and \
any(d in vs for d in _float_dtypes + _signed_dtypes)
def _wraps_partial(wrapped, *names):
# Only `wrapped` function have args of `names`.
def decorator(impl):
impl = functools.wraps(wrapped)(impl)
impl.__signature__ = inspect.signature(
functools.partial(wrapped, **{name: None for name in names}))
return impl
return decorator
def _wraps_partial_xp(wrapped, name, sp_name, scipy_name):
names = [name, sp_name, scipy_name]
names = [n for n in names if n is not None]
return _wraps_partial(wrapped, *names)
def _make_decorator(check_func, name, type_check, contiguous_check,
accept_error, sp_name=None, scipy_name=None,
check_sparse_format=True):
assert isinstance(name, str)
assert sp_name is None or isinstance(sp_name, str)
assert scipy_name is None or isinstance(scipy_name, str)
def decorator(impl):
@_wraps_partial_xp(impl, name, sp_name, scipy_name)
def test_func(self, *args, **kw):
# Run cupy and numpy
(
cupy_result, cupy_error,
numpy_result, numpy_error) = (
_call_func_numpy_cupy(
self, impl, args, kw, name, sp_name, scipy_name))
assert cupy_result is not None or cupy_error is not None
assert numpy_result is not None or numpy_error is not None
# Check errors raised
if cupy_error or numpy_error:
_check_cupy_numpy_error(cupy_error,
numpy_error,
accept_error=accept_error)
return
# Check returned arrays
if not isinstance(cupy_result, (tuple, list)):
cupy_result = cupy_result,
if not isinstance(numpy_result, (tuple, list)):
numpy_result = numpy_result,
assert len(cupy_result) == len(numpy_result)
# Check types
cupy_numpy_result_ndarrays = [
_convert_output_to_ndarray(
cupy_r, numpy_r, sp_name, check_sparse_format)
for cupy_r, numpy_r in zip(cupy_result, numpy_result)]
# Check dtypes
if type_check:
for cupy_r, numpy_r in cupy_numpy_result_ndarrays:
if cupy_r.dtype != numpy_r.dtype:
raise AssertionError(
'''ndarrays of different dtypes are returned.
cupy: {}
numpy: {}'''.format(cupy_r.dtype, numpy_r.dtype))
# Check contiguities
if contiguous_check:
for cupy_r, numpy_r in zip(cupy_result, numpy_result):
if isinstance(numpy_r, numpy.ndarray):
if (numpy_r.flags.c_contiguous
and not cupy_r.flags.c_contiguous):
raise AssertionError(
'The state of c_contiguous flag is false. '
'(cupy_result:{} numpy_result:{})'.format(
cupy_r.flags.c_contiguous,
numpy_r.flags.c_contiguous))
if (numpy_r.flags.f_contiguous
and not cupy_r.flags.f_contiguous):
raise AssertionError(
'The state of f_contiguous flag is false. '
'(cupy_result:{} numpy_result:{})'.format(
cupy_r.flags.f_contiguous,
numpy_r.flags.f_contiguous))
# Check shapes
for cupy_r, numpy_r in cupy_numpy_result_ndarrays:
assert cupy_r.shape == numpy_r.shape
# Check item values
for cupy_r, numpy_r in cupy_numpy_result_ndarrays:
# Behavior of assigning a negative value to an unsigned integer
# variable is undefined.
# nVidia GPUs and Intel CPUs behave differently.
# To avoid this difference, we need to ignore dimensions whose
# values are negative.
skip = False
if (_contains_signed_and_unsigned(kw)
and cupy_r.dtype in _unsigned_dtypes):
mask = _make_positive_mask(
self, impl, args, kw, name, sp_name, scipy_name)
if cupy_r.shape == ():
skip = (mask == 0).all()
else:
cupy_r = cupy_r[mask].get()
numpy_r = numpy_r[mask]
if not skip:
check_func(cupy_r, numpy_r)
return test_func
return decorator
def _convert_output_to_ndarray(c_out, n_out, sp_name, check_sparse_format):
"""Checks type of cupy/numpy results and returns cupy/numpy ndarrays.
Args:
c_out (cupy.ndarray, cupyx.scipy.sparse matrix, cupy.poly1d or scalar):
cupy result
n_out (numpy.ndarray, scipy.sparse matrix, numpy.poly1d or scalar):
numpy result
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
check_sparse_format (bool): If ``True``, consistency of format of
sparse matrix is also checked. Default is ``True``.
Returns:
The tuple of cupy.ndarray and numpy.ndarray.
"""
if sp_name is not None and cupyx.scipy.sparse.issparse(c_out):
# Sparse output case.
import scipy.sparse
assert scipy.sparse.issparse(n_out)
if check_sparse_format:
assert c_out.format == n_out.format
return c_out.A, n_out.A
if (isinstance(c_out, cupy.ndarray)
and isinstance(n_out, (numpy.ndarray, numpy.generic))):
# ndarray output case.
return c_out, n_out
if isinstance(c_out, cupy.poly1d) and isinstance(n_out, numpy.poly1d):
# poly1d output case.
assert c_out.variable == n_out.variable
return c_out.coeffs, n_out.coeffs
if isinstance(c_out, numpy.generic) and isinstance(n_out, numpy.generic):
# numpy scalar output case.
return c_out, n_out
if numpy.isscalar(c_out) and numpy.isscalar(n_out):
# python scalar output case.
return cupy.array(c_out), numpy.array(n_out)
raise AssertionError(
'numpy and cupy returns different type of return value:\n'
'cupy: {}\nnumpy: {}'.format(
type(c_out), type(n_out)))
def _check_tolerance_keys(rtol, atol):
def _check(tol):
if isinstance(tol, dict):
for k in tol.keys():
if type(k) is type:
continue
if type(k) is str and k == 'default':
continue
msg = ('Keys of the tolerance dictionary need to be type '
'objects as `numpy.float32` and `cupy.float32` or '
'`\'default\'` string.')
raise TypeError(msg)
_check(rtol)
_check(atol)
def _resolve_tolerance(type_check, result, rtol, atol):
def _resolve(dtype, tol):
if isinstance(tol, dict):
tol1 = tol.get(dtype.type)
if tol1 is None:
tol1 = tol.get('default')
if tol1 is None:
raise TypeError(
'Can not find tolerance for {}'.format(dtype.type))
return tol1
else:
return tol
dtype = result.dtype
rtol1 = _resolve(dtype, rtol)
atol1 = _resolve(dtype, atol)
return rtol1, atol1
def numpy_cupy_allclose(rtol=1e-7, atol=0, err_msg='', verbose=True,
name='xp', type_check=True, accept_error=False,
sp_name=None, scipy_name=None, contiguous_check=True,
*, _check_sparse_format=True):
"""Decorator that checks NumPy results and CuPy ones are close.
Args:
rtol(float or dict): Relative tolerance. Besides a float value, a
dictionary that maps a dtypes to a float value can be supplied to
adjust tolerance per dtype. If the dictionary has ``'default'``
string as its key, its value is used as the default tolerance in
case any dtype keys do not match.
atol(float or dict): Absolute tolerance. Besides a float value, a
dictionary can be supplied as ``rtol``.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values are
appended to the error message.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
contiguous_check(bool): If ``True``, consistency of contiguity is
also checked.
Decorated test fixture is required to return the arrays whose values are
close between ``numpy`` case and ``cupy`` case.
For example, this test case checks ``numpy.zeros`` and ``cupy.zeros``
should return same value.
>>> import unittest
>>> from cupy import testing
>>> @testing.gpu
... class TestFoo(unittest.TestCase):
...
... @testing.numpy_cupy_allclose()
... def test_foo(self, xp):
... # ...
... # Prepare data with xp
... # ...
...
... xp_result = xp.zeros(10)
... return xp_result
.. seealso:: :func:`cupy.testing.assert_allclose`
"""
_check_tolerance_keys(rtol, atol)
# When `type_check` is `False`, cupy result and numpy result may have
# different dtypes so we can not determine the dtype to use from the
# tolerance associations.
if not type_check:
if isinstance(rtol, dict) or isinstance(atol, dict):
raise TypeError('When `type_check` is `False`, `rtol` and `atol` '
'must be supplied as float.')
def check_func(c, n):
rtol1, atol1 = _resolve_tolerance(type_check, c, rtol, atol)
_array.assert_allclose(c, n, rtol1, atol1, err_msg, verbose)
return _make_decorator(check_func, name, type_check, contiguous_check,
accept_error, sp_name, scipy_name,
_check_sparse_format)
def numpy_cupy_array_almost_equal(decimal=6, err_msg='', verbose=True,
name='xp', type_check=True,
accept_error=False, sp_name=None,
scipy_name=None):
"""Decorator that checks NumPy results and CuPy ones are almost equal.
Args:
decimal(int): Desired precision.
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values
are appended to the error message.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the same arrays
in the sense of :func:`cupy.testing.assert_array_almost_equal`
(except the type of array module) even if ``xp`` is ``numpy`` or ``cupy``.
.. seealso:: :func:`cupy.testing.assert_array_almost_equal`
"""
def check_func(x, y):
_array.assert_array_almost_equal(x, y, decimal, err_msg, verbose)
return _make_decorator(check_func, name, type_check, False,
accept_error, sp_name, scipy_name)
def numpy_cupy_array_almost_equal_nulp(nulp=1, name='xp', type_check=True,
accept_error=False, sp_name=None,
scipy_name=None):
"""Decorator that checks results of NumPy and CuPy are equal w.r.t. spacing.
Args:
nulp(int): The maximum number of unit in the last place for tolerance.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True``, all error types are acceptable.
If it is ``False``, no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the same arrays
in the sense of :func:`cupy.testing.assert_array_almost_equal_nulp`
(except the type of array module) even if ``xp`` is ``numpy`` or ``cupy``.
.. seealso:: :func:`cupy.testing.assert_array_almost_equal_nulp`
""" # NOQA
def check_func(x, y):
_array.assert_array_almost_equal_nulp(x, y, nulp)
return _make_decorator(check_func, name, type_check, False,
accept_error, sp_name, scipy_name=None)
def numpy_cupy_array_max_ulp(maxulp=1, dtype=None, name='xp', type_check=True,
accept_error=False, sp_name=None,
scipy_name=None):
"""Decorator that checks results of NumPy and CuPy ones are equal w.r.t. ulp.
Args:
maxulp(int): The maximum number of units in the last place
that elements of resulting two arrays can differ.
dtype(numpy.dtype): Data-type to convert the resulting
two array to if given.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the same arrays
in the sense of :func:`assert_array_max_ulp`
(except the type of array module) even if ``xp`` is ``numpy`` or ``cupy``.
.. seealso:: :func:`cupy.testing.assert_array_max_ulp`
""" # NOQA
def check_func(x, y):
_array.assert_array_max_ulp(x, y, maxulp, dtype)
return _make_decorator(check_func, name, type_check, False,
accept_error, sp_name, scipy_name)
def numpy_cupy_array_equal(err_msg='', verbose=True, name='xp',
type_check=True, accept_error=False, sp_name=None,
scipy_name=None, strides_check=False):
"""Decorator that checks NumPy results and CuPy ones are equal.
Args:
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values are
appended to the error message.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
strides_check(bool): If ``True``, consistency of strides is also
checked.
Decorated test fixture is required to return the same arrays
in the sense of :func:`numpy_cupy_array_equal`
(except the type of array module) even if ``xp`` is ``numpy`` or ``cupy``.
.. seealso:: :func:`cupy.testing.assert_array_equal`
"""
def check_func(x, y):
_array.assert_array_equal(x, y, err_msg, verbose, strides_check)
return _make_decorator(check_func, name, type_check, False,
accept_error, sp_name, scipy_name)
def numpy_cupy_array_list_equal(
err_msg='', verbose=True, name='xp', sp_name=None, scipy_name=None):
"""Decorator that checks the resulting lists of NumPy and CuPy's one are equal.
Args:
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values are appended
to the error message.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the same list of arrays
(except the type of array module) even if ``xp`` is ``numpy`` or ``cupy``.
.. seealso:: :func:`cupy.testing.assert_array_list_equal`
""" # NOQA
warnings.warn(
'numpy_cupy_array_list_equal is deprecated.'
' Use numpy_cupy_array_equal instead.',
DeprecationWarning)
def check_func(x, y):
_array.assert_array_equal(x, y, err_msg, verbose)
return _make_decorator(check_func, name, False, False,
False, sp_name, scipy_name)
def numpy_cupy_array_less(err_msg='', verbose=True, name='xp',
type_check=True, accept_error=False, sp_name=None,
scipy_name=None):
"""Decorator that checks the CuPy result is less than NumPy result.
Args:
err_msg(str): The error message to be printed in case of failure.
verbose(bool): If ``True``, the conflicting values are
appended to the error message.
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
type_check(bool): If ``True``, consistency of dtype is also checked.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the smaller array
when ``xp`` is ``cupy`` than the one when ``xp`` is ``numpy``.
.. seealso:: :func:`cupy.testing.assert_array_less`
"""
def check_func(x, y):
_array.assert_array_less(x, y, err_msg, verbose)
return _make_decorator(check_func, name, type_check, False,
accept_error, sp_name, scipy_name)
def numpy_cupy_equal(name='xp', sp_name=None, scipy_name=None):
"""Decorator that checks NumPy results are equal to CuPy ones.
Args:
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.sciyp.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
Decorated test fixture is required to return the same results
even if ``xp`` is ``numpy`` or ``cupy``.
"""
def decorator(impl):
@_wraps_partial_xp(impl, name, sp_name, scipy_name)
def test_func(self, *args, **kw):
# Run cupy and numpy
(
cupy_result, cupy_error,
numpy_result, numpy_error) = (
_call_func_numpy_cupy(
self, impl, args, kw, name, sp_name, scipy_name))
if cupy_error or numpy_error:
_check_cupy_numpy_error(
cupy_error, numpy_error,
accept_error=False)
return
if cupy_result != numpy_result:
message = '''Results are not equal:
cupy: %s
numpy: %s''' % (str(cupy_result), str(numpy_result))
raise AssertionError(message)
return test_func
return decorator
def numpy_cupy_raises(name='xp', sp_name=None, scipy_name=None,
accept_error=Exception):
"""Decorator that checks the NumPy and CuPy throw same errors.
Args:
name(str): Argument name whose value is either
``numpy`` or ``cupy`` module.
sp_name(str or None): Argument name whose value is either
``scipy.sparse`` or ``cupyx.scipy.sparse`` module. If ``None``, no
argument is given for the modules.
scipy_name(str or None): Argument name whose value is either ``scipy``
or ``cupyx.scipy`` module. If ``None``, no argument is given for
the modules.
accept_error(bool, Exception or tuple of Exception): Specify
acceptable errors. When both NumPy test and CuPy test raises the
same type of errors, and the type of the errors is specified with
this argument, the errors are ignored and not raised.
If it is ``True`` all error types are acceptable.
If it is ``False`` no error is acceptable.
Decorated test fixture is required throw same errors
even if ``xp`` is ``numpy`` or ``cupy``.
"""
warnings.warn(
'cupy.testing.numpy_cupy_raises is deprecated.',
DeprecationWarning)
def decorator(impl):
@_wraps_partial_xp(impl, name, sp_name, scipy_name)
def test_func(self, *args, **kw):
# Run cupy and numpy
(
cupy_result, cupy_error,
numpy_result, numpy_error) = (
_call_func_numpy_cupy(
self, impl, args, kw, name, sp_name, scipy_name))
_check_cupy_numpy_error(cupy_error,
numpy_error,
accept_error=accept_error)
return test_func
return decorator
def for_dtypes(dtypes, name='dtype'):
"""Decorator for parameterized dtype test.
Args:
dtypes(list of dtypes): dtypes to be tested.
name(str): Argument name to which specified dtypes are passed.
This decorator adds a keyword argument specified by ``name``
to the test fixture. Then, it runs the fixtures in parallel
by passing the each element of ``dtypes`` to the named
argument.
"""
def decorator(impl):
@_wraps_partial(impl, name)
def test_func(self, *args, **kw):
for dtype in dtypes:
try:
kw[name] = numpy.dtype(dtype).type
impl(self, *args, **kw)
except _skip_classes as e:
print('skipped: {} = {} ({})'.format(name, dtype, e))
except Exception:
print(name, 'is', dtype)
raise
return test_func
return decorator
_complex_dtypes = (numpy.complex64, numpy.complex128)
_regular_float_dtypes = (numpy.float64, numpy.float32)
_float_dtypes = _regular_float_dtypes + (numpy.float16,)
_signed_dtypes = tuple(numpy.dtype(i).type for i in 'bhilq')
_unsigned_dtypes = tuple(numpy.dtype(i).type for i in 'BHILQ')
_int_dtypes = _signed_dtypes + _unsigned_dtypes
_int_bool_dtypes = _int_dtypes + (numpy.bool_,)
_regular_dtypes = _regular_float_dtypes + _int_bool_dtypes
_dtypes = _float_dtypes + _int_bool_dtypes
def _make_all_dtypes(no_float16, no_bool, no_complex):
if no_float16:
dtypes = _regular_float_dtypes
else:
dtypes = _float_dtypes
if no_bool:
dtypes += _int_dtypes
else:
dtypes += _int_bool_dtypes
if not no_complex:
dtypes += _complex_dtypes
return dtypes
def for_all_dtypes(name='dtype', no_float16=False, no_bool=False,
no_complex=False):
"""Decorator that checks the fixture with all dtypes.
Args:
name(str): Argument name to which specified dtypes are passed.
no_float16(bool): If ``True``, ``numpy.float16`` is
omitted from candidate dtypes.
no_bool(bool): If ``True``, ``numpy.bool_`` is
omitted from candidate dtypes.
no_complex(bool): If ``True``, ``numpy.complex64`` and
``numpy.complex128`` are omitted from candidate dtypes.
dtypes to be tested: ``numpy.complex64`` (optional),
``numpy.complex128`` (optional),
``numpy.float16`` (optional), ``numpy.float32``,
``numpy.float64``, ``numpy.dtype('b')``, ``numpy.dtype('h')``,
``numpy.dtype('i')``, ``numpy.dtype('l')``, ``numpy.dtype('q')``,
``numpy.dtype('B')``, ``numpy.dtype('H')``, ``numpy.dtype('I')``,
``numpy.dtype('L')``, ``numpy.dtype('Q')``, and ``numpy.bool_`` (optional).
The usage is as follows.
This test fixture checks if ``cPickle`` successfully reconstructs
:class:`cupy.ndarray` for various dtypes.
``dtype`` is an argument inserted by the decorator.
>>> import unittest
>>> from cupy import testing
>>> @testing.gpu
... class TestNpz(unittest.TestCase):
...
... @testing.for_all_dtypes()
... def test_pickle(self, dtype):
... a = testing.shaped_arange((2, 3, 4), dtype=dtype)
... s = pickle.dumps(a)
... b = pickle.loads(s)
... testing.assert_array_equal(a, b)
Typically, we use this decorator in combination with
decorators that check consistency between NumPy and CuPy like
:func:`cupy.testing.numpy_cupy_allclose`.
The following is such an example.
>>> import unittest
>>> from cupy import testing
>>> @testing.gpu
... class TestMean(unittest.TestCase):
...
... @testing.for_all_dtypes()
... @testing.numpy_cupy_allclose()
... def test_mean_all(self, xp, dtype):
... a = testing.shaped_arange((2, 3), xp, dtype)
... return a.mean()
.. seealso:: :func:`cupy.testing.for_dtypes`
"""
return for_dtypes(_make_all_dtypes(no_float16, no_bool, no_complex),
name=name)
def for_float_dtypes(name='dtype', no_float16=False):
"""Decorator that checks the fixture with float dtypes.
Args:
name(str): Argument name to which specified dtypes are passed.
no_float16(bool): If ``True``, ``numpy.float16`` is
omitted from candidate dtypes.
dtypes to be tested are ``numpy.float16`` (optional), ``numpy.float32``,
and ``numpy.float64``.
.. seealso:: :func:`cupy.testing.for_dtypes`,
:func:`cupy.testing.for_all_dtypes`
"""
if no_float16:
return for_dtypes(_regular_float_dtypes, name=name)
else:
return for_dtypes(_float_dtypes, name=name)
def for_signed_dtypes(name='dtype'):
"""Decorator that checks the fixture with signed dtypes.
Args:
name(str): Argument name to which specified dtypes are passed.
dtypes to be tested are ``numpy.dtype('b')``, ``numpy.dtype('h')``,
``numpy.dtype('i')``, ``numpy.dtype('l')``, and ``numpy.dtype('q')``.
.. seealso:: :func:`cupy.testing.for_dtypes`,
:func:`cupy.testing.for_all_dtypes`
"""
return for_dtypes(_signed_dtypes, name=name)
def for_unsigned_dtypes(name='dtype'):
"""Decorator that checks the fixture with unsinged dtypes.
Args:
name(str): Argument name to which specified dtypes are passed.
dtypes to be tested are ``numpy.dtype('B')``, ``numpy.dtype('H')``,
``numpy.dtype('I')``, ``numpy.dtype('L')``, and ``numpy.dtype('Q')``.
.. seealso:: :func:`cupy.testing.for_dtypes`,
:func:`cupy.testing.for_all_dtypes`
"""
return for_dtypes(_unsigned_dtypes, name=name)
def for_int_dtypes(name='dtype', no_bool=False):
"""Decorator that checks the fixture with integer and optionally bool dtypes.
Args:
name(str): Argument name to which specified dtypes are passed.
no_bool(bool): If ``True``, ``numpy.bool_`` is
omitted from candidate dtypes.
dtypes to be tested are ``numpy.dtype('b')``, ``numpy.dtype('h')``,
``numpy.dtype('i')``, ``numpy.dtype('l')``, ``numpy.dtype('q')``,
``numpy.dtype('B')``, ``numpy.dtype('H')``, ``numpy.dtype('I')``,
``numpy.dtype('L')``, ``numpy.dtype('Q')``, and ``numpy.bool_`` (optional).
.. seealso:: :func:`cupy.testing.for_dtypes`,
:func:`cupy.testing.for_all_dtypes`
""" # NOQA
if no_bool:
return for_dtypes(_int_dtypes, name=name)
else:
return for_dtypes(_int_bool_dtypes, name=name)
def for_complex_dtypes(name='dtype'):
"""Decorator that checks the fixture with complex dtypes.
Args: