1# Copyright 2015 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"""Tests for tf.bitcast.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21import numpy as np 22 23from tensorflow.python.framework import dtypes 24from tensorflow.python.framework import test_util 25from tensorflow.python.ops import array_ops 26from tensorflow.python.platform import test 27 28 29class BitcastTest(test.TestCase): 30 31 def _testBitcast(self, x, datatype, shape): 32 with test_util.use_gpu(): 33 tf_ans = array_ops.bitcast(x, datatype) 34 out = self.evaluate(tf_ans) 35 buff_after = memoryview(out).tobytes() 36 buff_before = memoryview(x).tobytes() 37 self.assertEqual(buff_before, buff_after) 38 self.assertEqual(tf_ans.get_shape(), shape) 39 self.assertEqual(tf_ans.dtype, datatype) 40 41 def testSmaller(self): 42 x = np.random.rand(3, 2) 43 datatype = dtypes.int8 44 shape = [3, 2, 8] 45 self._testBitcast(x, datatype, shape) 46 47 def testLarger(self): 48 x = np.arange(16, dtype=np.int8).reshape([4, 4]) 49 datatype = dtypes.int32 50 shape = [4] 51 self._testBitcast(x, datatype, shape) 52 53 def testSameDtype(self): 54 x = np.random.rand(3, 4) 55 shape = [3, 4] 56 self._testBitcast(x, x.dtype, shape) 57 58 def testSameSize(self): 59 x = np.random.rand(3, 4) 60 shape = [3, 4] 61 self._testBitcast(x, dtypes.int64, shape) 62 63 @test_util.run_deprecated_v1 64 def testErrors(self): 65 x = np.zeros([1, 1], np.int8) 66 datatype = dtypes.int32 67 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): 68 array_ops.bitcast(x, datatype, None) 69 70 def testEmpty(self): 71 x = np.ones([], np.int32) 72 datatype = dtypes.int8 73 shape = [4] 74 self._testBitcast(x, datatype, shape) 75 76 @test_util.run_deprecated_v1 77 def testUnknown(self): 78 x = array_ops.placeholder(dtypes.float32) 79 datatype = dtypes.int8 80 array_ops.bitcast(x, datatype, None) 81 82 def testQuantizedType(self): 83 shape = [3, 4] 84 x = np.zeros(shape, np.uint16) 85 datatype = dtypes.quint16 86 self._testBitcast(x, datatype, shape) 87 88 def testUnsignedType(self): 89 shape = [3, 4] 90 x = np.zeros(shape, np.int64) 91 datatype = dtypes.uint64 92 self._testBitcast(x, datatype, shape) 93 94 95if __name__ == "__main__": 96 test.main() 97