-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
shape_poly_test.py
2836 lines (2536 loc) · 128 KB
/
shape_poly_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 2020 The JAX Authors.
#
# 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.
"""Tests for the shape-polymorphic jax2tf conversion."""
import contextlib
import math
import unittest
from absl import logging
from absl.testing import absltest, parameterized
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import collections
import functools
from functools import partial
import operator as op
import re
import jax
from jax import core
from jax.experimental import jax2tf
from jax.experimental.jax2tf import shape_poly
from jax.experimental.jax2tf import jax_export
from jax.experimental import pjit
from jax import lax
import jax.numpy as jnp
from jax import random
from jax import tree_util
from jax._src import test_util as jtu
from jax._src import util
from jax._src.lax import lax as lax_internal
from jax._src.lax import control_flow as lax_control_flow
from jax._src.lib import xla_client
import numpy as np
from jax.experimental.jax2tf.tests import tf_test_util
import tensorflow as tf # type: ignore[import]
from jax import config
from jax._src.config import numpy_dtype_promotion
config.parse_flags_with_absl()
# Import after parsing flags
from jax.experimental.jax2tf.tests import primitive_harness
from jax.experimental.jax2tf.tests.primitive_harness import Harness, CustomArg, RandArg, StaticArg
from jax.experimental.jax2tf.tests.jax2tf_limitations import Jax2TfLimitation
PS = jax2tf.PolyShape
_f32 = np.float32
_i32 = np.int32
expect_error_associative_scan = (
(None, None) if (not config.jax2tf_default_native_serialization or
jtu.device_under_test() == "tpu") else
(NotImplementedError,
"associative scan over axis of non-constant size"))
class DimExprTest(tf_test_util.JaxToTfTestCase):
def test_parse_shape(self):
self.assertEqual((), shape_poly._parse_spec("", ()))
self.assertEqual((), shape_poly._parse_spec("()", ()))
self.assertEqual((2, 3), shape_poly._parse_spec(None, (2, 3)))
self.assertEqual((2, 3), shape_poly._parse_spec("2, 3,", (2, 3)))
self.assertEqual((2, 3), shape_poly._parse_spec("2, _", (2, 3)))
self.assertEqual((2, 3), shape_poly._parse_spec("2, ...", (2, 3)))
self.assertEqual((2, 3), shape_poly._parse_spec("...", (2, 3)))
self.assertEqual((2, 3), shape_poly._parse_spec(" ( 2 , 3 ) ", (2, 3)))
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertEqual((a, 3), shape_poly._parse_spec("(a, ...) ", (None, 3)))
tshape = tf.TensorShape([None, 3])
self.assertEqual((a, 3), shape_poly._parse_spec("(a, ...) ", tshape))
a, b = shape_poly._parse_spec("a, b", (2, 3))
@parameterized.named_parameters(
dict(testcase_name=f"_{dim_spec}",
dim_spec=dim_spec, dim_poly=dim_poly)
for dim_spec, dim_poly in [
("2*a*b", 2 * a * b),
("-2 * a^2 * b + b^2", -2 * a * a * b + b * b),
("-2 * a^2 * b + -1 *b^2*a", -2 * a * a * b - a * b * b),
("3 * a * b * a + -2", 3 * a * b * a - 2),
("a + 1 ,", a + 1),
("a - 1", a - 1),
("a + -1", a - 1),
("3 * a * mod(a + 2, b + 2)", 3 * a * ((a + 2) % (b + 2))),
("3 * floordiv(a + 2, b + 2) * 2", 3 * ((a + 2) // (b + 2)) * 2),
])
def test_parse_dim(self,
dim_spec="-2 * a^2 * b + b^2",
dim_poly=-2 * a * a * b + b * b):
self.assertEqual((dim_poly,), shape_poly._parse_spec(dim_spec, (None,)))
self.assertEqual((dim_poly,), shape_poly._parse_spec(str(dim_poly), (None,)))
@parameterized.named_parameters(
dict(testcase_name=f"_{shape_spec=}",
shape_spec=shape_spec)
for shape_spec in [
"2.5", "a + a a", "a ^ a", "a, a",
"_", "...", "a ;", ")(", "2a", "a@", "'a'", "('a', ...)",
"mod(a)", "floordiv(a, b, c)", "..., 3"
])
def test_parse_error(self,
shape_spec="a + a a"):
with self.assertRaisesRegex(ValueError,
"syntax error in polymorphic shape"):
shape_poly._parse_spec(shape_spec, (None,))
@parameterized.named_parameters(
dict(testcase_name=f"_{shape_spec=}",
shape_spec=shape_spec, arg_shape=arg_shape)
for shape_spec, arg_shape in [
("3", (4,)),
("b, 3", (None, 4)),
])
def test_parse_mismatch_error(self,
shape_spec="3", arg_shape=(4,)):
with self.assertRaisesRegex(ValueError,
"syntax error in polymorphic shape .* different size"):
shape_poly._parse_spec(shape_spec, arg_shape)
def test_dim_vars(self):
a, b, a1 = shape_poly._parse_spec("a, b, a", (2, 3, 2))
self.assertEqual(True, a == a)
self.assertEqual(True, a == a1)
self.assertEqual(False, a != a)
self.assertFalse(a == b)
self.assertTrue(a != b)
self.assertLen({a, a}, 1)
self.assertLen({a, b}, 2)
self.assertIn(a, {a, b})
self.assertIn(b, {a, b})
self.assertIn(a, [a, b])
self.assertIn(b, [a, b])
def test_get_vars(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertEqual({"a"}, a.get_vars())
self.assertEqual({"a", "b"}, (a * b * a).get_vars())
def test_evaluate(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertEqual(1, (a * a - b).evaluate(dict(a=2, b=3)))
self.assertEqual(1, ((a * a) // b).evaluate(dict(a=2, b=3)))
self.assertEqual(4, ((a * a) % b).evaluate(dict(a=5, b=7)))
def test_dim_vars_symbolic_equal(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertTrue(core.symbolic_equal_dim(a, a))
self.assertFalse(core.symbolic_equal_dim(a, 1))
self.assertFalse(core.symbolic_equal_dim(a, b))
self.assertTrue(core.symbolic_equal_one_of_dim(a, [2, a]))
self.assertFalse(core.symbolic_equal_one_of_dim(a, [2, b]))
self.assertFalse(core.symbolic_equal_one_of_dim(a, []))
self.assertTrue(core.symbolic_equal_one_of_dim(2, [a, 3, 2]))
self.assertFalse(core.symbolic_equal_one_of_dim(1, [2, b]))
self.assertFalse(core.symbolic_equal_one_of_dim(3, []))
self.assertTrue(core.symbolic_equal_dim(1, jnp.add(0, 1))) # A DeviceArray
with self.assertRaisesRegex(TypeError,
re.escape("Shapes must be 1D sequences of concrete values of integer type, got (1, 'a').")):
self.assertTrue(core.symbolic_equal_dim(1, "a"))
def test_poly_bounds(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
bounded_le4 = 5 - a
bounded_ge2 = b + 1
bounded_ge0_le4 = a % 5
self.assertEqual(a.bounds(), (1, np.PINF))
self.assertEqual(bounded_le4.bounds(), (np.NINF, 4))
self.assertEqual(bounded_ge2.bounds(), (2, np.PINF))
self.assertEqual(bounded_ge0_le4.bounds(), (0, 4))
# Additions
self.assertEqual((bounded_ge0_le4 + bounded_le4).bounds(), (np.NINF, 8))
self.assertEqual((bounded_ge0_le4 + bounded_ge2).bounds(), (2, np.PINF))
self.assertEqual((bounded_le4 + bounded_ge2).bounds(), (np.NINF, np.PINF))
# Subtractions
self.assertEqual((bounded_ge0_le4 - bounded_le4).bounds(), (-4, np.PINF))
self.assertEqual((- bounded_ge0_le4 + bounded_le4).bounds(), (np.NINF, 4))
self.assertEqual((bounded_ge0_le4 - bounded_ge2).bounds(), (np.NINF, 2))
self.assertEqual((- bounded_ge0_le4 + bounded_ge2).bounds(), (-2, np.PINF))
self.assertEqual((bounded_le4 - bounded_ge2).bounds(), (np.NINF, 2))
self.assertEqual((- bounded_le4 + bounded_ge2).bounds(), (-2, np.PINF))
# Multiplications
self.assertEqual((2 * a - 3).bounds(), (-1, np.PINF))
self.assertEqual((-2 * a - 3).bounds(), (np.NINF, -5))
self.assertEqual((3 * a * b * b + 5 * a - 7).bounds(), (1, np.PINF))
self.assertEqual((3 * a * b * b - 5 * a - 7).bounds(), (np.NINF, np.PINF))
self.assertEqual((a + b - a * b + a * b * a).bounds(), (np.NINF, np.PINF))
self.assertEqual((a + 2 * b - a).bounds(), (2, np.PINF))
self.assertEqual((a + 2 * b - a).bounds(), (2, np.PINF))
# mod
self.assertEqual(((b + 1) % 2).bounds(), (0, 1))
self.assertEqual(((b + 1) % -2).bounds(), (-1, 0))
self.assertEqual(((b - 4) % 2).bounds(), (0, 1))
self.assertEqual(((b + 1) % a).bounds(), (0, np.PINF))
self.assertEqual((11 % (a + 1)).bounds(), (0, np.PINF))
self.assertEqual((-11 % (a + 1)).bounds(), (0, np.PINF))
self.assertEqual((b % (a - 2)).bounds(), (np.NINF, np.PINF))
# floordiv
self.assertEqual(((a + 4) // 2).bounds(), (2, np.PINF))
self.assertEqual(((a + 4) // -2).bounds(), (np.NINF, -3))
self.assertEqual(((a + 5) // 2).bounds(), (3, np.PINF))
self.assertEqual(((a + 5) // -2).bounds(), (np.NINF, -3))
self.assertEqual((11 // (a + 1)).bounds(), (0, 5))
self.assertEqual((-11 // (a + 1)).bounds(), (-6, -1))
self.assertEqual((-11 // (- a)).bounds(), (0, 11)) # finite negative dividend, infinite divisor
self.assertEqual(((b + 1) // (a + 1)).bounds(), (0, np.PINF))
self.assertEqual((-b // (a + 1)).bounds(), (np.NINF, -1))
# Generate test cases for floordiv and mod: (a + N) // +-2, (N - a) // +-2
# and then evaluate them for a = 1, 5, 10000
div_mod_atoms = [
operation(op1 + n, div)
for op1 in (a, a + 10, a + 11, -a, -a + 10, -a + 11)
for n in (-3, -1, 0, 1, 3)
for div in (-2, 2, a + 4, -4 - a) # Either negative, or positive
for operation in (op.floordiv, op.mod)
]
for atom in div_mod_atoms:
lb, ub = atom.bounds()
self.assertLessEqual(lb, ub)
for a_val in (1, 5, 10000):
atom_val = atom.evaluate(dict(a=a_val))
self.assertGreaterEqual(atom_val, lb)
self.assertLessEqual(atom_val, ub)
# Inequalities involving mod and floordiv
self.assertEqual((5 - a % 5).bounds(), (1, 5))
self.assertEqual((-5 - a % (-5)).bounds(), (-5, -1))
self.assertEqual((a - 5 % a).bounds(), (1, np.PINF))
self.assertEqual((a - 5 % a).bounds(), (1, np.PINF))
self.assertEqual((3 * (a + b) - 5 % (3 * (a + b))).bounds(), (1, np.PINF))
self.assertEqual((- a + (b - 5) % a).bounds(), (np.NINF, -1))
def test_poly_equal(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
poly3 = a + 3 - a
self.assertTrue(poly3 == 3)
self.assertTrue(poly3 == np.array(3, np.int64))
self.assertTrue(poly3 == np.array(3, np.int64)[()])
self.assertFalse((poly3 + 1) == 3)
self.assertFalse(poly3 == poly3 + 1)
self.assertTrue((2 * a * b * a + 3).eq(1 + b * a * a + a * a * b + 2))
self.assertFalse((2 * a * b * a + 3).eq(a * b * a + 3))
self.assertFalse((a * b * a + 3).eq(a * b * a + 4))
self.assertFalse((2 * a * b * a).eq(a * b * a))
self.assertFalse((2 * a * b * a + 1).eq(a * b * a))
self.assertFalse((3 * a * b * a - 1).eq(a * b * a))
self.assertFalse((3 * a * b * a - 2).eq(a * b * a))
self.assertTrue(a % b == a % b)
self.assertTrue(a % b - a % b == 0)
self.assertTrue(a // b == a // b)
self.assertTrue(a // b - a // b == 0)
self.assertTrue(a % b == (2 * a // 2) % (a + b - a))
self.assertTrue(a // b == (2 * a // 2) // (a + b - a))
self.assertTrue(a, a + (a + b) // b - (b + a) // b)
# Test the normalization (a // b) * b == a - a % b
self.assertTrue((a // 2) * 2 == a - a % 2)
self.assertTrue((a // 2) + (a // 2) == a - a % 2)
self.assertTrue((a // 2) * 6 == 3 * a - 3 * (a % 2))
self.assertTrue((a // b) * b == a - a % b)
self.assertTrue(2 * (a // b) * b * b == 2 * b * a - 2 * b * (a % b))
self.assertTrue(a // (2 * b) * 2 * b == a - a % (2 * b))
self.assertTrue(a // (2 * b) * 2 * b + 2 * a == 3 * a - a % (2 * b))
def test_poly_compare(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
poly = 4 * a + b + 3
self.assertTrue(poly.ge(0))
self.assertTrue(poly.ge(8))
self.assertTrue(poly.ge(poly))
self.assertTrue(poly.ge(poly - 1))
with self.assertRaisesRegex(core.InconclusiveDimensionOperation, "inconclusive"):
poly.ge(9)
with self.assertRaisesRegex(core.InconclusiveDimensionOperation, "inconclusive"):
(4 * a - b).ge(0)
def test_poly_compare_overload(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
poly = 4 * a + b + 3
self.assertTrue(poly >= 0)
self.assertTrue(poly >= 8)
self.assertTrue(poly > 7)
self.assertTrue(poly >= poly)
self.assertTrue(poly >= poly - 1)
with self.assertRaisesRegex(core.InconclusiveDimensionOperation, "inconclusive"):
poly >= 9
with self.assertRaisesRegex(core.InconclusiveDimensionOperation, "inconclusive"):
(4 * a - b) >= 0
def test_core_greater_equal(self):
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertTrue(core.greater_equal_dim(a, a))
self.assertTrue(core.greater_equal_dim(a, 0))
self.assertTrue(core.greater_equal_dim(a, 1))
self.assertTrue(core.greater_equal_shape((a, 2), (1, 1)))
with self.assertRaisesRegex(core.InconclusiveDimensionOperation,
"Symbolic dimension comparison .* is inconclusive"):
core.greater_equal_dim(a, 2)
with self.assertRaisesRegex(core.InconclusiveDimensionOperation,
"Symbolic dimension comparison .* is inconclusive"):
core.greater_equal_dim(a, b)
def test_poly_int_results(self):
# Whenever the result is an integer, it should be represented as an
# Python integer, not a symbolic dimension.
a, b = shape_poly._parse_spec("a, b", (2, 3))
self.assertEqual(a + 2 - a, 2)
self.assertIsInstance(a + 2 - a, int)
self.assertEqual(a + (2 - a), 2)
self.assertIsInstance(a + (2 - a), int)
self.assertEqual(a * 2 // a, 2)
self.assertIsInstance(a * 2 // a, int)
@parameterized.named_parameters(
dict(testcase_name=f"_D={dividend}_d={divisor}_q={quotient}_r={remainder}",
dividend=dividend, divisor=divisor, quotient=quotient,
remainder=remainder)
for dividend, divisor, quotient, remainder in [
(a, 1, a, 0),
(3 * a, 3, a, 0),
(3 * a + 3, 3, a + 1, 0),
(3 * a + 2, 3, a, 2),
(3 * a + 5, 3, a + 1, 2),
(3 * a - 2, 3, a - 1, 1),
(3 * a * a * b + 2 * b * b * a, a * b, 3 * a + 2 * b, 0),
(a * a - b * b, a + b, a - b, 0),
(a, b, "floordiv(a, b)", "mod(a, b)"),
(3 * a, 2, "floordiv(3*a, 2)", "mod(3*a, 2)"),
(2 * a * b + b * b, a + b, "floordiv(2*a*b + b^2, a + b)", "mod(2*a*b + b^2, a + b)"),
(3, a, "floordiv(3, a)", "mod(3, a)"),
])
def test_poly_divmod(self, *, dividend, quotient, divisor, remainder):
if isinstance(quotient, str):
d1, d2 = divmod(dividend, divisor)
self.assertEqual((quotient, remainder), (str(d1), str(d2)))
else:
self.assertEqual((quotient, remainder), divmod(dividend, divisor))
def test_dilate_shape(self):
"""0 if d == 0 else 1 + dilation * (d - 1))"""
a, = shape_poly._parse_spec("a,", (2,))
self.assertEqual((4, 7), core.dilate_shape((2, 3), (3, 3)))
self.assertEqual((0, 7), core.dilate_shape((0, 3), (3, 3)))
self.assertEqual((a, 7), core.dilate_shape((a, 3), (1, 3)))
self.assertEqual((2 * a - 1, 7), core.dilate_shape((a, 3), (2, 3)))
def test_stride_shape(self):
"""(s - window_size) // window_stride + 1"""
a, stride = shape_poly._parse_spec("a, s", (2, 3))
self.assertEqual((8, 9), core.stride_shape((10, 20), window_size=(3, 3), window_stride=(1, 2)))
self.assertEqual((a, 9), core.stride_shape((a, 20), (1, 3), (1, 2)))
self.assertEqual((a - 1, 9), core.stride_shape((a, 20), (2, 3), (1, 2)))
self.assertEqual((a + 1, 9), core.stride_shape((a * stride + 2, 20), (2, 3), (stride, 2)))
(stride0, stride1) = core.stride_shape((a, 20), (1, 3), (2, 2))
self.assertEqual("floordiv(a + -1, 2) + 1", str(stride0))
self.assertEqual(9, stride1)
class PolyHarness(Harness):
"""Tests a function with shape polymorphism.
Converts `fun` with shape polymorphism, creates a `tf.ConcreteFunction`
given `input_signature` and checks the inferred output shapes to match
`expected_output_shapes`, then checks that the JAX and the TF functions
produce the same results.
"""
def __init__(self,
group_name: str, name: str,
fun: Callable,
*,
arg_descriptors: Sequence[primitive_harness.ArgDescriptor] = (),
polymorphic_shapes: Sequence[Optional[str]] = (),
input_signature: Optional[Sequence[tf.TensorSpec]] = None,
expected_output_signature: Optional[tf.TensorSpec] = None,
enable_xla: bool = True,
expect_error: Tuple[Optional[Any], Optional[str]] = (None, None),
skip_jax_run: bool = False,
check_result: bool = True,
tol: Optional[float] = None,
limitations: Sequence[Jax2TfLimitation] = (),
override_jax_config_flags: Dict[str, Any] = {}):
"""Args:
group_name, name: The name for the harness. See `Harness.__init__`.
fun: the function to be converted, possbily after partial application to
static arguments from `arg_descriptors`. See `Harness.__init__`.
arg_descriptors: The argument descriptors. See `Harness.__init__`. May
be missing, in which case `skip_jax_run` should be `True` and
`input_signature` must be present.
polymorphic_shapes: For `jax2tf.convert`.
input_signature: For `tf.function.get_concrete_function`. If missing,
generated from `polymorphic_shapes`.
expected_output_signature: the expected inferred output shape.
enable_xla: For `jax2tf.convert`.
expect_error: a pair of an Exception type and a regular expression to
match the expected exception string.
skip_jax_run: If True, then neither the JAX nor the TF functions are
executed.
check_result: specifies if we want to check that the result of the shape
polymorphic conversion produces the same result and the JAX function.
tol: the tolerance to use for checking results.
limitations: if given, then apply the custom_assert and tolerance from the
Jax2TfLimitations.
override_jax_config_flags: jax.config flags to override for the duration
of the test.
"""
super().__init__(group_name, name, fun, arg_descriptors,
dtype=np.float32)
self.polymorphic_shapes = polymorphic_shapes
self.input_signature = input_signature
self.expected_output_signature = expected_output_signature
self.skip_jax_run = skip_jax_run
self.expect_error = expect_error
self.enable_xla = enable_xla
self.tol = tol
self.check_result = check_result
self.limitations = limitations
self.override_jax_config_flags = override_jax_config_flags
# Replicate the harness for both enable and disable xla
def both_enable_and_disable_xla(self) -> Tuple["PolyHarness", "PolyHarness"]:
assert self.enable_xla
other = PolyHarness(self.group_name,
f"{self.name}_enable_xla=False",
self.fun,
arg_descriptors=self.arg_descriptors,
polymorphic_shapes=self.polymorphic_shapes,
input_signature=self.input_signature,
expected_output_signature=self.expected_output_signature,
expect_error=self.expect_error,
tol=self.tol,
enable_xla=False)
self.name = f"{self.name}_enable_xla=True"
return (self, other)
def run_test(self, tst: tf_test_util.JaxToTfTestCase):
def log_message(extra: str):
return f"[{tst._testMethodName}]: {extra}"
# Check that we have overriden the jax.config flags
for fname, fvalue in self.override_jax_config_flags.items():
tst.assertEqual(getattr(jax.config, fname), fvalue, (
f"Flag {fname} current value {getattr(jax.config, fname)} != {fvalue}"))
tst.assertIsNotNone(self.polymorphic_shapes)
polymorphic_shapes = self.polymorphic_shapes
if not self.skip_jax_run:
args = self.dyn_args_maker(tst.rng())
else:
tst.assertIsNotNone(self.input_signature)
if self.input_signature is None:
tst.assertEqual(
len(polymorphic_shapes), len(args),
f"polymorphic_shapes {polymorphic_shapes} of length "
f"{len(polymorphic_shapes)} must match number of arguments {len(args)}")
args_specs = jax_export.poly_specs(args, polymorphic_shapes)
input_signature = [
tf.TensorSpec(
[d if isinstance(d, int) else None for d in a.shape],
dtype=a.dtype) for a in args_specs]
else:
input_signature = self.input_signature # type: ignore
expect_error_type, expect_error_regex = self.expect_error
if self.skip_jax_run and not self.arg_descriptors:
f_jax = self.fun
else:
f_jax = self.dyn_fun
with contextlib.ExitStack() as stack:
if expect_error_type is not None:
stack.enter_context(tst.assertRaisesRegex(expect_error_type, expect_error_regex))
f_tf = jax2tf.convert(f_jax, polymorphic_shapes=polymorphic_shapes,
enable_xla=self.enable_xla)
# Run in tf.Eager mode first, because it is friendlier to debuggers
res_tf = f_tf(*args) if not self.skip_jax_run else None
f_tf_func = tf.function(
f_tf, autograph=False, input_signature=input_signature)
# Create tf.ConcreteFunction and check inferred output signature
concrete_f_tf = f_tf_func.get_concrete_function(*input_signature)
if expect_error_type is not None:
return
if self.expected_output_signature:
# Strangely, output_shapes can be a single shape for a function with a
# single result, or a list/tuple of shapes.
expected_output_signature = self.expected_output_signature
concrete_output_tf_shape = concrete_f_tf.output_shapes
if not isinstance(concrete_output_tf_shape, (tuple, list)): # Single result
assert not isinstance(self.expected_output_signature, (tuple, list))
expected_output_signature = [self.expected_output_signature]
concrete_output_tf_shape = [concrete_output_tf_shape]
for expected, found in util.safe_zip(expected_output_signature,
concrete_output_tf_shape):
tst.assertEqual(tuple(expected.shape), tuple(found))
# Run the JAX and the TF functions and compare the results
if not self.skip_jax_run:
res_jax = f_jax(*args)
if self.check_result:
res_tf = tf.nest.map_structure(lambda t: t.numpy(), res_tf) # type: ignore
custom_assert_lims = [
l for l in self.limitations if l.custom_assert is not None]
assert len(custom_assert_lims) <= 1, custom_assert_lims
tol = None
if self.tol is not None:
tol = self.tol
elif self.limitations:
max_lim = self.limitations[0].get_max_tolerance_limitation(
self.limitations)
if max_lim is not None:
tol = max_lim.tol
if not custom_assert_lims:
tst.assertAllClose(res_jax, res_tf, atol=tol, rtol=tol)
else:
logging.info(log_message(
f"Running custom_assert with tol={tol} due "
f"to {custom_assert_lims[0]}"))
custom_assert_lims[0].custom_assert(tst, res_jax, res_tf, args=args, # type: ignore
tol=tol, err_msg=None)
def check_shape_poly(tst, f_jax: Callable, *,
arg_descriptors: Sequence[primitive_harness.ArgDescriptor] = (),
skip_jax_run: bool = False,
polymorphic_shapes: Sequence[Optional[str]] = (),
input_signature: Optional[Sequence[tf.TensorSpec]] = None,
expected_output_signature: Optional[tf.TensorSpec] = None,
expect_error=(None, None)):
# Makes and tests a harness. See PolyHarness documentation.
h = PolyHarness("", "", f_jax,
arg_descriptors=arg_descriptors,
skip_jax_run=skip_jax_run,
polymorphic_shapes=polymorphic_shapes,
input_signature=input_signature,
expected_output_signature=expected_output_signature,
expect_error=expect_error)
h.run_test(tst)
class ShapePolyTest(tf_test_util.JaxToTfTestCase):
def test_simple_unary(self):
"""Test shape polymorphism for a simple case, unary function."""
def f_jax(x):
return x + jnp.sin(x)
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32)],
polymorphic_shapes=[None],
expected_output_signature=tf.TensorSpec([2, 3]))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32)],
polymorphic_shapes=["_, h"],
expected_output_signature=tf.TensorSpec([2, None]))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((3, 3), _f32)],
polymorphic_shapes=["h, h"],
expected_output_signature=tf.TensorSpec([None, None]))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((3, 3), _f32)],
polymorphic_shapes=["h, h"],
expected_output_signature=tf.TensorSpec([None, None]))
def test_simple_binary(self):
"""Test shape polymorphism for a simple case, binary function."""
def f_jax(x, y):
return x + jnp.sin(y)
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32), RandArg((2, 3), _f32)],
polymorphic_shapes=[None, None],
expected_output_signature=tf.TensorSpec([2, 3]))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32), RandArg((2, 3), _f32)],
polymorphic_shapes=["_, h", "_, h"],
input_signature=[tf.TensorSpec([2, None]), tf.TensorSpec([2, 3])],
expected_output_signature=(
# for native serialization we cannot refine the inferred shape of the
# output if the input is more specific than polymorphic_shapes.
tf.TensorSpec([2, 3]) if not config.jax2tf_default_native_serialization
else tf.TensorSpec([2, None])))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((3, 3), _f32), RandArg((3, 3), _f32)],
polymorphic_shapes=["h, h", "h, h"],
expected_output_signature=tf.TensorSpec([None, None]))
@jtu.parameterized_filterable(
# make_args invoked with op.shape[0]: start, stop, step, dtype
kwargs=[
dict(testcase_name="b", make_args=lambda b: (b, None, None, None)),
dict(testcase_name="0_b+1", make_args=lambda b: (0, b + 1, None, None)),
dict(testcase_name="0_5b_2", make_args=lambda b: (0, 5 * b, 2, None)),
dict(testcase_name="0_5b+1_2", make_args=lambda b: (0, 5 * b + 1, 2, None)),
dict(testcase_name="b_5b+2_2", make_args=lambda b: (b, 5 * b + 2, 2, None)),
dict(testcase_name="0_b-1_2", make_args=lambda b: (0, b - 1, 2, None)),
dict(testcase_name="0_b-2_2", make_args=lambda b: (0, b - 2, 2, None)),
dict(testcase_name="0_-b_2", make_args=lambda b: (0, -b, 2, None)),
dict(testcase_name="0_1-b_2", make_args=lambda b: (0, 1 - b, 2, None)),
# Negative step
dict(testcase_name="b_0_-1", make_args=lambda b: (b, 0, -1, None)),
dict(testcase_name="b_1_-2", make_args=lambda b: (b, 1, -2, None)),
dict(testcase_name="b_-1_-1", make_args=lambda b: (b, -1, -1, None)),
dict(testcase_name="5b+1_0_-2", make_args=lambda b: (5 * b + 1, 0, -2, None)),
dict(testcase_name="5b+2_0_-2", make_args=lambda b: (5 * b + 2, 0, -2, None)),
# Symbolic step
dict(testcase_name="0_10_b", make_args=lambda b: (0, 10, b)),
dict(testcase_name="0_0_b", make_args=lambda b: (0, 0, b)),
dict(testcase_name="10_0_-b", make_args=lambda b: (10, 0, -b)),
dict(testcase_name="b_1_-b", make_args=lambda b: (b, 1, -b)),
# Float return type
dict(testcase_name="0_b_1_f32", make_args=lambda b: (0, b, 1, np.float32))
])
def test_arange(self, make_args):
def f_jax(x): # x: i32[b]
return x[0] + jnp.arange(*(make_args(x.shape[0])))
x = np.ones((3,), dtype=np.int32)
self.assertAllClose(jax2tf.convert(f_jax, polymorphic_shapes="b")(x),
f_jax(x))
@jtu.parameterized_filterable(
# make_args invoked with op.shape[0]: start, stop, step, dtype
kwargs=[
dict(testcase_name=name, make_args=make_args, expect_error=expect_error, expect_msg=expect_msg)
for name, make_args, expect_error, expect_msg in [
# make_args invoked with op.shape[0]: start, stop, step, dtype
("float_start", lambda b: (0., b, None),
ValueError, "must be either dimension expressions or integers"),
("float_step", lambda b: (0, b, 0.5),
ValueError, "must be either dimension expressions or integers"),
("step_0", lambda b: (0, b, 0),
ValueError, "has step == 0"),
("inconclusive_step_sign", lambda b: (0, b, b - 2),
core.InconclusiveDimensionOperation,
"must be resolved statically if it is > 0 or < 0"),
("inconclusive_distance", lambda b: (0, b - 3, 2),
core.InconclusiveDimensionOperation,
"must be resolved statically if it is >= -1 or >= 1"),
]
]
)
def test_arange_error(self, make_args=lambda b: (0., b, 2),
expect_error=ValueError,
expect_msg="must be either dimension expressions or integers"):
def f_jax(x): # x: i32[b]
return x[0] + jnp.arange(*(make_args(x.shape[0])))
x = np.ones((3,), dtype=np.int32)
with self.assertRaisesRegex(expect_error, expect_msg):
jax2tf.convert(f_jax, polymorphic_shapes="b")(x)
def test_argmax(self):
def f_jax(x): # x: f32[b, 4, 5]
return lax.argmax(x, axis=1, index_dtype=np.int32)
x = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
self.assertAllClose(jax2tf.convert(f_jax, polymorphic_shapes="(b, _, _)")(x),
f_jax(x))
@jtu.parameterized_filterable(
kwargs=[
dict(testcase_name=f"expr={name}", expr=expr)
for name, expr in [
("d + 2", lambda d: d + 2),
("2 - d", lambda d: 2 - d),
("d * 2", lambda d: d * 2),
("d * d", lambda d: d * d),
("(- d) * d", lambda d: (- d) * d),
("d * d - d", lambda d: d * d - d),
# Division
("d // 2", lambda d: d // 2),
("(d + 1) // 2", lambda d: (d + 1) // 2),
("d // -2", lambda d: d // -2),
("(d + 1) // -2", lambda d: (d + 1) // -2),
("(-d) // 2", lambda d: (-d) // 2),
("(-d - 1) // 2", lambda d: (-d - 1) // 2),
("(-d) // -2", lambda d: (-d) // -2),
("(-d - 1) // -2", lambda d: (-d - 1) // -2),
# Remainder
("d % 2", lambda d: d % 2),
("(d + 1) % 2", lambda d: (d + 1) % 2),
("d % -2", lambda d: d % -2),
("(d + 1) % -2", lambda d: (d + 1) % -2),
("(-d) % 2", lambda d: (-d) % 2),
("(-d - 1) % 2", lambda d: (-d - 1) % 2),
("(-d) % -2", lambda d: (-d) % -2),
("(-d - 1) % -2", lambda d: (-d - 1) % -2),
]
])
def test_non_trivial_dim_expr(self, expr=lambda d: d % -2):
# Check the lowering for shape expressions
check_shape_poly(
self,
lambda x: x[0] * 0 + expr(x.shape[0]),
arg_descriptors=[RandArg((3,), np.int64)],
polymorphic_shapes=["b"])
def test_static_shape_result(self):
"""The result has static shape."""
def f_jax(x):
return jnp.sum(x + jnp.sin(x), axis=0)
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32)],
polymorphic_shapes=[None],
expected_output_signature=tf.TensorSpec([3]))
check_shape_poly(self,
f_jax,
arg_descriptors=[RandArg((2, 3), _f32)],
polymorphic_shapes=["b, _"],
expected_output_signature=tf.TensorSpec([3]))
def test_forgot_polymorphic_shapes_error(self):
msg_re = "syntax error in polymorphic shape"
with self.assertRaisesRegex(ValueError, msg_re):
check_shape_poly(self,
jnp.sin,
arg_descriptors=[RandArg((1, 3,), _f32)],
input_signature=[tf.TensorSpec([1, None])],
polymorphic_shapes=[None])
def test_kwargs(self):
"""Test shape polymorphism for a function with kwargs."""
x = np.ones(3, dtype=np.float32)
y = np.ones(1, dtype=np.float32)
def f_jax(x, *, y):
return x + jnp.sin(y)
f_tf: Callable[..., Any] = jax2tf.convert(f_jax, polymorphic_shapes=["b, ..."])
self.assertAllClose(f_jax(x, y=y), f_tf(x, y=y))
def test_arg_avals_non_native(self):
"""Test conversion of actual arguments to abstract values."""
def check_avals(*, arg_shapes: Sequence[Sequence[Optional[int]]],
polymorphic_shapes: Sequence[Optional[Union[str, PS]]],
expected_avals: Optional[Sequence[core.ShapedArray]] = None,
expected_shapeenv: Optional[Dict[str, int]] = None,
eager_mode: bool = False):
# Use eager mode only for when all arg_shapes are known, in order to
# check expected_shapeenv.
arg_dtypes = (_f32,) * len(arg_shapes)
def f_tf(*args_tf):
avals = tuple(map(shape_poly.arg_aval, arg_shapes, arg_dtypes, polymorphic_shapes))
dim_vars = shape_poly.all_dim_vars(avals)
dim_values, _ = jax2tf.jax2tf._interpret_fun_jax(
partial(shape_poly.compute_dim_vars_from_arg_shapes,
avals,
args_kwargs_tree=tree_util.tree_flatten((avals, {}))[1]),
args_tf, avals, "")
if expected_avals is not None:
self.assertEqual(expected_avals, avals)
return dict(zip(dim_vars, dim_values))
if eager_mode:
# If we want to check the shape_env then all arg_shapes must be known
assert all(all(d is not None for d in a_s)
for a_s in arg_shapes)
shape_env = f_tf(*[tf.ones(a_s, dtype=_f32) for a_s in arg_shapes])
if expected_shapeenv is not None:
for v, val in expected_shapeenv.items():
self.assertEqual(val, shape_env.get(v))
else:
f_tf = tf.function(autograph=False)(f_tf)
f_tf.get_concrete_function(*[tf.TensorSpec(a_s, _f32)
for a_s in arg_shapes])
assert not expected_shapeenv, "Should use eager_mode=True"
def shaped_array(shape_spec: str, actual_shape: core.Shape):
return core.ShapedArray(
shape_poly._parse_spec(shape_spec, actual_shape), np.float32)
# Known shapes for the arguments
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=[None],
expected_avals=(shaped_array("2, 3", [2, 3]),))
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=["(2, 3)"],
expected_avals=(shaped_array("2, 3", [2, 3]),))
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=["(_, 3)"],
expected_avals=(shaped_array("2, 3", [2, 3]),))
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=[PS("_", 3)],
expected_avals=(shaped_array("2, 3", [2, 3]),))
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=["..."],
expected_avals=(shaped_array("2, 3", [2, 3]),))
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=[PS(...)],
expected_avals=(shaped_array("2, 3", [2, 3]),))
# Partially known shapes for the arguments
check_avals(
arg_shapes=[(None, 3)],
polymorphic_shapes=[PS("b", ...)],
expected_avals=(shaped_array("(b, 3)", (2, 3)),))
check_avals(
arg_shapes=[(None, None)],
polymorphic_shapes=["h, h"],
expected_avals=(shaped_array("(h, h)", (2, 2)),))
check_avals(
arg_shapes=[(2, None)],
polymorphic_shapes=["h, h"],
expected_avals=(shaped_array("(h, h)", (2, 2)),))
check_avals(
arg_shapes=[(None, 3, 4)],
polymorphic_shapes=["(c, b, a)"],
expected_avals=(shaped_array("(c, b, a)", (2, 3, 4)),),
)
# Check cases when the specifications are polynomials
check_avals(
arg_shapes=[(2, 3)],
polymorphic_shapes=[PS("a + 1", "b + 2")],
eager_mode=True,
expected_shapeenv=dict(a=1, b=1))
check_avals(
arg_shapes=[(7, 5)],
polymorphic_shapes=[PS("2 * a + b", "b + 2")],
eager_mode=True,
expected_shapeenv=dict(a=2, b=3))
check_avals(
arg_shapes=[(7, 11, 4)],
polymorphic_shapes=[PS("2 * a + b", "b * b + 2", "b + 1")],
eager_mode=True,
expected_shapeenv=dict(a=2, b=3))
check_avals(
arg_shapes=[(7, 11, 19, 7)],
polymorphic_shapes=[PS("2 * a + b", "b * b + 2", "b + c * c", "2 * c + -1")],
eager_mode=True,
expected_shapeenv=dict(a=2, b=3, c=4))
def test_arg_avals_errors(self):
"""Test error reporting for shape polymorpish."""
def conv_and_run(*, arg_shape: core.Shape,
polymorphic_shape: str):
arg = np.arange(math.prod(arg_shape), dtype=np.float32).reshape(arg_shape)
jax2tf.convert(lambda x: x, polymorphic_shapes=[polymorphic_shape])(arg)
with self.assertRaisesRegex(ValueError,
re.escape("polymorphic shape spec should be")):
conv_and_run(arg_shape=(2,), polymorphic_shape=5.)
with self.assertRaisesRegex(ValueError,
re.escape("pytree structure error: different types")):
conv_and_run(arg_shape=(2,), polymorphic_shape=["a list"])
with self.assertRaisesRegex(ValueError,
re.escape("pytree structure error: different types")):
conv_and_run(arg_shape=(2,), polymorphic_shape=("a tuple",))
# The following do not work yet with native serialization because
# XlaCallModule does not yet do shape checking.
if config.jax2tf_default_native_serialization:
return
# TODO(necula): enable even for native serialization
with self.assertRaisesRegex(ValueError,
"Cannot solve for values of dimension variables {'b'}"):
conv_and_run(arg_shape=(4, 36, 3), polymorphic_shape="b * b, b * d * d, d")
# TODO(necula): enable even for native serialization
with self.assertRaisesRegex(ValueError,
"Dimension variable 'b' must have integer value >= 1"):
conv_and_run(arg_shape=(5, 36), polymorphic_shape="3 * b, ...")
# TODO(necula): enable even for native serialization
with self.assertRaisesRegex(ValueError,
"Dimension variable 'b' must have integer value >= 1"):
conv_and_run(arg_shape=(10, 3), polymorphic_shape="3 * b + 10, ...")
# TODO(necula): enable even for native serialization
with self.assertRaisesRegex(ValueError,
"Dimension variable 'b' must have integer value >= 1"):
conv_and_run(arg_shape=(7, 3), polymorphic_shape="3 * b + 10, ...")
# TODO(necula): enable even for native serialization
with self.assertRaisesRegex(
ValueError,
"Found inconsistency 3 != 2 when solving.*"):
conv_and_run(arg_shape=(2, 3), polymorphic_shape="(a, a)")
def test_pytree(self):
"""Arguments and polymorphic_shapes are pytrees."""
# Arguments are of the form [([x00, x01], [x10]), dict(a=ya, b=yb)]
def add_all_jax(x_pair_of_list, y_dict):
x_list_0, x_list_1 = x_pair_of_list
return functools.reduce(op.add,
x_list_0 + x_list_1 + [y_dict["a"], y_dict["b"]])
input_signature = [([tf.TensorSpec([None]), tf.TensorSpec([None])],
[tf.TensorSpec([None])]),
dict(a=tf.TensorSpec([None]),
b=tf.TensorSpec([None]))]
check_shape_poly(self,
add_all_jax,
skip_jax_run=True,
input_signature=input_signature,
polymorphic_shapes=[(["v", "v"], ["v"]),
dict(a="v", b="v")],
expected_output_signature=tf.TensorSpec([None]))
# Prefix polymorphic shapes
check_shape_poly(self,
add_all_jax,
skip_jax_run=True,
input_signature=input_signature,
polymorphic_shapes="v",
expected_output_signature=tf.TensorSpec([None]))
check_shape_poly(self,
add_all_jax,
skip_jax_run=True,
input_signature=input_signature,
polymorphic_shapes=["v", "v"],
expected_output_signature=tf.TensorSpec([None]))