1# Copyright 2017 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Unit tests for TensorFlow "Eager" Mode's Tensor class.""" 16 17import copy 18import re 19import sys 20 21import numpy as np 22 23from tensorflow.python import pywrap_tfe 24from tensorflow.python.eager import context 25from tensorflow.python.eager import core 26from tensorflow.python.eager import test 27from tensorflow.python.framework import constant_op 28from tensorflow.python.framework import dtypes 29from tensorflow.python.framework import errors 30from tensorflow.python.framework import ops 31from tensorflow.python.framework import test_util 32from tensorflow.python.ops import array_ops 33from tensorflow.python.ops import io_ops 34from tensorflow.python.ops import list_ops 35from tensorflow.python.ops import resource_variable_ops 36from tensorflow.python.ops import variables 37 38 39def _create_tensor(value, device=None, dtype=None): 40 context.ensure_initialized() 41 ctx = context.context() 42 if device is None: 43 device = ctx.device_name 44 if dtype is not None: 45 dtype = dtype.as_datatype_enum 46 try: 47 return ops.EagerTensor(value, device=device, dtype=dtype) 48 except core._NotOkStatusException as e: # pylint: disable=protected-access 49 raise core._status_to_exception(e) 50 51 52class TFETensorTest(test_util.TensorFlowTestCase): 53 54 def testScalarTensor(self): 55 t = _create_tensor(3, dtype=dtypes.int32) 56 self.assertAllEqual(t, _create_tensor(np.array(3))) 57 self.assertEqual(dtypes.int32, t.dtype) 58 self.assertEqual(0, t.shape.ndims) 59 self.assertAllEqual([], t.shape.as_list()) 60 self.assertIn("tf.Tensor", str(t)) 61 self.assertIn("tf.Tensor", repr(t)) 62 63 def testBadConstructorArgs(self): 64 context.ensure_initialized() 65 ctx = context.context() 66 device = ctx.device_name 67 # Missing device. 68 with self.assertRaisesRegex(TypeError, r".*argument 'device' \(pos 2\).*"): 69 ops.EagerTensor(1) 70 # Bad dtype type. 71 with self.assertRaisesRegex(TypeError, 72 "Expecting a DataType value for dtype. Got"): 73 ops.EagerTensor(1, device=device, dtype="1") 74 75 # Following errors happen when trying to copy to GPU. 76 if not test_util.is_gpu_available(): 77 self.skipTest("No GPUs found") 78 79 with ops.device("/device:GPU:0"): 80 # Bad device. 81 with self.assertRaisesRegex(TypeError, "Error parsing device argument"): 82 ops.EagerTensor(1.0, device=1) 83 84 def testNumpyValue(self): 85 values = np.array([3.0]) 86 t = _create_tensor(values) 87 self.assertAllEqual(values, t) 88 89 @test_util.assert_no_new_pyobjects_executing_eagerly 90 def testNumpyDtypeSurvivesThroughTensorConversion(self): 91 scalar_creators = [np.int32, np.int64, np.float32, np.float64] 92 conversion_functions = [ops.convert_to_tensor, constant_op.constant] 93 94 for scalar_creator in scalar_creators: 95 for conversion_function in conversion_functions: 96 np_val = scalar_creator(3) 97 tensor_val = conversion_function(np_val) 98 self.assertEqual(tensor_val.numpy().dtype, np_val.dtype) 99 self.assertEqual(tensor_val.numpy(), np_val) 100 101 def testNumpyValueWithCast(self): 102 values = np.array([3.0], dtype=np.float32) 103 t = _create_tensor(values, dtype=dtypes.float64) 104 self.assertAllEqual(values, t) 105 ctx = context.context() 106 # Bad dtype value. 107 with self.assertRaisesRegex(TypeError, "Invalid dtype argument value"): 108 ops.EagerTensor(values, device=ctx.device_name, dtype=12345) 109 110 def testNumpyOrderHandling(self): 111 n = np.array([[1, 2], [3, 4]], order="F") 112 t = _create_tensor(n) 113 self.assertAllEqual([[1, 2], [3, 4]], t) 114 115 def testNumpyArrayDtype(self): 116 tensor = constant_op.constant([1.0, 2.0, 3.0]) 117 numpy_tensor = np.asarray(tensor, dtype=np.int32) 118 self.assertAllEqual(numpy_tensor, [1, 2, 3]) 119 120 def testNdimsAgreesWithNumpy(self): 121 numpy_tensor = np.asarray(1.0) 122 tensor = constant_op.constant(numpy_tensor) 123 self.assertAllEqual(numpy_tensor.ndim, tensor.ndim) 124 125 numpy_tensor = np.asarray([1.0, 2.0, 3.0]) 126 tensor = constant_op.constant(numpy_tensor) 127 self.assertAllEqual(numpy_tensor.ndim, tensor.ndim) 128 129 numpy_tensor = np.asarray([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) 130 tensor = constant_op.constant(numpy_tensor) 131 self.assertAllEqual(numpy_tensor.ndim, tensor.ndim) 132 133 def testLenAgreesWithNumpy(self): 134 numpy_tensor = np.asarray(1.0) 135 tensor = constant_op.constant(numpy_tensor) 136 with self.assertRaises(TypeError): 137 len(numpy_tensor) 138 with self.assertRaisesRegex(TypeError, r"Scalar tensor has no `len[(][)]`"): 139 len(tensor) 140 141 numpy_tensor = np.asarray([1.0, 2.0, 3.0]) 142 tensor = constant_op.constant(numpy_tensor) 143 self.assertAllEqual(len(numpy_tensor), len(tensor)) 144 145 numpy_tensor = np.asarray([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) 146 tensor = constant_op.constant(numpy_tensor) 147 self.assertAllEqual(len(numpy_tensor), len(tensor)) 148 149 def testCopy(self): 150 t = constant_op.constant(1.0) 151 tt = copy.copy(t) 152 self.assertAllEqual(tt, 1.0) 153 del tt 154 tt = copy.deepcopy(t) 155 self.assertAllEqual(tt, 1.0) 156 del tt 157 self.assertAllEqual(t, 1.0) 158 159 def testConstantDtype(self): 160 self.assertEqual( 161 constant_op.constant(1, dtype=np.int64).dtype, dtypes.int64) 162 163 def testTensorAndNumpyMatrix(self): 164 expected = np.array([[1.0, 2.0], [3.0, 4.0]], np.float32) 165 actual = _create_tensor([[1.0, 2.0], [3.0, 4.0]]) 166 self.assertAllEqual(expected, actual) 167 self.assertEqual(np.float32, actual.dtype) 168 self.assertEqual(dtypes.float32, actual.dtype) 169 self.assertAllEqual([2, 2], actual.shape.as_list()) 170 171 def testFloatDowncast(self): 172 # Unless explicitly specified, float64->float32 173 t = _create_tensor(3.0) 174 self.assertEqual(dtypes.float32, t.dtype) 175 t = _create_tensor(3.0, dtype=dtypes.float64) 176 self.assertEqual(dtypes.float64, t.dtype) 177 178 def testBool(self): 179 self.assertFalse(bool(_create_tensor(False))) 180 self.assertFalse(bool(_create_tensor([False]))) 181 self.assertFalse(bool(_create_tensor([[False]]))) 182 self.assertFalse(bool(_create_tensor([0]))) 183 self.assertFalse(bool(_create_tensor([0.]))) 184 self.assertTrue(bool(_create_tensor([1]))) 185 self.assertTrue(bool(_create_tensor([1.]))) 186 187 def testIndex(self): 188 self.assertEqual([42][_create_tensor(0)], 42) 189 190 with self.assertRaises(TypeError): 191 _ = [42][_create_tensor([0])] 192 193 def testIntDowncast(self): 194 t = _create_tensor(3) 195 self.assertEqual(dtypes.int32, t.dtype) 196 t = _create_tensor(3, dtype=dtypes.int64) 197 self.assertEqual(dtypes.int64, t.dtype) 198 t = _create_tensor(2**33) 199 self.assertEqual(dtypes.int64, t.dtype) 200 201 def testTensorCreationFailure(self): 202 with self.assertRaises(ValueError): 203 # Should fail because the each row of the Python object has a different 204 # number of columns. 205 self.assertEqual(None, _create_tensor([[1], [1, 2]])) 206 207 def testMultiLineTensorStr(self): 208 t = _create_tensor(np.eye(3)) 209 tensor_str = str(t) 210 self.assertIn("shape=%s, dtype=%s" % (t.shape, t.dtype.name), tensor_str) 211 self.assertIn(str(t), tensor_str) 212 213 def testMultiLineTensorRepr(self): 214 t = _create_tensor(np.eye(3)) 215 tensor_repr = repr(t) 216 self.assertTrue(tensor_repr.startswith("<")) 217 self.assertTrue(tensor_repr.endswith(">")) 218 self.assertIn( 219 "shape=%s, dtype=%s, numpy=\n%r" % (t.shape, t.dtype.name, t.numpy()), 220 tensor_repr) 221 222 def testTensorStrReprObeyNumpyPrintOptions(self): 223 orig_threshold = np.get_printoptions()["threshold"] 224 orig_edgeitems = np.get_printoptions()["edgeitems"] 225 np.set_printoptions(threshold=2, edgeitems=1) 226 227 t = _create_tensor(np.arange(10, dtype=np.int32)) 228 self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", str(t))) 229 self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", repr(t))) 230 231 # Clean up: reset to previous printoptions. 232 np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems) 233 234 def testZeroDimTensorStr(self): 235 t = _create_tensor(42) 236 self.assertIn("42, shape=(), dtype=int32", str(t)) 237 238 def testZeroDimTensorRepr(self): 239 t = _create_tensor(42) 240 self.assertTrue(repr(t).startswith("<")) 241 self.assertTrue(repr(t).endswith(">")) 242 self.assertIn("shape=(), dtype=int32, numpy=42", repr(t)) 243 244 def testZeroSizeTensorStr(self): 245 t = _create_tensor(np.zeros(0, dtype=np.float32)) 246 self.assertIn("[], shape=(0,), dtype=float32", str(t)) 247 248 def testZeroSizeTensorRepr(self): 249 t = _create_tensor(np.zeros(0, dtype=np.float32)) 250 self.assertTrue(repr(t).startswith("<")) 251 self.assertTrue(repr(t).endswith(">")) 252 self.assertIn("shape=(0,), dtype=float32, numpy=%r" % t.numpy(), repr(t)) 253 254 def testStringTensor(self): 255 t_np_orig = np.array([[b"a", b"ab"], [b"abc", b"abcd"]]) 256 t = _create_tensor(t_np_orig) 257 t_np = t.numpy() 258 self.assertTrue(np.all(t_np == t_np_orig), "%s vs %s" % (t_np, t_np_orig)) 259 260 def testIterateOverTensor(self): 261 l = [[1, 2], [3, 4]] 262 t = _create_tensor(l) 263 for list_element, tensor_element in zip(l, t): 264 self.assertAllEqual(list_element, tensor_element.numpy()) 265 266 def testIterateOverScalarTensorRaises(self): 267 t = _create_tensor(1) 268 with self.assertRaisesRegex(TypeError, 269 "Cannot iterate over a scalar tensor"): 270 iter(t) 271 272 @test_util.run_gpu_only 273 def testStringTensorOnGPU(self): 274 with ops.device("/device:GPU:0"): 275 t = _create_tensor("test string") 276 self.assertIn("GPU", t.device) 277 278 def testInvalidUTF8ProducesReasonableError(self): 279 if sys.version_info[0] < 3: 280 self.skipTest("Test is only valid in python3.") 281 with self.assertRaises(UnicodeDecodeError): 282 io_ops.read_file(b"\xff") 283 284 @test_util.run_in_graph_and_eager_modes 285 def testConvertToTensorPreferredDtypeIsRespected(self): 286 self.assertEqual( 287 ops.convert_to_tensor(0.5, preferred_dtype=dtypes.int32).dtype, 288 dtypes.float32) 289 self.assertEqual( 290 ops.convert_to_tensor(0.5, preferred_dtype=dtypes.float64).dtype, 291 dtypes.float64) 292 293 @test_util.run_in_graph_and_eager_modes 294 def testCompatibility(self): 295 integer_types = [ 296 dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, 297 dtypes.uint16, dtypes.uint32, dtypes.uint64 298 ] 299 300 # Floats are not compatible with ints 301 for t in integer_types: 302 with self.assertRaises(TypeError): 303 constant_op.constant(0.5, dtype=t) 304 305 # Ints compatible with floats 306 self.assertEqual( 307 self.evaluate(constant_op.constant(5, dtype=dtypes.float16)), 5.0) 308 self.assertEqual( 309 self.evaluate(constant_op.constant(5, dtype=dtypes.float32)), 5.0) 310 self.assertEqual( 311 self.evaluate(constant_op.constant(5, dtype=dtypes.float64)), 5.0) 312 self.assertEqual( 313 self.evaluate(constant_op.constant(5, dtype=dtypes.bfloat16)), 5.0) 314 315 # Ints and floats are compatible with complex types 316 self.assertEqual( 317 constant_op.constant([[1.0]], dtype=dtypes.complex128).dtype, 318 dtypes.complex128) 319 self.assertEqual( 320 constant_op.constant([[1]], dtype=dtypes.complex128).dtype, 321 dtypes.complex128) 322 323 # Quantized types are not compatible with floats 324 quantized_types = [ 325 dtypes.qint16, dtypes.qint32, dtypes.qint8, dtypes.quint16, 326 dtypes.quint8 327 ] 328 329 for t in quantized_types: 330 with self.assertRaises(TypeError): 331 constant_op.constant(0.5, dtype=t) 332 333 # TODO(b/118402529): quantized types are broken in eager. 334 335 @test_util.run_in_graph_and_eager_modes 336 def testCConvertToTensor(self): 337 with self.assertRaises(TypeError): 338 _ = constant_op.constant(0) < 0.5 339 340 @test_util.run_in_graph_and_eager_modes 341 def testConvertToTensorAllowsOverflow(self): 342 _ = ops.convert_to_tensor(123456789, dtype=dtypes.uint8) 343 344 @test_util.assert_no_new_pyobjects_executing_eagerly 345 @test_util.run_in_graph_and_eager_modes 346 def testConvertToTensorNumpyZeroDim(self): 347 for np_type, dtype in [(np.int32, dtypes.int32), (np.half, dtypes.half), 348 (np.float32, dtypes.float32)]: 349 x = ops.convert_to_tensor( 350 [np.array(65, dtype=np_type), 351 np.array(16, dtype=np_type)]) 352 self.assertEqual(x.dtype, dtype) 353 self.assertAllEqual(x, [65, 16]) 354 355 @test_util.assert_no_new_pyobjects_executing_eagerly 356 @test_util.run_in_graph_and_eager_modes 357 def testConvertToTensorNumpyScalar(self): 358 x = ops.convert_to_tensor([ 359 np.array(321, dtype=np.int64).item(), 360 np.array(16, dtype=np.int64).item() 361 ]) 362 self.assertAllEqual(x, [321, 16]) 363 364 def testEagerTensorError(self): 365 with self.assertRaisesRegex(TypeError, 366 "Cannot convert .* to EagerTensor of dtype .*"): 367 _ = ops.convert_to_tensor(1., dtype=dtypes.int32) 368 369 def testEagerLargeConstant(self): 370 for t in [dtypes.uint64, dtypes.uint32, dtypes.int32, dtypes.int64]: 371 self.assertEqual(constant_op.constant(t.max, dtype=t).numpy(), t.max) 372 self.assertEqual(constant_op.constant(t.min, dtype=t).numpy(), t.min) 373 374 def test_numpyIsView(self): 375 with ops.device("CPU"): 376 t = constant_op.constant([0.0]) 377 t._numpy()[0] = 42.0 378 self.assertAllClose(t, constant_op.constant([42.0])) 379 380 def test_numpyFailsForResource(self): 381 v = variables.Variable(42) 382 with self.assertRaisesRegex(errors.InvalidArgumentError, 383 "Cannot convert .+ resource"): 384 v._handle._numpy() 385 386 def test_numpyFailsForVariant(self): 387 variant_t = list_ops.tensor_list_reserve( 388 element_shape=[], num_elements=1, element_dtype=dtypes.float32) 389 with self.assertRaisesRegex(errors.InvalidArgumentError, 390 "Cannot convert .+ variant"): 391 variant_t._numpy() 392 393 def testMemoryviewFailsForResource(self): 394 v = variables.Variable(42) 395 with self.assertRaisesRegex(BufferError, "Cannot convert .+ resource"): 396 np.asarray(memoryview(v._handle)) 397 398 def testMemoryviewFailsForVariant(self): 399 variant_t = list_ops.tensor_list_reserve( 400 element_shape=[], num_elements=1, element_dtype=dtypes.float32) 401 with self.assertRaisesRegex(BufferError, "Cannot convert .+ variant"): 402 np.asarray(memoryview(variant_t)) 403 404 def testMemoryviewIsReadonly(self): 405 t = constant_op.constant([0.0]) 406 self.assertTrue(memoryview(t).readonly) 407 408 @test_util.assert_no_new_pyobjects_executing_eagerly 409 def testMemoryviewScalar(self): 410 t = constant_op.constant(42.0) 411 self.assertAllEqual( 412 np.array(memoryview(t)), np.array(42.0, dtype=np.float32)) 413 414 @test_util.assert_no_new_pyobjects_executing_eagerly 415 def testMemoryviewEmpty(self): 416 t = constant_op.constant([], dtype=np.float32) 417 self.assertAllEqual(np.array(memoryview(t)), np.array([])) 418 419 @test_util.run_gpu_only 420 @test_util.assert_no_new_pyobjects_executing_eagerly 421 def testMemoryviewCopyToCPU(self): 422 with ops.device("/device:GPU:0"): 423 t = constant_op.constant([0.0]) 424 self.assertAllEqual( 425 np.array(memoryview(t)), np.array([0.0], dtype=np.float32)) 426 427 @test_util.disable_tfrt("b/169877776: ResourceVariable is not initialized " 428 "properly in TFRT") 429 def testResourceTensorCopy(self): 430 if not test_util.is_gpu_available(): 431 self.skipTest("GPU only") 432 433 with ops.device("GPU:0"): 434 v = resource_variable_ops.ResourceVariable(1.) 435 436 read_handle_on_gpu = resource_variable_ops.read_variable_op( 437 v.handle, dtypes.float32) 438 handle_on_cpu = v.handle.cpu() 439 read_handle_on_cpu = resource_variable_ops.read_variable_op( 440 handle_on_cpu, dtypes.float32) 441 442 self.assertAllEqual(read_handle_on_cpu, read_handle_on_gpu) 443 444 def testEagerTensorFormat(self): 445 t = array_ops.constant(1) 446 self.assertEqual(f"{t}", "1") 447 self.assertEqual(str(t), "tf.Tensor(1, shape=(), dtype=int32)") 448 self.assertEqual(f"{t!s}", "tf.Tensor(1, shape=(), dtype=int32)") 449 self.assertEqual(repr(t), "<tf.Tensor: shape=(), dtype=int32, numpy=1>") 450 self.assertEqual(f"{t!r}", "<tf.Tensor: shape=(), dtype=int32, numpy=1>") 451 452 def testEagerTensorFormatForResource(self): 453 t = resource_variable_ops.VarHandleOp(shape=[], dtype=dtypes.float32) 454 455 # type is compiler-depdendent, as it comes from demangling. 456 handle_str = (f"<ResourceHandle(" 457 f"name=\"\", " 458 f"device=\"{t.device}\", " 459 f"container=\"localhost\", " 460 f"type=\"@@tensorflow@@Var@@\")>") 461 462 def make_regex(s): 463 return re.escape(s).replace("@@", ".*") 464 465 self.assertRegex(f"{t}", make_regex(handle_str)) 466 self.assertRegex( 467 str(t), 468 make_regex(f"tf.Tensor({handle_str}, shape=(), dtype=resource)")) 469 self.assertRegex( 470 f"{t!s}", 471 make_regex(f"tf.Tensor({handle_str}, shape=(), dtype=resource)")) 472 self.assertRegex( 473 repr(t), 474 make_regex( 475 f"<tf.Tensor: shape=(), dtype=resource, value={handle_str}>")) 476 self.assertRegex( 477 f"{t!r}", 478 make_regex( 479 f"<tf.Tensor: shape=(), dtype=resource, value={handle_str}>")) 480 481 def testEagerTensorFormatForVariant(self): 482 t = list_ops.tensor_list_reserve( 483 element_shape=[1], num_elements=1, element_dtype=dtypes.float32) 484 self.assertEqual(f"{t}", "<TensorList>") 485 self.assertEqual(str(t), "tf.Tensor(<TensorList>, shape=(), dtype=variant)") 486 self.assertEqual(f"{t!s}", 487 "tf.Tensor(<TensorList>, shape=(), dtype=variant)") 488 self.assertEqual( 489 repr(t), "<tf.Tensor: shape=(), dtype=variant, value=<TensorList>>") 490 self.assertEqual( 491 f"{t!r}", "<tf.Tensor: shape=(), dtype=variant, value=<TensorList>>") 492 493 494class TFETensorUtilTest(test_util.TensorFlowTestCase): 495 496 def setUp(self): 497 super(TFETensorUtilTest, self).setUp() 498 context.ensure_initialized() 499 500 def testListOfThree(self): 501 t1 = _create_tensor([[1, 2], [3, 4], [5, 6]], dtype=dtypes.int32) 502 t2 = _create_tensor([[1, 2, 5], [3, 4, 5]], dtype=dtypes.int32) 503 t3 = _create_tensor([[1], [3], [5], [6]], dtype=dtypes.int32) 504 505 r = pywrap_tfe.TFE_Py_TensorShapeSlice([t1, t2, t3], 0) 506 self.assertAllEqual(np.array([3, 2, 4]), r.numpy()) 507 508 r = pywrap_tfe.TFE_Py_TensorShapeSlice([t1, t2, t3], 1) 509 self.assertAllEqual(np.array([2, 3, 1]), r.numpy()) 510 511 def testEmptyTensorList(self): 512 a = pywrap_tfe.TFE_Py_TensorShapeSlice([], 0) 513 self.assertTrue(isinstance(a, ops.EagerTensor)) 514 self.assertEqual(0, a.numpy().size) 515 516 def testTensorListContainsNonTensors(self): 517 t1 = _create_tensor([1, 2], dtype=dtypes.int32) 518 519 with self.assertRaisesRegex( 520 TypeError, 521 r"Expected a list of EagerTensors but element 1 has type \"str\""): 522 pywrap_tfe.TFE_Py_TensorShapeSlice([t1, "abc"], 0) 523 524 with self.assertRaisesRegex( 525 TypeError, 526 r"Expected a list of EagerTensors but element 0 has type \"int\""): 527 pywrap_tfe.TFE_Py_TensorShapeSlice([2, t1], 0) 528 529 def testTensorListNotList(self): 530 t1 = _create_tensor([1, 2], dtype=dtypes.int32) 531 532 with self.assertRaisesRegex( 533 TypeError, 534 r"tensors argument must be a list or a tuple. Got.*EagerTensor"): 535 pywrap_tfe.TFE_Py_TensorShapeSlice(t1, -2) 536 537 def testNegativeSliceDim(self): 538 t1 = _create_tensor([1, 2], dtype=dtypes.int32) 539 540 with self.assertRaisesRegex( 541 ValueError, r"Slice dimension must be non-negative. Got -2"): 542 pywrap_tfe.TFE_Py_TensorShapeSlice([t1], -2) 543 544 def testUnicode(self): 545 self.assertEqual(constant_op.constant(u"asdf").numpy(), b"asdf") 546 547 def testFloatTensor(self): 548 self.assertEqual(dtypes.float64, _create_tensor(np.float64()).dtype) # pylint: disable=no-value-for-parameter 549 self.assertEqual(dtypes.float32, _create_tensor(np.float32()).dtype) # pylint: disable=no-value-for-parameter 550 self.assertEqual(dtypes.float16, _create_tensor(np.float16()).dtype) # pylint: disable=no-value-for-parameter 551 self.assertEqual(dtypes.float32, _create_tensor(0.0).dtype) 552 553 def testSliceDimOutOfRange(self): 554 t1 = _create_tensor([[1, 2], [3, 4], [5, 6]], dtype=dtypes.int32) 555 t2 = _create_tensor([1, 2], dtype=dtypes.int32) 556 t3 = _create_tensor(2, dtype=dtypes.int32) 557 558 with self.assertRaisesRegex( 559 IndexError, 560 r"Slice dimension \(2\) must be smaller than rank of all tensors, " 561 "but tensor at index 0 has rank 2"): 562 pywrap_tfe.TFE_Py_TensorShapeSlice([t1], 2) 563 564 with self.assertRaisesRegex( 565 IndexError, 566 r"Slice dimension \(1\) must be smaller than rank of all tensors, " 567 "but tensor at index 0 has rank 1"): 568 pywrap_tfe.TFE_Py_TensorShapeSlice([t2], 1) 569 570 with self.assertRaisesRegex( 571 IndexError, 572 r"Slice dimension \(1\) must be smaller than rank of all tensors, " 573 "but tensor at index 1 has rank 1"): 574 pywrap_tfe.TFE_Py_TensorShapeSlice([t1, t2], 1) 575 576 with self.assertRaisesRegex( 577 IndexError, 578 r"Slice dimension \(0\) must be smaller than rank of all tensors, " 579 "but tensor at index 0 has rank 0"): 580 pywrap_tfe.TFE_Py_TensorShapeSlice([t3], 0) 581 582 with self.assertRaisesRegex( 583 IndexError, 584 r"Slice dimension \(0\) must be smaller than rank of all tensors, " 585 "but tensor at index 2 has rank 0"): 586 pywrap_tfe.TFE_Py_TensorShapeSlice([t2, t1, t3], 0) 587 588 @test_util.assert_no_new_pyobjects_executing_eagerly 589 def testTensorDir(self): 590 t = array_ops.ones(1) 591 t.test_attr = "Test" 592 593 instance_dir = dir(t) 594 type_dir = dir(ops.EagerTensor) 595 596 # Monkey patched attributes should show up in dir(t) 597 self.assertIn("test_attr", instance_dir) 598 instance_dir.remove("test_attr") 599 self.assertEqual(instance_dir, type_dir) 600 601 def testNonRectangularPackAsConstant(self): 602 l = [array_ops.zeros((10, 1)).numpy(), array_ops.zeros(1).numpy()] 603 604 with self.assertRaisesRegex(ValueError, "non-rectangular Python sequence"): 605 constant_op.constant(l) 606 607 @test_util.assert_no_new_pyobjects_executing_eagerly 608 def testFloatAndIntAreConvertibleToComplex(self): 609 a = [[1., 1], [1j, 2j]] 610 np_value = np.array(a, dtype=np.complex128) 611 tf_value = ops.convert_to_tensor(a, dtype=dtypes.complex128) 612 self.assertAllEqual(tf_value.numpy(), np_value) 613 614 615if __name__ == "__main__": 616 test.main() 617