/
array_ops_test.py
2461 lines (2070 loc) · 91.1 KB
/
array_ops_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 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for array_ops."""
import re
import time
import unittest
from absl.testing import parameterized
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import test_ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gradient_checker_v2
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import list_ops
from tensorflow.python.ops import map_fn
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.ragged.ragged_tensor import RaggedTensor
from tensorflow.python.platform import test as test_lib
@test_util.run_all_in_graph_and_eager_modes
class BatchMatrixTransposeTest(test_util.TensorFlowTestCase):
def testNonBatchMatrix(self):
matrix = [[1, 2, 3], [4, 5, 6]] # Shape (2, 3)
expected_transposed = [[1, 4], [2, 5], [3, 6]] # Shape (3, 2)
transposed = array_ops.matrix_transpose(matrix)
self.assertEqual((3, 2), transposed.get_shape())
self.assertAllEqual(expected_transposed, transposed)
def testConjugate(self):
m = [[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]]
expected_transposed = [[1 - 1j, 4 - 4j], [2 - 2j, 5 - 5j], [3 - 3j, 6 - 6j]]
matrix = ops.convert_to_tensor(m)
transposed = array_ops.matrix_transpose(matrix, conjugate=True)
self.assertEqual((3, 2), transposed.get_shape())
self.assertAllEqual(expected_transposed, transposed)
def testBatchMatrix(self):
matrix_0 = [[1, 2, 3], [4, 5, 6]]
matrix_0_t = [[1, 4], [2, 5], [3, 6]]
matrix_1 = [[11, 22, 33], [44, 55, 66]]
matrix_1_t = [[11, 44], [22, 55], [33, 66]]
batch_matrix = [matrix_0, matrix_1] # Shape (2, 2, 3)
expected_transposed = [matrix_0_t, matrix_1_t] # Shape (2, 3, 2)
transposed = array_ops.matrix_transpose(batch_matrix)
self.assertEqual((2, 3, 2), transposed.get_shape())
self.assertAllEqual(expected_transposed, transposed)
def testNonBatchMatrixDynamicallyDefined(self):
# needs explicit `constant` because lists are not automatically
# converted to sensors when applying `transpose` below
matrix = constant_op.constant([[1, 2, 3], [4, 5, 6]]) # Shape (2, 3)
expected_transposed = [[1, 4], [2, 5], [3, 6]] # Shape (3, 2)
@def_function.function(input_signature=[
tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32)
])
def transpose(matrix):
self.assertIs(matrix.shape.ndims, None)
return array_ops.matrix_transpose(matrix)
self.assertAllEqual(expected_transposed, transpose(matrix))
def testBatchMatrixDynamicallyDefined(self):
matrix_0 = [[1, 2, 3], [4, 5, 6]]
matrix_0_t = [[1, 4], [2, 5], [3, 6]]
matrix_1 = [[11, 22, 33], [44, 55, 66]]
matrix_1_t = [[11, 44], [22, 55], [33, 66]]
# needs explicit `constant` because lists are not automatically
# converted to sensors when applying `transpose` below
batch_matrix = constant_op.constant([matrix_0, matrix_1]) # Shape (2, 2, 3)
expected_transposed = [matrix_0_t, matrix_1_t] # Shape (2, 3, 2)
@def_function.function(input_signature=[
tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32)
])
def transpose(matrix):
self.assertIs(matrix.shape.ndims, None)
return array_ops.matrix_transpose(matrix)
self.assertAllEqual(expected_transposed, transpose(batch_matrix))
def testTensorWithStaticRankLessThanTwoRaisesBecauseNotAMatrix(self):
vector = [1, 2, 3]
with self.assertRaisesRegex(ValueError, "should be a "):
array_ops.matrix_transpose(vector)
def testNarrowMatrixConjugateTranspose(self):
for dtype in (dtypes.float32, dtypes.float64):
for conjugate in (True, False):
with self.subTest(complex_type=dtype, conjugate=conjugate):
vector = math_ops.complex(
constant_op.constant(0, dtype=dtype),
math_ops.range(96, dtype=dtype))
column_vector = array_ops.expand_dims(vector, axis=-1)
row_vector = array_ops.expand_dims(vector, axis=0)
narrow_matrix = array_ops.tile(column_vector, [1, 2]) # [96, 2]
expected_transposed = array_ops.tile(row_vector, [2, 1]) # [2, 96]
if conjugate:
expected_transposed = -expected_transposed
transposed = array_ops.matrix_transpose(
narrow_matrix, conjugate=conjugate)
self.assertEqual((2, 96), transposed.get_shape())
self.assertAllEqual(expected_transposed, transposed)
class BooleanMaskTest(test_util.TensorFlowTestCase):
def setUp(self):
self.rng = np.random.RandomState(42)
def CheckVersusNumpy(self, ndims_mask, arr_shape, make_mask=None, axis=None):
"""Check equivalence between boolean_mask and numpy masking."""
if make_mask is None:
make_mask = lambda shape: self.rng.randint(0, 2, size=shape).astype(bool)
arr = np.random.rand(*arr_shape)
mask = make_mask(arr_shape[:ndims_mask])
if axis is not None:
mask = make_mask(arr_shape[axis:ndims_mask + axis])
if axis is None or axis == 0:
masked_arr = arr[mask]
elif axis == 1:
masked_arr = arr[:, mask]
elif axis == 2:
masked_arr = arr[:, :, mask]
masked_tensor = array_ops.boolean_mask(arr, mask, axis=axis)
# Leading dimension size of masked_tensor is always unknown until runtime
# since we don't how many elements will be kept.
leading = 1 if axis is None else axis + 1
self.assertAllEqual(masked_tensor.get_shape()[leading:],
masked_arr.shape[leading:])
self.assertAllClose(masked_arr, masked_tensor)
def testMaskDim1ArrDim2Axis1(self):
ndims_mask = 1
for arr_shape in [(1, 1), (2, 2), (2, 5)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape, axis=1)
def testMaskDim2ArrDim2Axis1(self):
ndims_mask = 2
for arr_shape in [(1, 1), (2, 2), (2, 5)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape, axis=1)
def testMaskDim1ArrDim1(self):
ndims_mask = 1
for arr_shape in [(1,), (2,), (3,), (10,)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape)
def testMaskDim1ArrDim2(self):
ndims_mask = 1
for arr_shape in [(1, 1), (2, 2), (2, 5)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape)
def testMaskDim2ArrDim2(self):
ndims_mask = 2
for arr_shape in [(1, 1), (2, 2), (2, 5)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape)
def testMaskDim2ArrDim3(self):
ndims_mask = 2
for arr_shape in [(1, 1, 1), (1, 2, 2), (2, 2, 1)]:
with self.subTest(arr_shape=arr_shape):
self.CheckVersusNumpy(ndims_mask, arr_shape)
def testEmptyInput2D(self):
mask = np.array([True, False])
arr = np.array([[], []]).astype(np.float32)
numpy_result = arr[mask]
tf_result = array_ops.boolean_mask(arr, mask)
self.assertAllEqual(numpy_result.shape[1:], tf_result.get_shape()[1:])
with self.cached_session():
self.assertAllClose(numpy_result, tf_result)
def testEmptyInput1D(self):
mask = np.array([]).astype(bool)
arr = np.array([]).astype(np.float32)
numpy_result = arr[mask]
tf_result = array_ops.boolean_mask(arr, mask)
self.assertAllEqual(numpy_result.shape[1:], tf_result.get_shape()[1:])
with self.cached_session():
self.assertAllClose(numpy_result, tf_result)
def testEmptyOutput(self):
make_mask = lambda shape: np.zeros(shape, dtype=bool)
for ndims_mask in range(1, 4):
for ndims_arr in range(ndims_mask, ndims_mask + 3):
for _ in range(3):
with self.subTest(ndims_mask=ndims_mask, ndims_arr=ndims_arr, _=_):
arr_shape = np.random.randint(1, 5, size=ndims_arr)
self.CheckVersusNumpy(ndims_mask, arr_shape, make_mask=make_mask)
def testWorksWithDimensionsEqualToNoneDuringGraphBuild(self):
# The rank of the mask tensor must be specified. This is explained
# in the docstring as well.
@def_function.function
def func(ph_tensor, ph_mask):
return array_ops.boolean_mask(ph_tensor, ph_mask)
f = func.get_concrete_function(
tensor_spec.TensorSpec(None, dtypes.int32),
tensor_spec.TensorSpec([None], dtypes.bool))
arr = np.array([[1, 2], [3, 4]], np.int32)
mask = np.array([False, True])
masked_tensor = f(arr, mask)
self.assertAllEqual(masked_tensor, arr[mask])
def testMaskDimensionsSetToNoneRaises(self):
# The rank of the mask tensor must be specified. This is explained
# in the docstring as well.
@def_function.function
def func(tensor, mask):
return array_ops.boolean_mask(tensor, mask)
with self.assertRaisesRegex(ValueError, "dimensions must be specified"):
_ = func.get_concrete_function(
tensor_spec.TensorSpec([None, 2], dtypes.int32),
tensor_spec.TensorSpec(None, dtypes.bool))
def testMaskHasMoreDimsThanTensorRaises(self):
mask = [[True, True], [False, False]]
tensor = [1, 2, 3, 4]
with self.cached_session():
with self.assertRaisesRegex(ValueError, "incompatible"):
self.evaluate(array_ops.boolean_mask(tensor, mask))
def testMaskIsScalarRaises(self):
mask = True
tensor = 1
with self.cached_session():
with self.assertRaisesRegex(ValueError, "mask.*scalar"):
self.evaluate(array_ops.boolean_mask(tensor, mask))
def testMaskShapeDifferentThanFirstPartOfTensorShapeRaises(self):
mask = [True, True, True]
tensor = [[1, 2], [3, 4]]
with self.cached_session():
with self.assertRaisesRegex(ValueError, "incompatible"):
self.evaluate(array_ops.boolean_mask(tensor, mask))
def testStringMask(self):
# Reproduces b/111171330, where the optimized boolean_mask graph would
# be incorrectly placed on GPU.
config.set_optimizer_experimental_options({"shape_optimization": True})
@def_function.function
def func(tile_input):
string_tensor = array_ops.tile([["hello"]], tile_input)
bool_tensor = array_ops.tile([[True]], tile_input)
masked_tensor = array_ops.boolean_mask(string_tensor, bool_tensor)
return masked_tensor
result = func([2, 2])
self.assertAllEqual([b"hello", b"hello", b"hello", b"hello"], result)
def testMaskWithAxisTensor(self):
@def_function.function(autograph=False)
def f():
return array_ops.boolean_mask([1, 2, 3], [True, False, True],
axis=constant_op.constant(
0, dtype=dtypes.int32))
self.assertAllEqual(self.evaluate(f()), [1, 3])
def testMaskWithAxisNonConstTensor(self):
@def_function.function(
autograph=False,
input_signature=[
tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32)
])
def f(axis):
return array_ops.boolean_mask([1, 2, 3], [True, False, True], axis=axis)
self.assertAllEqual(
self.evaluate(f(constant_op.constant(0, dtype=dtypes.int32))), [1, 3])
@test_util.run_all_in_graph_and_eager_modes
class OperatorShapeTest(test_util.TensorFlowTestCase):
def testExpandScalar(self):
scalar = "hello"
scalar_expanded = array_ops.expand_dims(scalar, [0])
self.assertEqual(scalar_expanded.get_shape(), (1,))
def testSqueezeScalar(self):
scalar = "hello"
scalar_squeezed = array_ops.squeeze(scalar, ())
self.assertEqual(scalar_squeezed.get_shape(), ())
def testSqueezeMatrix(self):
matrix = [[1, 2, 3]]
matrix_squeezed = array_ops.squeeze(matrix, [0])
self.assertEqual(matrix_squeezed.get_shape(), (3))
with self.assertRaisesRegex(
Exception, "Can not squeeze dim.1., expected a dimension of 1, got 3"):
matrix_squeezed = array_ops.squeeze(matrix, [1])
def testSqueezeScalarDim(self):
matrix = [[1, 2, 3]]
matrix_squeezed = array_ops.squeeze(matrix, 0)
self.assertEqual(matrix_squeezed.get_shape(), (3))
def testExpandDimsWithNonScalarDim(self):
with self.assertRaisesRegex(Exception,
"must be a tensor with a single value"):
array_ops.expand_dims(1, axis=[0, 1])
def testReshapeWithManyDims(self):
with self.assertRaisesRegex(errors.InvalidArgumentError,
"too many dimensions"):
self.evaluate(
array_ops.reshape(
tensor=[[1]],
shape=constant_op.constant([1 for i in range(254)],
dtype=dtypes.int64)))
@test_util.with_eager_op_as_function
class ReverseV2Test(test_util.TensorFlowTestCase):
def testReverse0DimAuto(self):
x_np = 4
for use_gpu in [False, True]:
with self.subTest(use_gpu=use_gpu):
with self.cached_session(use_gpu=use_gpu):
x_tf = self.evaluate(array_ops.reverse_v2(x_np, []))
self.assertAllEqual(x_tf, x_np)
def _reverse1DimAuto(self, np_dtype):
x_np = np.array([1, 200, 3, 40, 5], dtype=np_dtype)
for use_gpu in [False, True]:
for axis_dtype in [dtypes.int32, dtypes.int64]:
with self.subTest(use_gpu=use_gpu, axis_dtype=axis_dtype):
x_tf = self.evaluate(
array_ops.reverse_v2(x_np,
constant_op.constant([0], dtype=axis_dtype)))
self.assertAllEqual(x_tf, np.asarray(x_np)[::-1])
def _reverse2DimAuto(self, np_dtype):
x_np = np.array([[1, 200, 3], [4, 5, 60]], dtype=np_dtype)
for reverse_f in [array_ops.reverse_v2, array_ops.reverse]:
for use_gpu in [False, True]:
for axis_dtype in [dtypes.int32, dtypes.int64]:
with self.subTest(
reverse_f=reverse_f, use_gpu=use_gpu, axis_dtype=axis_dtype):
x_tf_1 = self.evaluate(
reverse_f(x_np, constant_op.constant([0], dtype=axis_dtype)))
x_tf_2 = self.evaluate(
reverse_f(x_np, constant_op.constant([-2], dtype=axis_dtype)))
x_tf_3 = self.evaluate(
reverse_f(x_np, constant_op.constant([1], dtype=axis_dtype)))
x_tf_4 = self.evaluate(
reverse_f(x_np, constant_op.constant([-1], dtype=axis_dtype)))
x_tf_5 = self.evaluate(
reverse_f(x_np, constant_op.constant([1, 0], dtype=axis_dtype)))
self.assertAllEqual(x_tf_1, np.asarray(x_np)[::-1, :])
self.assertAllEqual(x_tf_2, np.asarray(x_np)[::-1, :])
self.assertAllEqual(x_tf_3, np.asarray(x_np)[:, ::-1])
self.assertAllEqual(x_tf_4, np.asarray(x_np)[:, ::-1])
self.assertAllEqual(x_tf_5, np.asarray(x_np)[::-1, ::-1])
# This test covers the axis validation in the shape function
# (no eval())
def testInvalidAxis(self):
x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"is out of.* range"):
array_ops.reverse_v2(x_np, [-30])
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"is out of.* range"):
array_ops.reverse_v2(x_np, [2])
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
r"axis 0 specified more than once|axis 0 was repeated"):
array_ops.reverse_v2(x_np, [0, -2])
# This is the version of reverse that uses axis indices rather than
# bool tensors
# TODO(b/32254538): Change this test to use array_ops.reverse
#
# Note: this test passes placeholder as constant axis is validated
# in shape function (see testInvalidAxis)
def testInvalid(self):
x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
@def_function.function
def func(ax):
return array_ops.reverse_v2(x_np, ax)
with self.assertRaisesRegex((ValueError, errors_impl.InvalidArgumentError),
"is out of.*range"):
func([-30])
with self.assertRaisesRegex((ValueError, errors_impl.InvalidArgumentError),
"is out of.*range"):
func([2])
with self.assertRaisesRegex(
(ValueError, errors_impl.InvalidArgumentError),
"(axis 0 specified more than once|canonicalized axis 0 was repeated.)"):
func([0, -2])
def testReverse1DimAuto(self):
for dtype in [
np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64,
np.int64, np.bool_, np.float16, np.float32, np.float64, np.complex64,
np.complex128,
np.array(b"").dtype.type
]:
self._reverse1DimAuto(dtype)
def testReverse2DimAuto(self):
for dtype in [
np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64,
np.int64, np.bool_, np.float16, np.float32, np.float64, np.complex64,
np.complex128,
np.array(b"").dtype.type
]:
self._reverse2DimAuto(dtype)
def testReverseRowsOf3Channels(self):
"""Tests optimized code for reversing rows with last dim size = 3."""
for reverse_f in [array_ops.reverse_v2, array_ops.reverse]:
for outer_size in (1, 2):
for middle_size in list(range(50)) + [100000]:
with self.subTest(
reverse_f=reverse_f,
outer_size=outer_size,
middle_size=middle_size,
use_gpu=True):
x_np = np.reshape(
np.arange(outer_size * middle_size * 3, dtype=np.float32),
newshape=(outer_size, middle_size, 3))
x_tf = self.evaluate(reverse_f(x_np, [1]))
np_answer = x_np[:, ::-1, :]
self.assertAllEqual(x_tf, np_answer)
def testReverseRowsOf4Channels(self):
for reverse_f in [array_ops.reverse_v2, array_ops.reverse]:
for outer_size in (1, 2):
for middle_size in list(range(50)) + [100000]:
with self.subTest(
reverse_f=reverse_f,
outer_size=outer_size,
middle_size=middle_size,
use_gpu=True):
x_np = np.reshape(
np.arange(outer_size * middle_size * 4, dtype=np.float32),
newshape=(outer_size, middle_size, 4))
x_tf = self.evaluate(reverse_f(x_np, [1]))
np_answer = x_np[:, ::-1, :]
self.assertAllEqual(x_tf, np_answer)
def testReverseColumnsOf3Channels(self):
for reverse_f in [array_ops.reverse_v2, array_ops.reverse]:
for outer_size in list(range(50)) + [100000]:
for middle_size in (1, 2):
with self.subTest(
reverse_f=reverse_f,
outer_size=outer_size,
middle_size=middle_size,
use_gpu=True):
x_np = np.reshape(
np.arange(outer_size * middle_size * 3, dtype=np.float32),
newshape=(outer_size, middle_size, 3))
x_tf = self.evaluate(reverse_f(x_np, [0]))
np_answer = x_np[::-1, :, :]
self.assertAllEqual(x_tf, np_answer)
def testReverseInvalidShape(self):
x = np.ndarray(shape=[0, 1, 1])
v = array_ops.reverse_v2(x, axis=[1])
self.assertAllEqual(self.evaluate(v), v)
class MeshgridTest(test_util.TensorFlowTestCase):
def _compareDiff(self, x, y, use_gpu):
for index in ("ij", "xy"):
numpy_out = np.meshgrid(x, y, indexing=index)
tf_out = array_ops.meshgrid(x, y, indexing=index)
with self.cached_session(use_gpu=use_gpu):
for xx, yy in zip(numpy_out, tf_out):
self.assertAllEqual(xx, yy)
def _compareDiffType(self, n, np_dtype, use_gpu):
inputs = []
for index in ("ij", "xy"):
for _ in range(n):
x = np.linspace(-10, 10, 5).astype(np_dtype)
if np_dtype in (np.complex64, np.complex128):
x += 1j
inputs.append(x)
numpy_out = np.meshgrid(*inputs, indexing=index)
with test_util.device(use_gpu=use_gpu):
tf_out = array_ops.meshgrid(*inputs, indexing=index)
for x_np, x_tf in zip(numpy_out, tf_out):
self.assertAllEqual(x_np, x_tf)
def testCompare(self):
for t in (np.float16, np.float32, np.float64, np.int32, np.int64,
np.complex64, np.complex128):
with self.subTest(t=t):
self._compareDiffType(2, t, False)
self._compareDiffType(3, t, False)
x = [1, 2, 3]
y = [4, 5]
a = [[1, 1], [1, 1]]
self._compareDiff(x, y, False)
self._compareDiff(x, a, False)
class StridedSliceChecker(object):
"""Check a given tensor against the numpy result."""
REF_TENSOR = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3)
REF_TENSOR_ALIGNED = np.arange(1, 97, dtype=np.float32).reshape(3, 4, 8)
def __init__(self, test, x, tensor_type=dtypes.int32, check_type_infer=True):
self.x_np = np.array(x).astype(tensor_type.as_numpy_dtype)
if tensor_type.is_bool:
self.x_np = np.array(x % 3).astype(np.bool_)
# Give the value a non-zero imaginary component for complex types.
if tensor_type.is_complex:
self.x_np -= 1j * self.x_np
self.test = test
self.x = constant_op.constant(self.x_np, dtype=tensor_type)
self.check_type_infer = check_type_infer
def __getitem__(self, spec):
op = self.x.__getitem__(spec)
def eval_if_tensor(x):
try:
return self.test.evaluate(x)
except (AttributeError, TypeError, ValueError):
return x
def casts_to_bool_nparray(x):
try:
return np.asarray(x).dtype == bool
except NotImplementedError:
return False
if isinstance(spec, bool) or \
(isinstance(spec, ops.Tensor) and spec.dtype == dtypes.bool) or \
(isinstance(spec, np.ndarray) and spec.dtype == bool) or \
(isinstance(spec, (list, tuple)) and casts_to_bool_nparray(spec)):
tensor = self.test.evaluate(op)
np_spec = eval_if_tensor(spec)
self.test.assertAllEqual(self.x_np[np_spec], tensor)
return tensor
if not isinstance(spec, (list, tuple)):
spec = [spec]
tensor = self.test.evaluate(op)
# Make a numpy spec that pre-evals the tensors
np_specs = []
for s in spec:
if isinstance(s, slice):
start = eval_if_tensor(s.start)
stop = eval_if_tensor(s.stop)
step = eval_if_tensor(s.step)
np_specs.append(slice(start, stop, step))
else:
np_specs.append(eval_if_tensor(s))
self.test.assertAllEqual(self.x_np[tuple(np_specs)], tensor)
if self.check_type_infer:
self.test.assertAllEqual(tensor.shape, op.get_shape())
return tensor
STRIDED_SLICE_TYPES = [
dtypes.int32, dtypes.int64, dtypes.int16, dtypes.int8, dtypes.uint8,
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128,
dtypes.bool
]
class StridedSliceTest(test_util.TensorFlowTestCase):
"""Test the strided slice operation with variants of slices."""
def test_basic_slice(self):
for tensor_type in STRIDED_SLICE_TYPES:
with self.subTest(tensor_type=tensor_type, use_gpu=True):
checker = StridedSliceChecker(
self, StridedSliceChecker.REF_TENSOR, tensor_type=tensor_type)
_ = checker[:, :, :]
# Various ways of representing identity slice
_ = checker[:, :, :]
_ = checker[::, ::, ::]
_ = checker[::1, ::1, ::1]
# Not zero slice
_ = checker[::1, ::5, ::2]
# Reverse in each dimension independently
_ = checker[::-1, :, :]
_ = checker[:, ::-1, :]
_ = checker[:, :, ::-1]
## negative index tests i.e. n-2 in first component
_ = checker[-2::-1, :, ::1]
# negative index tests i.e. n-2 in first component, non-unit stride
_ = checker[-2::-1, :, ::2]
# Check rank-0 examples
checker2 = StridedSliceChecker(self, 5, tensor_type=tensor_type)
_ = checker2[None]
_ = checker2[...]
_ = checker2[tuple()]
def testInt64GPU(self):
if not test_util.is_gpu_available():
self.skipTest("No GPU available")
with test_util.force_gpu():
x = constant_op.constant([1., 2., 3.])
begin = constant_op.constant([2], dtype=dtypes.int64)
end = constant_op.constant([3], dtype=dtypes.int64)
strides = constant_op.constant([1], dtype=dtypes.int64)
s = array_ops.strided_slice(x, begin, end, strides)
self.assertAllEqual([3.], self.evaluate(s))
@test_util.assert_no_new_pyobjects_executing_eagerly
@test_util.assert_no_garbage_created
def testTensorSliceEagerMemory(self):
with context.eager_mode():
inputs = constant_op.constant([[[1], [2], [3], [4]]],
dtype=dtypes.float32)
# Tests that slicing an EagerTensor doesn't leak memory
inputs[0] # pylint: disable=pointless-statement
@test_util.assert_no_new_pyobjects_executing_eagerly
@test_util.assert_no_garbage_created
def testVariableSliceEagerMemory(self):
with context.eager_mode():
v = variables.Variable([1., 2.])
v[0] # pylint: disable=pointless-statement
def testDegenerateSlices(self):
with test_util.device(use_gpu=True):
checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR)
# degenerate by offering a forward interval with a negative stride
_ = checker[0:-1:-1, :, :]
# degenerate with a reverse interval with a positive stride
_ = checker[-1:0, :, :]
# empty interval in every dimension
_ = checker[-1:0, 2:2, 2:3:-1]
# empty first dimension only (used to break for aligned tensors).
checker = StridedSliceChecker(self,
StridedSliceChecker.REF_TENSOR_ALIGNED)
_ = checker[1:0]
def testSliceWithUndefinedDimension(self):
t = constant_op.constant([1, 2, 3])
d = tensor_shape.Dimension(None)
self.assertAllEqual(t[d:d:d], t)
def testEllipsis(self):
with test_util.device(use_gpu=True):
raw = [[[[[1, 2], [3, 4], [5, 6]]], [[[7, 8], [9, 10], [11, 12]]]]]
checker = StridedSliceChecker(self, raw)
_ = checker[0:]
# implicit ellipsis
_ = checker[0:, ...]
# ellipsis alone
_ = checker[...]
# ellipsis at end
_ = checker[0:1, ...]
# ellipsis at begin
_ = checker[..., 0:1]
# ellipsis at middle
_ = checker[0:1, ..., 0:1]
# multiple ellipses not allowed
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"Multiple ellipses"):
_ = checker[..., :, ...].eval()
def testShrink(self):
with test_util.device(use_gpu=True):
raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
[[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]
checker = StridedSliceChecker(self, raw)
_ = checker[:, :, :, :, 3]
_ = checker[..., 3]
_ = checker[:, 0]
_ = checker[:, :, 0]
def testBothNewAxisAndShrink(self):
with test_util.device(use_gpu=True):
@def_function.function
def func(inp):
return inp[array_ops.newaxis, :, 0]
f = func.get_concrete_function(
tensor_spec.TensorSpec([2, 2], dtypes.int16))
# TODO(b/190416665): Allow the constant to be eagerly copied/created on
# the GPU.
with ops.device("CPU"):
ones = constant_op.constant([[1, 1], [1, 1]], dtypes.int16)
self.assertAllEqual([[1, 1]], self.evaluate(f(ones)))
def testTensorIndexing(self):
with test_util.device(use_gpu=True):
raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
[[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]
checker = StridedSliceChecker(self, raw, check_type_infer=False)
bar = constant_op.constant(2)
bar2 = constant_op.constant(3)
_ = checker[..., bar:bar2]
_ = checker[..., bar]
_ = checker[..., 3]
_ = checker[..., 2**64 // 2**63] # Test longs in Python 2
def testTensorIndexingTypeError(self):
with self.session():
checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR)
expected = re.escape(array_ops._SLICE_TYPE_ERROR)
with self.assertRaisesRegex(TypeError, expected):
_ = checker["foo"]
with self.assertRaisesRegex(TypeError, expected):
_ = checker[constant_op.constant("foo")]
with self.assertRaisesRegex(TypeError, expected):
_ = checker[0.0]
with self.assertRaisesRegex(TypeError, expected):
_ = checker[constant_op.constant(0.0)]
with self.assertRaisesRegex(TypeError, expected):
_ = checker[constant_op.constant([1, 2, 3])]
with self.assertRaisesRegex(TypeError, expected):
_ = checker[[2.1, -0.7, 1.5]]
def testExpand(self):
with test_util.device(use_gpu=True):
raw = [[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
[[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]
checker = StridedSliceChecker(self, raw)
# new axis (followed by implicit ellipsis)
_ = checker[np.newaxis]
# newaxis after ellipsis
_ = checker[..., np.newaxis]
# newaxis in between ellipsis and explicit range
_ = checker[..., np.newaxis, :]
_ = checker[:, ..., np.newaxis, :, :]
# Reverse final dimension with new axis
_ = checker[:, :, np.newaxis, :, 2::-1]
# Ellipsis in middle of two newaxis
_ = checker[np.newaxis, ..., np.newaxis]
def testExpandVariable(self):
with test_util.device(use_gpu=True):
x = variables.Variable(7, dtype=dtypes.int32)
self.evaluate(x.initializer)
y = self.evaluate(x[None])
self.assertEqual(y.shape, (1,))
self.assertAllEqual(y, (7,))
def testOptimizedCases(self):
with test_util.device(use_gpu=True):
checker = StridedSliceChecker(self,
StridedSliceChecker.REF_TENSOR_ALIGNED)
# Identity
_ = checker[:]
# Identity
_ = checker[...]
# Identity
_ = checker[np.newaxis, ..., np.newaxis]
# First axis slice
_ = checker[1:]
# First axis slice
_ = checker[np.newaxis, 1:]
def testMasks(self):
with test_util.device(use_gpu=True):
scalar = np.array(0)
# Test tensor type mask
checker = StridedSliceChecker(self, StridedSliceChecker.REF_TENSOR)
_ = checker[checker.x > 2]
_ = checker[checker.x <= 5]
_ = checker[ops.convert_to_tensor(scalar)]
# Test numpy array type mask
raw = np.array([[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]],
[[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23,
24]]]]])
checker1 = StridedSliceChecker(self, raw)
_ = checker1[raw >= 4]
_ = checker1[raw < 19]
_ = checker1[scalar]
# Test boolean and non boolean cases
mask = np.array([True, False, True])
raw1 = np.array([[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]])
checker2 = StridedSliceChecker(self, raw1)
_ = checker2[mask]
_ = checker2[ops.convert_to_tensor(mask)]
def test_int16_indices(self):
def _int16(i):
return constant_op.constant(i, dtype=dtypes.int16)
def _int64(i):
return constant_op.constant(i, dtype=dtypes.int64)
for tensor_type in STRIDED_SLICE_TYPES:
with self.subTest(tensor_type=tensor_type, use_gpu=True):
checker = StridedSliceChecker(
self, StridedSliceChecker.REF_TENSOR, tensor_type=tensor_type)
_ = checker[_int16(1)]
with self.assertRaises(Exception):
_ = checker[_int16(1)::1, :, 1:_int64(3):2]
with self.assertRaises(Exception):
_ = checker[:, _int16(1):_int16(5):-1, :]
with self.assertRaises(Exception):
_ = checker[::_int64(1), _int64(1):10:_int16(3), ::_int64(2)]
_ = checker[::_int16(1), _int16(1)::_int16(5), ::2]
_ = checker[_int16(1):_int16(5):_int16(2), 1:2, :]
class StridedSliceShapeTest(test_util.TensorFlowTestCase):
"""Test the shape inference of StridedSliceShapes."""
def testUnknown(self):
with test_util.device(use_gpu=True):
@def_function.function
def f(x):
y = x[...]
self.assertAllEqual(y.get_shape().ndims, None)
_ = f.get_concrete_function(tensor_spec.TensorSpec(None, dtypes.float32))
def tensorShapeEqual(self, x, y):
self.assertTrue(x is not None and y is not None or x is None and y is None)
self.assertEqual(x.as_list(), y.as_list())
def testTensorShapeUncertain(self):
with test_util.device(use_gpu=True):
@def_function.function
def f1(x):
y = x[3:5]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 7]))
_ = f1.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f2(x):
y = x[3:5, :, 4]
self.tensorShapeEqual(y.get_shape(), tensor_shape.TensorShape([2,
None]))
_ = f2.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f3(x):
y = x[3:5, 3:4, 4]
self.tensorShapeEqual(y.get_shape(), tensor_shape.TensorShape([2,
None]))
_ = f3.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f4(x):
y = x[3:5, :, 5:10]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 2]))
_ = f4.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f5(x):
y = x[3:5, :, 50:3]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 0]))
_ = f5.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f6(x):
y = x[3:5, :, array_ops.newaxis, 50:3,]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 1, 0]))
_ = f6.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f7(x):
y = x[1:5:2, :, array_ops.newaxis, 50:3,]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 1, 0]))
_ = f7.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f8(x):
y = x[:5:3, :, array_ops.newaxis, 50:3,]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([2, None, 1, 0]))
_ = f8.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f9(x):
y = x[:2:3, :, array_ops.newaxis, 50:3,]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([1, None, 1, 0]))
_ = f9.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
@def_function.function
def f10(x):
y = x[::-1, :, array_ops.newaxis, ::-2]
self.tensorShapeEqual(y.get_shape(),
tensor_shape.TensorShape([5, None, 1, 4]))
_ = f10.get_concrete_function(
tensor_spec.TensorSpec((5, None, 7), dtypes.float32))
def testTensorValuedIndexShape(self):
with self.session():
@def_function.function
def f1(x, y):
z = x[y]
self.tensorShapeEqual(z.get_shape(), tensor_shape.TensorShape([3, 7]))
_ = f1.get_concrete_function(
tensor_spec.TensorSpec((5, 3, 7)),
tensor_spec.TensorSpec((), dtypes.int32))
@def_function.function
def f2(x, y):