forked from jax-ml/jax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_test.py
8678 lines (7110 loc) · 269 KB
/
api_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 2018 Google LLC
#
# 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
#
# https://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 collections
import collections.abc
from contextlib import contextmanager
import copy
import enum
from functools import partial
import inspect
import operator
import re
import subprocess
import sys
import types
from typing import Callable, List, Optional
import unittest
import warnings
import weakref
import functools
import itertools as it
import operator as op
from absl import logging
from absl.testing import absltest, parameterized
import numpy as np
import concurrent.futures
import jax
import jax.numpy as jnp
from jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian
from jax import core, lax
from jax import custom_batching
from jax._src import api, dtypes, dispatch
from jax.core import Primitive
from jax.errors import UnexpectedTracerError
from jax.interpreters import ad
from jax.interpreters import mlir
from jax.interpreters import xla
from jax.interpreters import pxla
from jax.interpreters import partial_eval as pe
from jax.interpreters.pxla import PartitionSpec as P
from jax._src import device_array
import jax._src.lib
from jax._src.lib import xla_client
from jax._src import test_util as jtu
from jax import tree_util
from jax import linear_util as lu
import jax._src.util
from jax._src.ad_checkpoint import saved_residuals
from jax.ad_checkpoint import checkpoint as new_checkpoint, checkpoint_name
from jax.config import config
config.parse_flags_with_absl()
FLAGS = config.FLAGS
python_version = (sys.version_info[0], sys.version_info[1])
numpy_version = tuple(map(int, np.__version__.split('.')[:3]))
jaxlib_version = jax._src.lib.version
class CPPJitTest(jtu.BufferDonationTestCase):
"""Shared tests between the Python and the C++ jax,jit implementations.
Because the Python implementation supports more features, we need to have the
Python tests that extend the C++ tests (and not the other way around).
"""
@property
def use_cpp_jit(self) -> bool:
return True
@property
def jit(self):
return functools.partial(api._jit, self.use_cpp_jit)
def test_jit_repr(self):
def my_function():
return
jitted = jit(my_function)
self.assertEqual(repr(jitted), f"<CompiledFunction of {repr(my_function)}>")
def test_jit_repr_errors(self):
class Callable:
def __call__(self): pass
def __repr__(self):
raise ValueError("invalid repr")
# repr succeeds when underlying function repr fails.
jitted = jit(Callable())
self.assertEqual(repr(jitted), "<CompiledFunction>")
# repr succeeds when object is malformed.
del jitted.__wrapped__
self.assertEqual(repr(jitted), "<CompiledFunction>")
def test_jit_of_noncallable(self):
self.assertRaisesRegex(TypeError, "Expected a callable value.*",
lambda: self.jit(3))
def test_jit_of_generator(self):
def gen(x):
yield x
self.assertRaisesRegex(TypeError,
"Expected a function, got a generator function.*",
lambda: self.jit(gen))
@parameterized.parameters([
# Integer support
(1, 2, 3, 4, 5),
# Numpy array support
(
np.asarray(1, np.int32),
np.asarray(2, np.int32),
np.asarray(3, np.int32),
np.asarray(4, np.int32),
np.asarray(5, np.int32),
),
])
def test_jit_static_args(self, one, two, three, four, five):
side = []
def f(x, y, z, flag=False, flag2=False):
del flag2 # unused
assert flag
side.append(None)
return 100 * x + 10 * y + z
f1 = self.jit(f, static_argnums=(3, 4))
assert f1(one, two, three, True, False) == 123
assert len(side) == 1
assert f1(one, two, three, True, False) == 123
assert len(side) == 1 # Obvious cache hit.
assert f1(two, one, three, True, False) == 213
assert len(side) == 1 # Should cache hit because same signature.
assert f1(two, one, three, True, True) == 213
assert len(side) == 2
side[:] = []
f2 = self.jit(f, static_argnums=(0, 2, 3, 4))
assert f2(1, 2, 3, True, False) == 123
assert len(side) == 1
assert f2(1, 3, 3, True, False) == 133
assert len(side) == 1
assert f2(2, 2, 3, True, False) == 223
assert len(side) == 2
assert f2(2, 4, 3, True, False) == 243
assert len(side) == 2
assert f2(2, 4, 3, True, True) == 243
assert len(side) == 3
assert f2(2, 5, 3, True, True) == 253
assert len(side) == 3
def test_static_args_equality(self):
class A():
def __hash__(self):
return 1
def __eq__(self, other):
return isinstance(other, A)
side = []
def f(x, static_arg):
del static_arg
side.append(None)
return x * 100
f1 = self.jit(f, static_argnums=(1,))
self.assertEqual(f1(1, A()), 100)
self.assertLen(side, 1)
self.assertEqual(f1(1, A()), 100)
self.assertLen(side, 1)
if self.use_cpp_jit:
f1_cpp = getattr(f1, "_cpp_jitted_f", f1)
self.assertEqual(f1_cpp._cache_size(), 1)
@parameterized.parameters([
(1, 2, 3),
(
np.asarray(1, np.int32),
np.asarray(2, np.int32),
np.asarray(3, np.int32),
),
])
def test_jit_kwargs(self, one, two, three):
side = []
# For the CPP jit, we need to clear the cache to prevent cache hits between
# parameterized tests.
if hasattr(self.jit, "cache_clear"):
self.jit.cache_clear()
def f(x, y, z):
side.append(None)
return 100 * x + 10 * y + z
f = self.jit(f)
assert f(one, two, three) == 123
assert len(side) == 1
assert f(one, two, three) == 123
assert len(side) == 1
assert f(one, two, z=three) == 123
assert len(side) == 2 # actually recompiles from kwarg
assert f(one, two, z=three) == 123
assert len(side) == 2 # but should still cache
f(one, two, z=np.zeros(3)) # doesn't crash
if config.x64_enabled:
# In the above call, three is of a new type (int64), thus it should
# trigger a new compilation.
assert len(side) == 3
def test_jit_device(self):
device = jax.devices()[-1]
x = self.jit(lambda x: x, device=device)(3.)
self.assertIsInstance(x, jnp.DeviceArray)
self.assertEqual(x.device_buffer.device(), device)
def test_complex_support(self):
self.assertEqual(self.jit(lambda x: x + 1)(1 + 1j), 2 + 1j)
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": f"_{argnum_type}",
"argnum_type": argnum_type}
for argnum_type in ("static_argnums", "donate_argnums")))
def test_jit_argnums_overflow_error(self, argnum_type: str):
def f(a, b, c):
...
# TODO(phawkins): reenable this test after Python 3.7 support is dropped.
# def g(a, /, b, *, c):
# ...
def h(a, *args):
...
def i():
...
# Simplest cases
self.jit(f, **{argnum_type: (0, 1)})
# self.jit(g, **{argnum_type: (0, 1)})
self.jit(f, **{argnum_type: (0, 1, -3)})
# Out of bounds without *args
# with self.assertRaises(ValueError):
with self.assertWarns(SyntaxWarning):
self.jit(f, **{argnum_type: (0, 1, 3)})
# with self.assertRaises(ValueError):
with self.assertWarns(SyntaxWarning):
self.jit(f, **{argnum_type: (0, 1, -4)})
# # with self.assertRaises(ValueError):
# with self.assertWarns(SyntaxWarning):
# self.jit(g, **{argnum_type: (0, 1, 3)})
# # with self.assertRaises(ValueError):
# with self.assertWarns(SyntaxWarning):
# self.jit(g, **{argnum_type: (0, 1, -3)})
# Out of bounds with *args
self.jit(h, **{argnum_type: (0, 999)})
self.jit(h, **{argnum_type: (0, -999)})
# No positional arguments
self.jit(i, static_argnums=())
self.jit(i)
def test_jit_argnames_validation(self):
def f(a, b, c):
...
def g(a, b, **kwargs):
...
# TODO(phawkins): reenable this test after Python 3.7 support is dropped.
# def h(a, /, b, c, *args, **kwargs):
# ...
# Simplest case
self.jit(f, static_argnames=("b", "c"))
# Undefined arg without **kwargs
# with self.assertRaises(ValueError):
with self.assertWarns(SyntaxWarning):
self.jit(f, static_argnames=("b", "c", "not_defined"))
# Undefined arg with **kwargs
self.jit(g, static_argnames=("a", "b", "not_defined"))
# TODO(phawkins): reenable this test after Python 3.7 support is dropped.
# self.jit(h, static_argnames=("b", "c"))
# self.jit(h, static_argnames=("b", "c", "not_defined"))
#
# # Positional only
# # with self.assertRaises(ValueError):
# with self.assertWarns(SyntaxWarning):
# self.jit(h, static_argnames=("a", "c"))
# # Var positional
# # with self.assertRaises(ValueError):
# with self.assertWarns(SyntaxWarning):
# self.jit(h, static_argnames=("args", "c"))
def test_jit_with_many_args_works(self):
@self.jit
def f(args_list):
return sum(args_list)
self.assertEqual(f(list(range(500))), sum(range(500)))
# Jit and Donate arguments
def test_jit_donate_argnums_warning_raised(self):
x = jnp.array([1.0, 2.0], jnp.float32)
y = jnp.array([1, 2], jnp.int32)
f = self.jit(lambda x, y: x.sum() + y.sum(), donate_argnums=(0, 1))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
f(x, y)
self.assertLen(w, 1)
self.assertTrue(issubclass(w[-1].category, UserWarning))
self.assertIn(
"Some donated buffers were not usable:",
str(w[-1].message))
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
def test_jit_donate_argnums_invalidates_input(self):
# We can't just use `lambda x: x` because JAX simplifies this away to an
# empty XLA computation.
move = self.jit(lambda x: x + x - x, donate_argnums=0)
x = jnp.ones([])
y = move(x)
self.assertDeleted(x)
self.assertEqual(y, 1.)
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
def test_jit_donate_argnums_static_argnums(self):
jit_fun = self.jit(
lambda a, b, c, d: ((a + b + c), (a + b + d)),
static_argnums=(0, 1),
donate_argnums=(2, 3))
c = jax.device_put(jnp.array([1., 1.]))
d = jax.device_put(jnp.array([1., 1., 1.]))
e, f = jit_fun(1, 2, c, d)
np.testing.assert_allclose(e, jnp.array([4., 4.]))
np.testing.assert_allclose(f, jnp.array([4., 4., 4.]))
self.assertDeleted(c)
self.assertDeleted(d)
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
def test_jit_donate_argnums_weak_type(self):
# input has weak-type, output does not have weak-type
move = self.jit(lambda x: x.astype(int), donate_argnums=0)
x = jnp.broadcast_to(2, (3,))
move(x)
self.assertDeleted(x)
@jtu.skip_on_devices("cpu") # In/out aliasing not supported on CPU.
def test_jnp_array_copy(self):
# https://github.com/google/jax/issues/3412
@partial(self.jit, donate_argnums=(0,))
def _test(array):
return array.at[0].set(77)
x = jnp.asarray([0, 1])
x_copy = jnp.array(x, copy=True)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
_test(x) # donation
# Gives: RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer.
print(x_copy) # doesn't crash
def test_jit_global_cache(self):
def f(x):
assert python_should_be_executing
return x
python_should_be_executing = True
self.jit(f)(2)
python_should_be_executing = False
self.jit(f)(3)
def test_jit_shallow_copy(self):
def f(x):
return copy.copy(x)
self.jit(f)(1)
def test_jit_deep_copy(self):
def f(x):
return copy.deepcopy(x)
self.jit(f)(1)
def test_disable_jit(self):
effects = []
@self.jit
def f(x):
effects.append(1)
return x
with api.disable_jit():
f(2)
f(2)
assert len(effects) == 2
f(2)
f(2)
assert len(effects) == 3
def test_static_argnum_on_method(self):
class A:
@functools.partial(self.jit, static_argnums=(0,))
def my_func_jit(self, x):
return x+2
A().my_func_jit(3)
def test_static_argnum_on_static_method_is_not_supported(self):
with self.assertRaisesRegex(TypeError, "Expected a callable value"):
class A:
@functools.partial(self.jit, static_argnums=(0,))
@classmethod
def my_classmethod_jit(cls, x):
return x+2
def test_staticmethod_is_not_supported(self):
with self.assertRaisesRegex(TypeError,
"staticmethod arguments are not supported"):
class A:
@functools.partial(self.jit)
@staticmethod
def my_staticmethod_jit(x):
return x + 2
def test_concurrent_jit(self):
@self.jit
def f(x):
return x + x - 3.
xs = [self.rng().randn(i) for i in range(10)]
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(partial(f, x)) for x in xs]
ys = [f.result() for f in futures]
for x, y in zip(xs, ys):
self.assertAllClose(x * 2 - 3., y)
def test_trivial_computations(self):
x = jnp.array([1, 2, 3])
y = self.jit(lambda x: x)(x)
self.assertIs(x, y)
z1, z2 = self.jit(lambda x: (x, x))(x)
self.assertIs(z1, z2)
x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])
z1, z2, z3 = self.jit(lambda x, y: (y, 1, x))(x1, x2)
self.assertIs(z1, x2)
self.assertIs(z3, x1)
self.assertEqual(z2, 1)
def test_trivial_computations_with_tokens(self):
@self.jit
def noop(arr, token):
return arr, token
arr = jax.numpy.ones(10)
token = jax.lax.create_token()
self.assertEqual(token, noop(arr, token)[1])
def test_jit_bad_input(self):
def f(x):
return x
self.assertRaisesRegex(
TypeError, ".* 'foo' of type <.*'str'> is not a valid JAX type",
lambda: self.jit(f)("foo"))
# Jax type objects aren't valid data arguments.
self.assertRaisesRegex(
TypeError,
".* '.*int32.*' of type <.*_ScalarMeta.*> is not a valid JAX type",
lambda: self.jit(f)(jnp.int32))
def test_jit_on_all_devices(self):
# Verifies we can run the same computation on every device present, even
# if they are, for example, different models of GPU.
data = self.rng().rand(1000).astype(np.float32)
f = self.jit(jnp.negative)
for device in jax.local_devices():
x = device_put(data, device=device)
np.testing.assert_array_equal(-data, f(x))
def test_jit_nested_donate_ignored(self):
jit_fun = self.jit(lambda x: self.jit(lambda y: y**2, donate_argnums=0)(x))
a = jax.device_put(jnp.array(1))
# NOTE(mattjj): stopped raising error here and instead just ignored
# with self.assertRaisesRegex(ValueError, "nested.*not supported"):
# jit_fun(a)
jit_fun(a) # doesn't crash
def test_jit_reference_dropping(self):
x = jnp.ones(10)
f = (lambda x: lambda: x)(x) # reference to x in f's closure
g = self.jit(f)
x = weakref.ref(x) # no more strong ref to x in this scope
assert x() is not None # x is still around
f() # f runs
g() # g runs
g() # g runs a second time
del f # delete the raw callable
assert x() is not None # x is still around
g() # g still runs
del g # no more references to x
assert x() is None # x is gone
def test_jit_of_nonweakreferenceable_function(self):
class CallableWithSlots:
__slots__ = []
def __call__(self, x):
return x + 1
c = CallableWithSlots()
with self.assertRaisesRegex(TypeError, "cannot create weak reference.*"):
weakref.ref(c)
# Building a jit object does not crash.
f = self.jit(c)
with self.assertRaisesRegex(TypeError, "cannot create weak reference.*"):
# Calling the jit object will fail, but not because of the C++ JIT. The
# Python-level jit cache requires weak reference support.
f(3)
def test_jit_raises_on_first_invocation_on_non_hashable_static_argnum(self):
if self.jit != api._python_jit:
raise unittest.SkipTest("this test only applies to _python_jit")
f = lambda x, y: x + 3
jitted_f = self.jit(f, static_argnums=(1,))
msg = ("Non-hashable static arguments are not supported, as this can lead "
"to unexpected cache-misses. Static argument (index 1) of type "
"<class 'numpy.ndarray'> for function <lambda> is non-hashable.")
with self.assertRaisesRegex(ValueError, re.escape(msg)):
jitted_f(1, np.asarray(1))
def test_cpp_jit_raises_on_non_hashable_static_argnum(self):
if not self.use_cpp_jit:
raise unittest.SkipTest("this test only applies to _cpp_jit")
f = lambda x, y: x + 3
jitted_f = self.jit(f, static_argnums=[1])
jitted_f(1, 1)
msg = ("Non-hashable static arguments are not supported. An error occurred "
".*while trying to hash an object of type "
"<class 'numpy\\.ndarray'>, 1. The error was:\nTypeError: "
"unhashable type: 'numpy\\.ndarray'")
# Typo was fixed in newer jaxlib
if jax._src.lib.xla_extension_version < 66:
msg = msg.replace('occurred', 'occured')
with self.assertRaisesRegex(ValueError, msg):
jitted_f(1, np.asarray(1))
class HashableWithoutEq:
def __hash__(self):
return 1
def __eq__(self, other):
raise NotImplementedError(
"A Python error is as is, without stack trace")
with self.assertRaisesRegex(
ValueError,
re.escape("static arguments should be comparable using __eq__")):
jitted_f(1, HashableWithoutEq())
# __eq__ would only be called if we might have a cache hit. Call the
# function a second time with exactly the same arguments to make sure that
# we could.
jitted_f(1, HashableWithoutEq())
def test_cpp_jit_raises_other_exceptions_when_hashing_fails(self):
class A:
def __hash__(self):
raise ValueError
f = jax.jit(lambda x: x + 1, static_argnums=(0,))
a = A()
with self.assertRaisesRegex(ValueError, '^$'): # no extra message
f(a)
def test_cpp_jitted_function_returns_PyBuffer(self):
if not self.use_cpp_jit:
raise unittest.SkipTest("this test only applies to _cpp_jit")
jitted_f = self.jit(lambda a: a + 1)
jitted_f(1)
self.assertIsInstance(jitted_f(2), device_array.Buffer)
@jtu.skip_on_devices("cpu")
def test_explicit_backend(self):
f = lambda x: x + 1
jitted_f = jit(f, backend=jtu.device_under_test())
jitted_f_cpu = jit(f, backend="cpu")
result = jitted_f(1.)
result_cpu = jitted_f_cpu(1.)
self.assertEqual(result.device_buffer.platform(), jtu.device_under_test())
self.assertEqual(result_cpu.device_buffer.platform(), "cpu")
@jtu.skip_on_devices("cpu")
def test_device_to_device_copy_between_backends(self):
# b/186624243
f = lambda x: x + 1
jitted_f = jit(f, backend=jtu.device_under_test())
jitted_f_cpu = jit(f, backend="cpu")
x = np.arange(30).reshape(1, 10, 3)
result = jitted_f(x)
result_cpu = jitted_f_cpu(result)
result_2 = jitted_f(result_cpu)
result_cpu_2 = jitted_f_cpu(result_2)
self.assertAllClose(result_2, x + 3)
self.assertAllClose(result_cpu_2, x + 4)
@jtu.skip_on_devices("cpu")
def test_mismatched_nested_backends(self):
@partial(jit, backend=jtu.device_under_test())
def f(x):
return jit(lambda x: x + 1, backend="cpu")(x)
with self.assertRaisesRegex(
ValueError,
"Outer-jit backend specification .* must match explicit inner-jit "
"backend specification cpu."):
f(1.)
def test_omnistaging(self):
# See https://github.com/google/jax/issues/5206
# TODO(frostig): remove once we always enable_custom_prng
def _prng_key_as_array(key):
return key.unsafe_raw_array() if config.jax_enable_custom_prng else key
# TODO(frostig): remove once we always enable_custom_prng
def _array_as_prng_key(arr):
arr = np.array(arr, dtype=np.uint32)
if config.jax_enable_custom_prng:
return jax._src.prng.PRNGKeyArray(
jax._src.prng.threefry_prng_impl, arr)
else:
return arr
key_list = [None]
def init():
key, subkey = jax.random.split(key_list[0])
key_list[0] = key
return jax.random.normal(subkey, ())
key_list[0] = _array_as_prng_key([2384771982, 3928867769])
init()
self.jit(init)()
self.assertIsInstance(_prng_key_as_array(key_list[0]), core.Tracer)
def test_jit_wrapped_attributes(self):
def f(x: int) -> int:
"""docstring of f."""
return x + 1
f.some_value = 4
jf = self.jit(f)
for attr in ["doc", "name", "module", "qualname", "annotations"]:
self.assertEqual(
{attr: getattr(f, f"__{attr}__")},
{attr: getattr(jf, f"__{attr}__")})
self.assertEqual(f.some_value, jf.some_value)
def test_jit_python_builtin(self):
x = jnp.array([1, 2])
expected = x + 1
jit_add = self.jit(operator.add, static_argnums=(1,))
actual = jit_add(x, 1)
self.assertArraysEqual(expected, actual)
def test__infer_argnums_and_argnames(self):
def f(x, y=1):
pass
sig = inspect.signature(f)
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=None, argnames=None)
assert argnums == ()
assert argnames == ()
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=0, argnames=None)
assert argnums == (0,)
assert argnames == ('x',)
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=None, argnames='y')
assert argnums == (1,)
assert argnames == ('y',)
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=0, argnames='y') # no validation
assert argnums == (0,)
assert argnames == ('y',)
def g(x, y, *args):
pass
sig = inspect.signature(g)
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=(1, 2), argnames=None)
assert argnums == (1, 2)
assert argnames == ('y',)
def h(x, y, **kwargs):
pass
sig = inspect.signature(h)
argnums, argnames = api._infer_argnums_and_argnames(
sig, argnums=None, argnames=('foo', 'bar'))
assert argnums == ()
assert argnames == ('foo', 'bar')
def test_jit_with_static_argnames(self):
def f(x):
assert x == 'foo'
return 1
f_nums = self.jit(f, static_argnums=0)
assert f_nums('foo') == 1
assert f_nums(x='foo') == 1
f_names = self.jit(f, static_argnames='x')
assert f_names('foo') == 1
assert f_names(x='foo') == 1
def test_new_static_argnum_on_keyword_arguments(self):
f = self.jit(lambda x: x, static_argnums=0)
y = f(x=4)
assert y == 4
def test_new_static_argnum_with_default_arguments(self):
f = self.jit(lambda x=4: x, static_argnums=0)
y = f()
assert y == 4
def test_jit_with_mismatched_static_argnames(self):
x_is_tracer, y_is_tracer = False, False
def f(x, y):
assert isinstance(x, core.Tracer) == x_is_tracer
assert isinstance(y, core.Tracer) == y_is_tracer
return 1
# If both static_argnums and static_argnames are provided, they are allowed
# to disagree and `jit` will respect the user's choices.
f_nums = self.jit(f, static_argnums=1, static_argnames=())
x_is_tracer, y_is_tracer = True, False
assert f_nums(2, 'foo') == 1
x_is_tracer, y_is_tracer = True, True
assert f_nums(1, y=2) == 1
f_names = self.jit(f, static_argnums=(), static_argnames='y')
x_is_tracer, y_is_tracer = True, True
assert f_names(2, 3) == 1
x_is_tracer, y_is_tracer = True, False
assert f_names(1, y='foo') == 1
f_mixed = self.jit(f, static_argnums=(1,), static_argnames='x')
x_is_tracer, y_is_tracer = True, False
assert f_mixed(2, 'foo') == 1
x_is_tracer, y_is_tracer = True, True
assert f_mixed(1, y=3) == 1
x_is_tracer, y_is_tracer = False, True
assert f_mixed(x='foo', y=3) == 1
# TODO(zhangqiaorjc): Test pruning constants after DCE pass prunes primitive
# applications.
@parameterized.named_parameters(jtu.cases_from_list(
{"testcase_name": f"_num_args={num_args}",
"num_args": num_args}
for num_args in [2, 3, 4]))
def test_jit_with_pruned_args(self, num_args):
def f(*args):
used = np.array(2)
return args[1] + used
f_pruned = self.jit(f)
args = range(num_args)
with jtu.count_device_put() as count:
np.testing.assert_allclose(f_pruned(*args), 3)
self.assertEqual(count[0], 1)
def testBuffersAreFreedPromptly(self):
# Regression test for a bug where garbage collection was delayed too long
# for NumPy buffers that are aliased zero-copy by the runtime.
@self.jit
def f(x):
return x + 1
refs = []
x = np.ones((10000,), np.float32)
for step in range(1000):
x = f(x)
refs.append(weakref.ref(x))
x = np.asarray(x)
# We expect most of the input buffers to have been garbage
# collected in parallel with the execution. We can't call
# block_until_ready() here because it would force a garbage collection.
live_refs = len([ref for ref in refs if ref() is not None])
self.assertLessEqual(live_refs, 100)
def test_jit_lower_compile(self):
def f(x):
return jnp.sqrt(x ** 2) + 1.
f_jit = self.jit(f)
lowered = f_jit.lower(1.)
compiled = lowered.compile()
self.assertAllClose(compiled(1.), 2.)
self.assertEqual(lowered.in_avals, compiled.in_avals)
expected_dtype = np.float64 if config.x64_enabled else np.float32
for obj in [lowered, compiled]:
self.assertEqual(
obj.in_avals,
((jax.ShapedArray([], expected_dtype, weak_type=True),), {}))
self.assertEqual(obj.in_tree, jax.tree_flatten(((0,), {}))[1])
def test_jit_lower_duck_typing(self):
f_jit = self.jit(lambda x: 2 * x)
f_low = f_jit.lower(jax.ShapeDtypeStruct((), 'float32')) # doesn't crash
f_exe = f_low.compile()
self.assertAllClose(f_exe(jnp.float32(1.)), jnp.float32(2.))
def test_jit_lower_compile_in_tree_mismatch(self):
def f(x):
return jnp.sqrt(x ** 2) + 1.
f_jit = self.jit(f)
f_low = f_jit.lower(1.)
f_exe = f_low.compile()
self.assertRaisesRegex(
TypeError, "function compiled for .*, called with .*",
lambda: f_exe([1.]))
def test_jit_lower_compile_trivial(self):
def f(x): return x
out = self.jit(f).lower(1.).compile()(4.)
self.assertAllClose(out, 4.)
def test_jit_lower_compile_trivial_in_tree_mismatch(self):
def f(x): return x
f_exe = self.jit(f).lower(1.).compile()
self.assertRaisesRegex(
TypeError, "function compiled for .*, called with .*",
lambda: f_exe([4.]))
def test_jit_lower_compile_arg_type_mismatch(self):
def f(x):
return jnp.sqrt(x ** 2) + 1.
x = jnp.array(1, dtype=int)
x_f32 = x.astype(jnp.float32)
x_i32 = x.astype(jnp.int32)
f_exe = self.jit(f).lower(x_f32).compile()
self.assertRaisesRegex(
TypeError,
"Computation compiled for input types:\n.*float32.*\n"
"called with:\n.*int32.*",
lambda: f_exe(x_i32))
def test_jit_lower_compile_multi_arg(self):
def f(*args):
x, *_ = args
return jnp.sqrt(x ** 2) + 1.
f_exe = self.jit(f).lower(1., 1.).compile()
self.assertAllClose(f_exe(1., 1.), 2.)
def test_jit_lower_compile_trivial_multi_arg(self):
def f(*args):
x, *_ = args
return x
f_exe = self.jit(f).lower(1., 1.).compile()
self.assertAllClose(f_exe(1., 1.), 1.)
@jtu.skip_on_devices("cpu") # no donation on cpu, so this would warn
def test_jit_lower_donate_argnums_available(self):
def f(*args):
x, *_ = args
return x + 4.
f_low = self.jit(f, donate_argnums=(0,)).lower(1., 1.)
f_com = f_low.compile()
f_low.donate_argnums == f_com.donate_argnums == (0,)
def test_jit_lower_compile_vmap(self):
f = self.jit(lambda x: x + 4).lower(1.).compile()
def err():
return jax.vmap(lambda x: f(x) + 2)(jnp.ones(3))
self.assertRaisesRegex(
TypeError,
"Cannot apply JAX transformations to a function lowered and compiled "
"for a particular signature. Detected .*BatchTracer",
err)
def test_jit_lower_compiler_ir(self):
f = self.jit(lambda x: x + 4).lower(1.)
self.assertIsNotNone(f.compiler_ir())
self.assertIsNotNone(f.compiler_ir(dialect='hlo'))
self.assertIsNotNone(f.compiler_ir(dialect='mhlo'))
def test_jit_lower_compile_compiler_ir(self):
f = self.jit(lambda x: x + 4).lower(1.).compile()
self.assertIsNotNone(f.compiler_ir())
def test_jit_lower_trivial_compiler_ir(self):
f = self.jit(lambda x: x).lower(1.)
self.assertIsNotNone(f.compiler_ir())
self.assertIsNotNone(f.compiler_ir(dialect='hlo'))
self.assertIsNotNone(f.compiler_ir(dialect='mhlo'))
def test_jit_lower_trivial_compile_compiler_ir(self):
f = self.jit(lambda x: x).lower(1.).compile()
self.assertIsNotNone(f.compiler_ir())
def test_jit_lower_no_prunning(self):
compiled = self.jit(lambda x, y: x + y).lower(1., 2.).compile()
self.assertEqual(compiled._executable._kept_var_idx, {0, 1})
self.assertLen(compiled._executable.in_avals, 2)
compiled = self.jit(lambda x, y: x).lower(1., 2.).compile()
self.assertEqual(compiled._executable._kept_var_idx, {0})
self.assertLen(compiled._executable.in_avals, 1)
compiled = self.jit(lambda x, y: x, keep_unused=True).lower(
1., 2.).compile()
self.assertEqual(compiled._executable._kept_var_idx, {0, 1})
self.assertLen(compiled._executable.in_avals, 2)
# Also works with jax.jit
jitted_f = self.jit(lambda x, y: x, keep_unused=True)
with jtu.count_device_put() as count:
_ = jitted_f(1, 2)
self.assertEqual(count[0], 1)
def test_jit_lower_compile_executable(self):
f = self.jit(lambda x: x + 4).lower(1.).compile()
self.assertIsNotNone(f.runtime_executable())
def test_jit_enum_as_dict_keys_fails(self):
class E(enum.Enum):
A = 0
B = 1
@self.jit
def f(d) -> float:
return d[E.A]