text
stringlengths
5
261k
id
stringlengths
16
106
metadata
dict
__index_level_0__
int64
0
266
import numpy as np import pytest from keras import backend from keras import initializers from keras import layers from keras import testing class ConvLSTM2DTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basics(self): channels_last = backend.config.image_data_format() == "channels_last" self.run_layer_test( layers.ConvLSTM2D, init_kwargs={"filters": 5, "kernel_size": 3, "padding": "same"}, input_shape=(3, 2, 4, 4, 3) if channels_last else (3, 2, 3, 4, 4), expected_output_shape=( (3, 4, 4, 5) if channels_last else (3, 5, 4, 4) ), expected_num_trainable_weights=3, expected_num_non_trainable_weights=0, supports_masking=True, ) self.run_layer_test( layers.ConvLSTM2D, init_kwargs={ "filters": 5, "kernel_size": 3, "padding": "valid", "recurrent_dropout": 0.5, }, input_shape=(3, 2, 8, 8, 3) if channels_last else (3, 2, 3, 8, 8), call_kwargs={"training": True}, expected_output_shape=( (3, 6, 6, 5) if channels_last else (3, 5, 6, 6) ), expected_num_trainable_weights=3, expected_num_non_trainable_weights=0, supports_masking=True, ) self.run_layer_test( layers.ConvLSTM2D, init_kwargs={ "filters": 5, "kernel_size": 3, "padding": "valid", "return_sequences": True, }, input_shape=(3, 2, 8, 8, 3) if channels_last else (3, 2, 3, 8, 8), expected_output_shape=( (3, 2, 6, 6, 5) if channels_last else (3, 2, 5, 6, 6) ), expected_num_trainable_weights=3, expected_num_non_trainable_weights=0, supports_masking=True, ) def test_correctness(self): sequence = ( np.arange(480).reshape((2, 3, 4, 4, 5)).astype("float32") / 100 ) expected_output = np.array( [ [ [[0.48694518, 0.48694518], [0.50237733, 0.50237733]], [[0.5461202, 0.5461202], [0.5598283, 0.5598283]], ], [ [[0.8661607, 0.8661607], [0.86909103, 0.86909103]], [[0.8774414, 0.8774414], [0.8800861, 0.8800861]], ], ] ) if backend.config.image_data_format() == "channels_first": sequence = sequence.transpose((0, 1, 4, 2, 3)) expected_output = expected_output.transpose((0, 3, 1, 2)) layer = layers.ConvLSTM2D( filters=2, kernel_size=3, kernel_initializer=initializers.Constant(0.01), recurrent_initializer=initializers.Constant(0.02), bias_initializer=initializers.Constant(0.03), ) output = layer(sequence) self.assertAllClose( expected_output, output, )
keras/keras/layers/rnn/conv_lstm2d_test.py/0
{ "file_path": "keras/keras/layers/rnn/conv_lstm2d_test.py", "repo_id": "keras", "token_count": 1779 }
155
import math import numpy as np import pytest import scipy.signal from absl.testing import parameterized from keras import backend from keras import testing from keras.backend.common.keras_tensor import KerasTensor from keras.backend.common.variables import ALLOWED_DTYPES from keras.ops import math as kmath def _stft( x, sequence_length, sequence_stride, fft_length, window="hann", center=True ): # pure numpy version of stft that matches librosa's implementation x = np.array(x) ori_dtype = x.dtype if center: pad_width = [(0, 0) for _ in range(len(x.shape))] pad_width[-1] = (fft_length // 2, fft_length // 2) x = np.pad(x, pad_width, mode="reflect") l_pad = (fft_length - sequence_length) // 2 r_pad = fft_length - sequence_length - l_pad if window is not None: if isinstance(window, str): window = scipy.signal.get_window(window, sequence_length) win = np.array(window, dtype=x.dtype) win = np.pad(win, [[l_pad, r_pad]]) else: win = np.ones((sequence_length + l_pad + r_pad), dtype=x.dtype) x = scipy.signal.stft( x, fs=1.0, window=win, nperseg=(sequence_length + l_pad + r_pad), noverlap=(sequence_length + l_pad + r_pad - sequence_stride), nfft=fft_length, boundary=None, padded=False, )[-1] # scale and swap to (..., num_sequences, fft_bins) x = x / np.sqrt(1.0 / win.sum() ** 2) x = np.swapaxes(x, -2, -1) return np.real(x).astype(ori_dtype), np.imag(x).astype(ori_dtype) def _istft( x, sequence_length, sequence_stride, fft_length, length=None, window="hann", center=True, ): # pure numpy version of istft that matches librosa's implementation complex_input = x[0] + 1j * x[1] x = np.fft.irfft( complex_input, n=fft_length, axis=-1, norm="backward" ).astype(x[0].dtype) expected_output_len = fft_length + sequence_stride * (x.shape[-2] - 1) if window is not None: if isinstance(window, str): win = np.array( scipy.signal.get_window(window, sequence_length), dtype=x.dtype ) else: win = np.array(window, dtype=x.dtype) l_pad = (fft_length - sequence_length) // 2 r_pad = fft_length - sequence_length - l_pad win = np.pad(win, [[l_pad, r_pad]]) # square and sum _sequence_length = sequence_length + l_pad + r_pad denom = np.square(win) overlaps = -(-_sequence_length // sequence_stride) denom = np.pad( denom, [(0, overlaps * sequence_stride - _sequence_length)] ) denom = np.reshape(denom, [overlaps, sequence_stride]) denom = np.sum(denom, 0, keepdims=True) denom = np.tile(denom, [overlaps, 1]) denom = np.reshape(denom, [overlaps * sequence_stride]) win = np.divide(win, denom[:_sequence_length]) x = np.multiply(x, win) # overlap_sequences def _overlap_sequences(x, sequence_stride): *batch_shape, num_sequences, sequence_length = x.shape flat_batchsize = math.prod(batch_shape) x = np.reshape(x, (flat_batchsize, num_sequences, sequence_length)) output_size = sequence_stride * (num_sequences - 1) + sequence_length nstep_per_segment = 1 + (sequence_length - 1) // sequence_stride padded_segment_len = nstep_per_segment * sequence_stride x = np.pad( x, ((0, 0), (0, 0), (0, padded_segment_len - sequence_length)) ) x = np.reshape( x, (flat_batchsize, num_sequences, nstep_per_segment, sequence_stride), ) x = x.transpose((0, 2, 1, 3)) x = np.pad(x, ((0, 0), (0, 0), (0, num_sequences), (0, 0))) shrinked = x.shape[2] - 1 x = np.reshape(x, (flat_batchsize, -1)) x = x[:, : (nstep_per_segment * shrinked * sequence_stride)] x = np.reshape( x, (flat_batchsize, nstep_per_segment, shrinked * sequence_stride) ) x = np.sum(x, axis=1)[:, :output_size] return np.reshape(x, tuple(batch_shape) + (-1,)) x = _overlap_sequences(x, sequence_stride) if backend.backend() in {"numpy", "jax"}: x = np.nan_to_num(x) start = 0 if center is False else fft_length // 2 if length is not None: end = start + length elif center: end = -(fft_length // 2) else: end = expected_output_len return x[..., start:end] class MathOpsDynamicShapeTest(testing.TestCase, parameterized.TestCase): def test_segment_sum(self): data = KerasTensor((None, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_sum(data, segment_ids) self.assertEqual(outputs.shape, (None, 4)) data = KerasTensor((None, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_sum(data, segment_ids, num_segments=5) self.assertEqual(outputs.shape, (5, 4)) def test_segment_max(self): data = KerasTensor((None, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_max(data, segment_ids) self.assertEqual(outputs.shape, (None, 4)) data = KerasTensor((None, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_max(data, segment_ids, num_segments=5) self.assertEqual(outputs.shape, (5, 4)) def test_top_k(self): x = KerasTensor((None, 2, 3)) values, indices = kmath.top_k(x, k=1) self.assertEqual(values.shape, (None, 2, 1)) self.assertEqual(indices.shape, (None, 2, 1)) def test_in_top_k(self): targets = KerasTensor((None,)) predictions = KerasTensor((None, 10)) self.assertEqual( kmath.in_top_k(targets, predictions, k=1).shape, (None,) ) def test_logsumexp(self): x = KerasTensor((None, 2, 3), dtype="float32") result = kmath.logsumexp(x) self.assertEqual(result.shape, ()) def test_extract_sequences(self): # Defined dimension x = KerasTensor((None, 32), dtype="float32") sequence_length = 3 sequence_stride = 2 outputs = kmath.extract_sequences(x, sequence_length, sequence_stride) num_sequences = 1 + (x.shape[-1] - sequence_length) // sequence_stride self.assertEqual(outputs.shape, (None, num_sequences, sequence_length)) # Undefined dimension x = KerasTensor((None, None), dtype="float32") sequence_length = 3 sequence_stride = 2 outputs = kmath.extract_sequences(x, sequence_length, sequence_stride) self.assertEqual(outputs.shape, (None, None, sequence_length)) def test_fft(self): real = KerasTensor((None, 4, 3), dtype="float32") imag = KerasTensor((None, 4, 3), dtype="float32") real_output, imag_output = kmath.fft((real, imag)) ref = np.fft.fft(np.ones((2, 4, 3))) ref_shape = (None,) + ref.shape[1:] self.assertEqual(real_output.shape, ref_shape) self.assertEqual(imag_output.shape, ref_shape) def test_fft2(self): real = KerasTensor((None, 4, 3), dtype="float32") imag = KerasTensor((None, 4, 3), dtype="float32") real_output, imag_output = kmath.fft2((real, imag)) ref = np.fft.fft2(np.ones((2, 4, 3))) ref_shape = (None,) + ref.shape[1:] self.assertEqual(real_output.shape, ref_shape) self.assertEqual(imag_output.shape, ref_shape) @parameterized.parameters([(None,), (1,), (5,)]) def test_rfft(self, fft_length): x = KerasTensor((None, 4, 3), dtype="float32") real_output, imag_output = kmath.rfft(x, fft_length=fft_length) ref = np.fft.rfft(np.ones((2, 4, 3)), n=fft_length) ref_shape = (None,) + ref.shape[1:] self.assertEqual(real_output.shape, ref_shape) self.assertEqual(imag_output.shape, ref_shape) @parameterized.parameters([(None,), (1,), (5,)]) def test_irfft(self, fft_length): real = KerasTensor((None, 4, 3), dtype="float32") imag = KerasTensor((None, 4, 3), dtype="float32") output = kmath.irfft((real, imag), fft_length=fft_length) ref = np.fft.irfft(np.ones((2, 4, 3)), n=fft_length) ref_shape = (None,) + ref.shape[1:] self.assertEqual(output.shape, ref_shape) def test_stft(self): x = KerasTensor((None, 32), dtype="float32") sequence_length = 10 sequence_stride = 3 fft_length = 15 real_output, imag_output = kmath.stft( x, sequence_length, sequence_stride, fft_length ) real_ref, imag_ref = _stft( np.ones((2, 32)), sequence_length, sequence_stride, fft_length ) real_ref_shape = (None,) + real_ref.shape[1:] imag_ref_shape = (None,) + imag_ref.shape[1:] self.assertEqual(real_output.shape, real_ref_shape) self.assertEqual(imag_output.shape, imag_ref_shape) def test_istft(self): sequence_length = 10 sequence_stride = 3 fft_length = 15 real = KerasTensor((None, 32), dtype="float32") imag = KerasTensor((None, 32), dtype="float32") output = kmath.istft( (real, imag), sequence_length, sequence_stride, fft_length ) ref = _istft( (np.ones((5, 32)), np.ones((5, 32))), sequence_length, sequence_stride, fft_length, ) ref_shape = (None,) + ref.shape[1:] self.assertEqual(output.shape, ref_shape) def test_rsqrt(self): x = KerasTensor([None, 3]) self.assertEqual(kmath.rsqrt(x).shape, (None, 3)) class MathOpsStaticShapeTest(testing.TestCase): @pytest.mark.skipif( backend.backend() == "jax", reason="JAX does not support `num_segments=None`.", ) def test_segment_sum(self): data = KerasTensor((10, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_sum(data, segment_ids) self.assertEqual(outputs.shape, (None, 4)) def test_segment_sum_explicit_num_segments(self): data = KerasTensor((10, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_sum(data, segment_ids, num_segments=5) self.assertEqual(outputs.shape, (5, 4)) @pytest.mark.skipif( backend.backend() == "jax", reason="JAX does not support `num_segments=None`.", ) def test_segment_max(self): data = KerasTensor((10, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_max(data, segment_ids) self.assertEqual(outputs.shape, (None, 4)) def test_segment_max_explicit_num_segments(self): data = KerasTensor((10, 4), dtype="float32") segment_ids = KerasTensor((10,), dtype="int32") outputs = kmath.segment_max(data, segment_ids, num_segments=5) self.assertEqual(outputs.shape, (5, 4)) def test_topk(self): x = KerasTensor((1, 2, 3)) values, indices = kmath.top_k(x, k=1) self.assertEqual(values.shape, (1, 2, 1)) self.assertEqual(indices.shape, (1, 2, 1)) def test_in_top_k(self): targets = KerasTensor((5,)) predictions = KerasTensor((5, 10)) self.assertEqual(kmath.in_top_k(targets, predictions, k=1).shape, (5,)) def test_logsumexp(self): x = KerasTensor((1, 2, 3), dtype="float32") result = kmath.logsumexp(x) self.assertEqual(result.shape, ()) def test_extract_sequences(self): x = KerasTensor((10, 16), dtype="float32") sequence_length = 3 sequence_stride = 2 outputs = kmath.extract_sequences(x, sequence_length, sequence_stride) num_sequences = 1 + (x.shape[-1] - sequence_length) // sequence_stride self.assertEqual(outputs.shape, (10, num_sequences, sequence_length)) def test_fft(self): real = KerasTensor((2, 4, 3), dtype="float32") imag = KerasTensor((2, 4, 3), dtype="float32") real_output, imag_output = kmath.fft((real, imag)) ref = np.fft.fft(np.ones((2, 4, 3))) self.assertEqual(real_output.shape, ref.shape) self.assertEqual(imag_output.shape, ref.shape) def test_fft2(self): real = KerasTensor((2, 4, 3), dtype="float32") imag = KerasTensor((2, 4, 3), dtype="float32") real_output, imag_output = kmath.fft2((real, imag)) ref = np.fft.fft2(np.ones((2, 4, 3))) self.assertEqual(real_output.shape, ref.shape) self.assertEqual(imag_output.shape, ref.shape) def test_rfft(self): x = KerasTensor((2, 4, 3), dtype="float32") real_output, imag_output = kmath.rfft(x) ref = np.fft.rfft(np.ones((2, 4, 3))) self.assertEqual(real_output.shape, ref.shape) self.assertEqual(imag_output.shape, ref.shape) def test_irfft(self): real = KerasTensor((2, 4, 3), dtype="float32") imag = KerasTensor((2, 4, 3), dtype="float32") output = kmath.irfft((real, imag)) ref = np.fft.irfft(np.ones((2, 4, 3))) self.assertEqual(output.shape, ref.shape) def test_rsqrt(self): x = KerasTensor([4, 3], dtype="float32") self.assertEqual(kmath.rsqrt(x).shape, (4, 3)) def test_stft(self): x = KerasTensor((2, 32), dtype="float32") sequence_length = 10 sequence_stride = 3 fft_length = 15 real_output, imag_output = kmath.stft( x, sequence_length, sequence_stride, fft_length ) real_ref, imag_ref = _stft( np.ones((2, 32)), sequence_length, sequence_stride, fft_length ) self.assertEqual(real_output.shape, real_ref.shape) self.assertEqual(imag_output.shape, imag_ref.shape) def test_istft(self): # sequence_stride must <= x[0].shape[-1] # sequence_stride must >= fft_length / num_sequences sequence_length = 10 sequence_stride = 3 fft_length = 15 num_sequences = fft_length // sequence_stride + 1 real = KerasTensor((num_sequences, 32), dtype="float32") imag = KerasTensor((num_sequences, 32), dtype="float32") output = kmath.istft( (real, imag), sequence_length, sequence_stride, fft_length ) ref = _istft( (np.ones((num_sequences, 32)), np.ones((num_sequences, 32))), sequence_length, sequence_stride, fft_length, ) self.assertEqual(output.shape, ref.shape) class MathOpsCorrectnessTest(testing.TestCase, parameterized.TestCase): @pytest.mark.skipif( backend.backend() == "jax", reason="JAX does not support `num_segments=None`.", ) def test_segment_sum(self): # Test 1D case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_sum(data, segment_ids) # Segment 0: 1 + 2 = 3 # Segment 1: 3 + 4 + 5 = 12 # Segment 2: 6 + 7 + 8 = 21 expected = np.array([3, 12, 21], dtype=np.float32) self.assertAllClose(outputs, expected) # Test N-D case. data = np.random.rand(9, 3, 3) segment_ids = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_sum(data, segment_ids) expected = np.zeros((3, 3, 3)) for i in range(data.shape[0]): segment_id = segment_ids[i] expected[segment_id] += data[i] self.assertAllClose(outputs, expected) def test_segment_sum_explicit_num_segments(self): # Test 1D case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_sum(data, segment_ids, num_segments=4) expected = np.array([3, 12, 21, 0], dtype=np.float32) self.assertAllClose(outputs, expected) # Test 1D with -1 case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, -1, 2, 2, -1], dtype=np.int32) outputs = kmath.segment_sum(data, segment_ids, num_segments=4) # Segment ID 0: First two elements (1 + 2) = 3 # Segment ID 1: Next two elements (3 + 4) = 7 # Segment ID -1: Ignore the next two elements, because segment ID is -1. # Segment ID 2: Next two elements (6 + 7) = 13 # Segment ID 3: No elements, so output is 0. expected = np.array([3, 7, 13, 0], dtype=np.float32) self.assertAllClose(outputs, expected) # Test N-D case. data = np.random.rand(9, 3, 3) segment_ids = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_sum(data, segment_ids, num_segments=4) expected = np.zeros((4, 3, 3)) for i in range(data.shape[0]): segment_id = segment_ids[i] if segment_id != -1: expected[segment_id] += data[i] self.assertAllClose(outputs, expected) @pytest.mark.skipif( backend.backend() == "jax", reason="JAX does not support `num_segments=None`.", ) def test_segment_max(self): # Test 1D case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_max(data, segment_ids) # Segment ID 0: Max of the first two elements = 2 # Segment ID 1: Max of the next three elements = 5 # Segment ID 2: Max of the next three elements = 8 expected = np.array([2, 5, 8], dtype=np.float32) self.assertAllClose(outputs, expected) # Test N-D case. data = np.random.rand(9, 3, 3) segment_ids = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_max(data, segment_ids) expected = np.zeros((3, 3, 3)) for i in range(data.shape[0]): segment_id = segment_ids[i] expected[segment_id] = np.maximum(expected[segment_id], data[i]) self.assertAllClose(outputs, expected) def test_segment_max_explicit_num_segments(self): # Test 1D case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_max(data, segment_ids, num_segments=3) # Segment ID 0: Max of the first two elements = 2 # Segment ID 1: Max of the next three elements = 5 # Segment ID 2: Max of the next three elements = 8 expected = np.array([2, 5, 8], dtype=np.float32) self.assertAllClose(outputs, expected) # Test 1D with -1 case. data = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.float32) segment_ids = np.array([0, 0, 1, 1, -1, 2, 2, -1], dtype=np.int32) outputs = kmath.segment_max(data, segment_ids, num_segments=3) expected = np.array([2, 4, 7], dtype=np.float32) self.assertAllClose(outputs, expected) # Test N-D case. data = np.random.rand(9, 3, 3) segment_ids = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32) outputs = kmath.segment_max(data, segment_ids, num_segments=3) expected = np.full((3, 3, 3), -np.inf) for i in range(data.shape[0]): segment_id = segment_ids[i] expected[segment_id] = np.maximum(expected[segment_id], data[i]) self.assertAllClose(outputs, expected) def test_top_k(self): x = np.array([0, 4, 2, 1, 3, -1], dtype=np.float32) values, indices = kmath.top_k(x, k=2) self.assertAllClose(values, [4, 3]) self.assertAllClose(indices, [1, 4]) x = np.array([0, 4, 2, 1, 3, -1], dtype=np.float32) values, indices = kmath.top_k(x, k=2, sorted=False) # Any order ok when `sorted=False`. self.assertEqual(set(backend.convert_to_numpy(values)), set([4, 3])) self.assertEqual(set(backend.convert_to_numpy(indices)), set([1, 4])) x = np.random.rand(5, 5) outputs = kmath.top_k(x, k=2) expected_values = np.zeros((5, 2)) expected_indices = np.zeros((5, 2), dtype=np.int32) for i in range(x.shape[0]): top_k_indices = np.argsort(x[i])[-2:][::-1] expected_values[i] = x[i, top_k_indices] expected_indices[i] = top_k_indices self.assertAllClose(outputs[0], expected_values) self.assertAllClose(outputs[1], expected_indices) def test_in_top_k(self): targets = np.array([1, 0, 2]) predictions = np.array( [ [0.1, 0.9, 0.8, 0.8], [0.05, 0.95, 0, 1], [0.1, 0.8, 0.3, 1], ] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=1), [True, False, False] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=2), [True, False, False] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=3), [True, True, True] ) # Test tie cases. targets = np.array([1, 0, 2]) predictions = np.array( [ [0.1, 0.9, 0.8, 0.8], [0.95, 0.95, 0, 0.95], [0.1, 0.8, 0.8, 0.95], ] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=1), [True, True, False] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=2), [True, True, True] ) self.assertAllEqual( kmath.in_top_k(targets, predictions, k=3), [True, True, True] ) def test_logsumexp(self): x = np.random.rand(5, 5) outputs = kmath.logsumexp(x) expected = np.log(np.sum(np.exp(x))) self.assertAllClose(outputs, expected) outputs = kmath.logsumexp(x, axis=1) expected = np.log(np.sum(np.exp(x), axis=1)) self.assertAllClose(outputs, expected) def test_extract_sequences(self): # Test 1D case. x = np.random.random((10,)) sequence_length = 3 sequence_stride = 2 output = kmath.extract_sequences(x, sequence_length, sequence_stride) num_sequences = 1 + (x.shape[-1] - sequence_length) // sequence_stride expected = np.zeros(shape=(num_sequences, sequence_length)) pos = 0 for i in range(num_sequences): expected[i] = x[pos : pos + sequence_length] pos += sequence_stride self.assertAllClose(output, expected) # Test N-D case. x = np.random.random((4, 8)) sequence_length = 3 sequence_stride = 2 output = kmath.extract_sequences(x, sequence_length, sequence_stride) num_sequences = 1 + (x.shape[-1] - sequence_length) // sequence_stride expected = np.zeros(shape=(4, num_sequences, sequence_length)) pos = 0 for i in range(num_sequences): expected[:, i] = x[:, pos : pos + sequence_length] pos += sequence_stride self.assertAllClose(output, expected) def test_fft(self): real = np.random.random((2, 4, 3)) imag = np.random.random((2, 4, 3)) complex_arr = real + 1j * imag real_output, imag_output = kmath.fft((real, imag)) ref = np.fft.fft(complex_arr) real_ref = np.real(ref) imag_ref = np.imag(ref) self.assertAllClose(real_ref, real_output) self.assertAllClose(imag_ref, imag_output) def test_fft2(self): real = np.random.random((2, 4, 3)) imag = np.random.random((2, 4, 3)) complex_arr = real + 1j * imag real_output, imag_output = kmath.fft2((real, imag)) ref = np.fft.fft2(complex_arr) real_ref = np.real(ref) imag_ref = np.imag(ref) self.assertAllClose(real_ref, real_output) self.assertAllClose(imag_ref, imag_output) @parameterized.parameters([(None,), (3,), (15,)]) def test_rfft(self, n): # Test 1D. x = np.random.random((10,)) real_output, imag_output = kmath.rfft(x, fft_length=n) ref = np.fft.rfft(x, n=n) real_ref = np.real(ref) imag_ref = np.imag(ref) self.assertAllClose(real_ref, real_output, atol=1e-5, rtol=1e-5) self.assertAllClose(imag_ref, imag_output, atol=1e-5, rtol=1e-5) # Test N-D case. x = np.random.random((2, 3, 10)) real_output, imag_output = kmath.rfft(x, fft_length=n) ref = np.fft.rfft(x, n=n) real_ref = np.real(ref) imag_ref = np.imag(ref) self.assertAllClose(real_ref, real_output, atol=1e-5, rtol=1e-5) self.assertAllClose(imag_ref, imag_output, atol=1e-5, rtol=1e-5) @parameterized.parameters([(None,), (3,), (15,)]) def test_irfft(self, n): # Test 1D. real = np.random.random((10,)) imag = np.random.random((10,)) complex_arr = real + 1j * imag output = kmath.irfft((real, imag), fft_length=n) ref = np.fft.irfft(complex_arr, n=n) self.assertAllClose(output, ref, atol=1e-5, rtol=1e-5) # Test N-D case. real = np.random.random((2, 3, 10)) imag = np.random.random((2, 3, 10)) complex_arr = real + 1j * imag output = kmath.irfft((real, imag), fft_length=n) ref = np.fft.irfft(complex_arr, n=n) self.assertAllClose(output, ref, atol=1e-5, rtol=1e-5) @parameterized.parameters( [ (32, 8, 32, "hann", True), (8, 8, 16, "hann", True), (4, 4, 7, "hann", True), (32, 8, 32, "hamming", True), (32, 8, 32, "hann", False), (32, 8, 32, np.ones((32,)), True), (32, 8, 32, None, True), ] ) def test_stft( self, sequence_length, sequence_stride, fft_length, window, center ): # Test 1D case. x = np.random.random((32,)) real_output, imag_output = kmath.stft( x, sequence_length, sequence_stride, fft_length, window, center ) real_ref, imag_ref = _stft( x, sequence_length, sequence_stride, fft_length, window, center ) self.assertAllClose(real_ref, real_output, atol=1e-5, rtol=1e-5) self.assertAllClose(imag_ref, imag_output, atol=1e-5, rtol=1e-5) # Test N-D case. x = np.random.random((2, 3, 32)) real_output, imag_output = kmath.stft( x, sequence_length, sequence_stride, fft_length, window, center ) real_ref, imag_ref = _stft( x, sequence_length, sequence_stride, fft_length, window, center ) self.assertAllClose(real_ref, real_output, atol=1e-5, rtol=1e-5) self.assertAllClose(imag_ref, imag_output, atol=1e-5, rtol=1e-5) @parameterized.parameters( [ (32, 8, 32, "hann", True), (8, 8, 16, "hann", True), (4, 4, 7, "hann", True), (32, 8, 32, "hamming", True), (8, 4, 8, "hann", False), (32, 8, 32, np.ones((32,)), True), (32, 8, 32, None, True), ] ) def test_istft( self, sequence_length, sequence_stride, fft_length, window, center ): # sequence_stride must <= x[0].shape[-1] # sequence_stride must >= fft_length / num_sequences # Test 1D case. x = np.random.random((256,)) real_x, imag_x = _stft( x, sequence_length, sequence_stride, fft_length, window, center ) output = kmath.istft( (real_x, imag_x), sequence_length, sequence_stride, fft_length, window=window, center=center, ) ref = _istft( (real_x, imag_x), sequence_length, sequence_stride, fft_length, window=window, center=center, ) if backend.backend() in ("numpy", "jax", "torch"): # these backends have different implementation for the boundary of # the output, so we need to truncate 5% befroe assertAllClose truncated_len = int(output.shape[-1] * 0.05) output = output[..., truncated_len:-truncated_len] ref = ref[..., truncated_len:-truncated_len] self.assertAllClose(output, ref, atol=1e-5, rtol=1e-5) # Test N-D case. x = np.random.random((2, 3, 256)) real_x, imag_x = _stft( x, sequence_length, sequence_stride, fft_length, window, center ) output = kmath.istft( (real_x, imag_x), sequence_length, sequence_stride, fft_length, window=window, center=center, ) ref = _istft( (real_x, imag_x), sequence_length, sequence_stride, fft_length, window=window, center=center, ) if backend.backend() in ("numpy", "jax", "torch"): # these backends have different implementation for the boundary of # the output, so we need to truncate 5% befroe assertAllClose truncated_len = int(output.shape[-1] * 0.05) output = output[..., truncated_len:-truncated_len] ref = ref[..., truncated_len:-truncated_len] self.assertAllClose(output, ref, atol=1e-5, rtol=1e-5) def test_rsqrt(self): x = np.array([[1, 4, 9], [16, 25, 36]], dtype="float32") self.assertAllClose(kmath.rsqrt(x), 1 / np.sqrt(x)) self.assertAllClose(kmath.Rsqrt()(x), 1 / np.sqrt(x)) def test_erf_operation_basic(self): # Sample values for testing sample_values = np.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) # Expected output using numpy's approximation of the error function expected_output = scipy.special.erf(sample_values) # Output from the erf operation in keras_core output_from_erf_op = kmath.erf(sample_values) # Assert that the outputs are close self.assertAllClose(expected_output, output_from_erf_op, atol=1e-4) def test_erf_operation_dtype(self): # Test for float32 and float64 data types for dtype in ("float32", "float64"): sample_values = np.array( [-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0], dtype=dtype ) expected_output = scipy.special.erf(sample_values) output_from_erf_op = kmath.erf(sample_values) self.assertAllClose(expected_output, output_from_erf_op, atol=1e-4) def test_erf_operation_edge_cases(self): # Test for edge cases edge_values = np.array([1e5, -1e5, 1e-5, -1e-5], dtype=np.float64) expected_output = scipy.special.erf(edge_values) output_from_edge_erf_op = kmath.erf(edge_values) self.assertAllClose(expected_output, output_from_edge_erf_op, atol=1e-4) def test_erfinv_operation_basic(self): # Sample values for testing sample_values = np.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) # Expected output using numpy's approximation of the error function expected_output = scipy.special.erfinv(sample_values) # Output from the erf operation in keras_core output_from_erfinv_op = kmath.erfinv(sample_values) # Assert that the outputs are close self.assertAllClose(expected_output, output_from_erfinv_op, atol=1e-4) def test_erfinv_operation_dtype(self): # Test for float32 and float64 data types for dtype in ("float32", "float64"): sample_values = np.array( [-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0], dtype=dtype ) expected_output = scipy.special.erfinv(sample_values) output_from_erfinv_op = kmath.erfinv(sample_values) self.assertAllClose( expected_output, output_from_erfinv_op, atol=1e-4 ) def test_erfinv_operation_edge_cases(self): # Test for edge cases edge_values = np.array([1e5, -1e5, 1e-5, -1e-5], dtype=np.float64) expected_output = scipy.special.erfinv(edge_values) output_from_edge_erfinv_op = kmath.erfinv(edge_values) self.assertAllClose( expected_output, output_from_edge_erfinv_op, atol=1e-4 ) class MathDtypeTest(testing.TestCase, parameterized.TestCase): """Test the floating dtype to verify that the behavior matches JAX.""" # TODO: Using uint64 will lead to weak type promotion (`float`), # resulting in different behavior between JAX and Keras. Currently, we # are skipping the test for uint64 ALL_DTYPES = [ x for x in ALLOWED_DTYPES if x not in ["string", "uint64"] ] + [None] INT_DTYPES = [x for x in ALLOWED_DTYPES if "int" in x and x != "uint64"] FLOAT_DTYPES = [x for x in ALLOWED_DTYPES if "float" in x] if backend.backend() == "torch": # TODO: torch doesn't support uint16, uint32 and uint64 ALL_DTYPES = [ x for x in ALL_DTYPES if x not in ["uint16", "uint32", "uint64"] ] INT_DTYPES = [ x for x in INT_DTYPES if x not in ["uint16", "uint32", "uint64"] ] def setUp(self): from jax.experimental import enable_x64 self.jax_enable_x64 = enable_x64() self.jax_enable_x64.__enter__() return super().setUp() def tearDown(self) -> None: self.jax_enable_x64.__exit__(None, None, None) return super().tearDown() class ExtractSequencesOpTest(testing.TestCase): def test_extract_sequences_init_length_1_stride_1(self): extract_op = kmath.ExtractSequences( sequence_length=1, sequence_stride=1 ) self.assertIsNotNone(extract_op) self.assertEqual(extract_op.sequence_length, 1) self.assertEqual(extract_op.sequence_stride, 1) def test_extract_sequences_init_length_5_stride_2(self): extract_op = kmath.ExtractSequences( sequence_length=5, sequence_stride=2 ) self.assertIsNotNone(extract_op) self.assertEqual(extract_op.sequence_length, 5) self.assertEqual(extract_op.sequence_stride, 2) def test_compute_output_spec_low_rank(self): extract_op = kmath.ExtractSequences( sequence_length=5, sequence_stride=1 ) low_rank_input = np.array(42) error_message = r"Input should have rank >= 1. Received: .*" with self.assertRaisesRegex(ValueError, error_message): extract_op.compute_output_spec(low_rank_input) def test_extract_sequences_call(self): sequence_length, sequence_stride = 5, 2 extract_op = kmath.ExtractSequences(sequence_length, sequence_stride) test_input = np.random.rand(10, 20) result = extract_op.call(test_input) expected_shape = self.calculate_expected_shape( test_input.shape, sequence_length, sequence_stride ) self.assertEqual(result.shape, expected_shape) def calculate_expected_shape( self, input_shape, sequence_length, sequence_stride ): num_sequences = ( (input_shape[1] - sequence_length) // sequence_stride ) + 1 return (input_shape[0], num_sequences, sequence_length) class SegmentSumTest(testing.TestCase): def test_segment_sum_call(self): data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32) segment_ids = np.array([0, 0, 1], dtype=np.int32) num_segments = 2 sorted_segments = False segment_sum_op = kmath.SegmentSum( num_segments=num_segments, sorted=sorted_segments ) output = segment_sum_op.call(data, segment_ids) expected_output = np.array([[5, 7, 9], [7, 8, 9]], dtype=np.float32) self.assertAllClose(output, expected_output) class SegmentMaxTest(testing.TestCase): def test_segment_max_call(self): data = np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9]], dtype=np.float32) segment_ids = np.array([0, 0, 1], dtype=np.int32) num_segments = 2 sorted_segments = False segment_max_op = kmath.SegmentMax( num_segments=num_segments, sorted=sorted_segments ) output = segment_max_op.call(data, segment_ids) expected_output = np.array([[2, 5, 8], [3, 6, 9]], dtype=np.float32) self.assertAllClose(output, expected_output) class TopKTest(testing.TestCase): def test_top_k_call_values(self): data = np.array([[1, 3, 2], [4, 6, 5]], dtype=np.float32) k = 2 sorted_flag = True top_k_op = kmath.TopK(k=k, sorted=sorted_flag) values, _ = top_k_op.call(data) expected_values = np.array([[3, 2], [6, 5]], dtype=np.float32) self.assertAllClose(values, expected_values) def test_top_k_call_indices(self): data = np.array([[1, 3, 2], [4, 6, 5]], dtype=np.float32) k = 2 sorted_flag = True top_k_op = kmath.TopK(k=k, sorted=sorted_flag) _, indices = top_k_op.call(data) expected_indices = np.array([[1, 2], [1, 2]], dtype=np.int32) self.assertAllClose(indices, expected_indices) class InTopKTest(testing.TestCase): def test_in_top_k_call(self): targets = np.array([2, 0, 1], dtype=np.int32) predictions = np.array( [[0.1, 0.2, 0.7], [1.0, 0.2, 0.3], [0.2, 0.6, 0.2]], dtype=np.float32, ) k = 2 in_top_k_op = kmath.InTopK(k=k) output = in_top_k_op.call(targets, predictions) expected_output = np.array([True, True, True], dtype=bool) self.assertAllEqual(output, expected_output) class LogsumexpTest(testing.TestCase): def test_logsumexp_call(self): x = np.array([[1, 2], [3, 4]], dtype=np.float32) axis = 0 keepdims = True logsumexp_op = kmath.Logsumexp(axis=axis, keepdims=keepdims) output = logsumexp_op.call(x) expected_output = np.log( np.sum(np.exp(x), axis=axis, keepdims=keepdims) ) self.assertAllClose(output, expected_output) class FFTTest(testing.TestCase): def test_fft_input_not_tuple_or_list(self): fft_op = kmath.FFT() with self.assertRaisesRegex( ValueError, "Input `x` should be a tuple of two tensors" ): fft_op.compute_output_spec(np.array([1, 2, 3])) def test_fft_input_parts_different_shapes(self): fft_op = kmath.FFT() real = np.array([1, 2, 3]) imag = np.array([1, 2]) with self.assertRaisesRegex( ValueError, "Both the real and imaginary parts should have the same shape", ): fft_op.compute_output_spec((real, imag)) def test_fft_input_not_1d(self): fft_op = kmath.FFT() real = np.array(1) imag = np.array(1) with self.assertRaisesRegex(ValueError, "Input should have rank >= 1"): fft_op.compute_output_spec((real, imag)) def test_fft_last_axis_not_fully_defined(self): fft_op = kmath.FFT() real = KerasTensor(shape=(None,), dtype="float32") imag = KerasTensor(shape=(None,), dtype="float32") with self.assertRaisesRegex( ValueError, "Input should have its -1th axis fully-defined" ): fft_op.compute_output_spec((real, imag)) def test_fft_init_default_axis(self): fft_op = kmath.FFT() self.assertEqual(fft_op.axis, -1, "Default axis should be -1") class FFT2Test(testing.TestCase): def test_fft2_correct_input(self): fft2_op = kmath.FFT2() real_part = np.random.rand(2, 3, 4) imag_part = np.random.rand(2, 3, 4) # This should not raise any errors fft2_op.compute_output_spec((real_part, imag_part)) def test_fft2_incorrect_input_type(self): fft2_op = kmath.FFT2() incorrect_input = np.array([1, 2, 3]) # Not a tuple or list with self.assertRaisesRegex( ValueError, "should be a tuple of two tensors" ): fft2_op.compute_output_spec(incorrect_input) def test_fft2_mismatched_shapes(self): fft2_op = kmath.FFT2() real_part = np.random.rand(2, 3, 4) imag_part = np.random.rand(2, 3) # Mismatched shape with self.assertRaisesRegex( ValueError, "Both the real and imaginary parts should have the same shape", ): fft2_op.compute_output_spec((real_part, imag_part)) def test_fft2_low_rank(self): fft2_op = kmath.FFT2() low_rank_input = np.random.rand(3) # Rank of 1 with self.assertRaisesRegex(ValueError, "Input should have rank >= 2"): fft2_op.compute_output_spec((low_rank_input, low_rank_input)) def test_fft2_undefined_dimensions(self): fft2_op = kmath.FFT2() real_part = KerasTensor(shape=(None, None, 3), dtype="float32") imag_part = KerasTensor(shape=(None, None, 3), dtype="float32") with self.assertRaisesRegex( ValueError, "Input should have its .* axes fully-defined" ): fft2_op.compute_output_spec((real_part, imag_part)) class RFFTTest(testing.TestCase): def test_rfft_low_rank_input(self): rfft_op = kmath.RFFT() low_rank_input = np.array(5) with self.assertRaisesRegex(ValueError, "Input should have rank >= 1"): rfft_op.compute_output_spec(low_rank_input) def test_rfft_defined_fft_length(self): fft_length = 10 rfft_op = kmath.RFFT(fft_length=fft_length) input_tensor = np.random.rand(3, 8) expected_last_dimension = fft_length // 2 + 1 expected_shape = input_tensor.shape[:-1] + (expected_last_dimension,) output_tensors = rfft_op.compute_output_spec(input_tensor) for output_tensor in output_tensors: self.assertEqual(output_tensor.shape, expected_shape) def test_rfft_undefined_fft_length_defined_last_dim(self): rfft_op = kmath.RFFT() input_tensor = np.random.rand(3, 8) expected_last_dimension = input_tensor.shape[-1] // 2 + 1 expected_shape = input_tensor.shape[:-1] + ( expected_last_dimension, ) output_tensors = rfft_op.compute_output_spec(input_tensor) for output_tensor in output_tensors: self.assertEqual(output_tensor.shape, expected_shape) def test_rfft_undefined_fft_length_undefined_last_dim(self): rfft_op = kmath.RFFT() input_tensor = KerasTensor(shape=(None, None), dtype="float32") expected_shape = input_tensor.shape[:-1] + (None,) output_tensors = rfft_op.compute_output_spec(input_tensor) for output_tensor in output_tensors: self.assertEqual(output_tensor.shape, expected_shape) class ISTFTTest(testing.TestCase): def test_istft_incorrect_input_type(self): istft_op = kmath.ISTFT( sequence_length=5, sequence_stride=2, fft_length=10 ) incorrect_input = np.array([1, 2, 3]) with self.assertRaisesRegex( ValueError, "should be a tuple of two tensors" ): istft_op.compute_output_spec(incorrect_input) def test_istft_mismatched_shapes(self): istft_op = kmath.ISTFT( sequence_length=5, sequence_stride=2, fft_length=10 ) real_part = np.random.rand(2, 3, 4) imag_part = np.random.rand(2, 3) with self.assertRaisesRegex( ValueError, "Both the real and imaginary parts should have the same shape", ): istft_op.compute_output_spec((real_part, imag_part)) def test_istft_low_rank_input(self): istft_op = kmath.ISTFT( sequence_length=5, sequence_stride=2, fft_length=10 ) low_rank_input = np.random.rand(3) with self.assertRaisesRegex(ValueError, "Input should have rank >= 2"): istft_op.compute_output_spec((low_rank_input, low_rank_input))
keras/keras/ops/math_test.py/0
{ "file_path": "keras/keras/ops/math_test.py", "repo_id": "keras", "token_count": 21787 }
156
import numpy as np from absl.testing import parameterized from keras import backend from keras import ops from keras import testing from keras.optimizers.loss_scale_optimizer import LossScaleOptimizer from keras.optimizers.sgd import SGD class LossScaleOptimizerTest(testing.TestCase, parameterized.TestCase): def _skip_test_for_stateless(self, stateless): if not stateless and backend.backend() == "jax": self.skipTest( "LossScaleOptimizer must use stateless_apply with JAX." ) if stateless and backend.backend() == "tensorflow": self.skipTest( "stateless_apply is not supported with the TF backend." ) def test_config(self): inner_optimizer = SGD( learning_rate=0.5, momentum=0.06, nesterov=True, weight_decay=0.004, ) optimizer = LossScaleOptimizer(inner_optimizer) self.run_class_serialization_test(optimizer) @parameterized.named_parameters(("stateless", True), ("stateful", False)) def test_finite_step(self, stateless): self._skip_test_for_stateless(stateless) inner_optimizer = SGD(learning_rate=0.5) optimizer = LossScaleOptimizer(inner_optimizer) grads = [ops.array([1.0, 6.0, 7.0, 2.0]) * optimizer.initial_scale] vars = [backend.Variable([1.0, 2.0, 3.0, 4.0])] if stateless: optimizer.build(vars) vars, _ = optimizer.stateless_apply( optimizer.variables, grads, vars ) else: optimizer.apply(grads, vars) self.assertAllClose( vars, [[0.5, -1.0, -0.5, 3.0]], rtol=1e-4, atol=1e-4 ) @parameterized.named_parameters(("stateless", True), ("stateful", False)) def test_infinite_step(self, stateless): self._skip_test_for_stateless(stateless) inner_optimizer = SGD(learning_rate=0.5) optimizer = LossScaleOptimizer(inner_optimizer) grads = [ops.array([np.inf, np.inf, np.inf, np.inf])] vars = [backend.Variable([1.0, 2.0, 3.0, 4.0])] if stateless: optimizer.build(vars) vars, _ = optimizer.stateless_apply( optimizer.variables, grads, vars ) else: optimizer.apply(grads, vars) self.assertAllClose(vars, [[1.0, 2.0, 3.0, 4.0]], rtol=1e-4, atol=1e-4) @parameterized.named_parameters(("stateless", True), ("stateful", False)) def test_downscaling(self, stateless): self._skip_test_for_stateless(stateless) inner_optimizer = SGD(learning_rate=0.5) optimizer = LossScaleOptimizer(inner_optimizer, initial_scale=400.0) vars = [backend.Variable([1.0, 2.0, 3.0, 4.0])] optimizer.build(vars) opt_vars = optimizer.variables grads = [ops.array([np.inf, np.inf, np.inf, np.inf])] for _ in range(4): if stateless: _, opt_vars = optimizer.stateless_apply(opt_vars, grads, vars) for ref_v, v in zip(optimizer.variables, opt_vars): ref_v.assign(v) else: optimizer.apply(grads, vars) self.assertAllClose(optimizer.scale_loss(1.0), 25.0) @parameterized.named_parameters(("stateless", True), ("stateful", False)) def test_upscaling(self, stateless): self._skip_test_for_stateless(stateless) inner_optimizer = SGD(learning_rate=0.5) optimizer = LossScaleOptimizer( inner_optimizer, initial_scale=2.0, dynamic_growth_steps=2, ) vars = [backend.Variable([1.0, 2.0, 3.0, 4.0])] optimizer.build(vars) opt_vars = optimizer.variables grads = [ops.array([1.0, 6.0, 7.0, 2.0])] for _ in range(8): if stateless: _, opt_vars = optimizer.stateless_apply(opt_vars, grads, vars) for ref_v, v in zip(optimizer.variables, opt_vars): ref_v.assign(v) else: optimizer.apply(grads, vars) self.assertAllClose(optimizer.scale_loss(1.0), 32.0)
keras/keras/optimizers/loss_scale_optimizer_test.py/0
{ "file_path": "keras/keras/optimizers/loss_scale_optimizer_test.py", "repo_id": "keras", "token_count": 2089 }
157
import numpy as np import pytest from absl.testing import parameterized import keras from keras import backend from keras import ops from keras import testing from keras.random import random from keras.random import seed_generator from keras.utils.rng_utils import set_random_seed class RandomTest(testing.TestCase, parameterized.TestCase): @parameterized.parameters( {"seed": 10, "shape": (5,), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3, 4), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 10, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 10, "stddev": 3}, ) def test_normal(self, seed, shape, mean, stddev): np.random.seed(seed) np_res = np.random.normal(loc=mean, scale=stddev, size=shape) res = random.normal(shape, mean=mean, stddev=stddev, seed=seed) self.assertEqual(res.shape, shape) self.assertEqual(res.shape, np_res.shape) @parameterized.parameters( {"seed": 10, "shape": (5,), "minval": 0, "maxval": 1}, {"seed": 10, "shape": (2, 3), "minval": 0, "maxval": 1}, {"seed": 10, "shape": (2, 3, 4), "minval": 0, "maxval": 2}, {"seed": 10, "shape": (2, 3), "minval": -1, "maxval": 1}, {"seed": 10, "shape": (2, 3), "minval": 1, "maxval": 3}, ) def test_uniform(self, seed, shape, minval, maxval): np.random.seed(seed) np_res = np.random.uniform(low=minval, high=maxval, size=shape) res = random.uniform(shape, minval=minval, maxval=maxval, seed=seed) self.assertEqual(res.shape, shape) self.assertEqual(res.shape, np_res.shape) self.assertLessEqual(ops.max(res), maxval) self.assertGreaterEqual(ops.max(res), minval) @parameterized.parameters( {"seed": 10, "num_samples": 1, "batch_size": 1}, {"seed": 10, "num_samples": 5, "batch_size": 2}, {"seed": 10, "num_samples": 10, "batch_size": 4}, {"seed": 10, "num_samples": 15, "batch_size": 8}, ) def test_categorical(self, seed, num_samples, batch_size): np.random.seed(seed) # Create logits that definitely favors the batch index after a softmax # is applied. Without a softmax, this would be close to random. logits = np.eye(batch_size) * 1e5 + 1e6 res = random.categorical(logits, num_samples, seed=seed) # Outputs should have shape `(batch_size, num_samples)`, where each # output index matches the batch index. self.assertEqual(res.shape, (batch_size, num_samples)) expected = np.tile(np.arange(batch_size)[:, None], (1, num_samples)) self.assertAllClose(res, expected) def test_categorical_errors(self): with self.assertRaises(ValueError): random.categorical(np.ones((5,)), 5) with self.assertRaises(ValueError): random.categorical(np.ones((5, 5, 5)), 5) @parameterized.parameters( {"seed": 10, "shape": (5,), "min": 0, "max": 10, "dtype": "uint16"}, {"seed": 10, "shape": (2, 3), "min": 0, "max": 10, "dtype": "uint32"}, {"seed": 10, "shape": (2, 3, 4), "min": 0, "max": 2, "dtype": "int8"}, {"seed": 10, "shape": (2, 3), "min": -1, "max": 1, "dtype": "int16"}, {"seed": 10, "shape": (2, 3), "min": 1, "max": 3, "dtype": "int32"}, ) def test_randint(self, seed, shape, min, max, dtype): np.random.seed(seed) np_res = np.random.randint(low=min, high=max, size=shape) res = random.randint( shape, minval=min, maxval=max, seed=seed, dtype=dtype ) self.assertEqual(res.shape, shape) self.assertEqual(res.shape, np_res.shape) self.assertLessEqual(ops.max(res), max) self.assertGreaterEqual(ops.max(res), min) # Torch has incomplete dtype support for uints; will remap some dtypes. if keras.backend.backend() != "torch": self.assertEqual(backend.standardize_dtype(res.dtype), dtype) @parameterized.parameters( {"seed": 10, "shape": (5,), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3, 4), "mean": 0, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 10, "stddev": 1}, {"seed": 10, "shape": (2, 3), "mean": 10, "stddev": 3}, # Test list shapes. {"seed": 10, "shape": [2, 3], "mean": 10, "stddev": 3}, ) def test_truncated_normal(self, seed, shape, mean, stddev): np.random.seed(seed) np_res = np.random.normal(loc=mean, scale=stddev, size=shape) res = random.truncated_normal( shape, mean=mean, stddev=stddev, seed=seed ) self.assertEqual(res.shape, tuple(shape)) self.assertEqual(res.shape, np_res.shape) self.assertLessEqual(ops.max(res), mean + 2 * stddev) self.assertGreaterEqual(ops.max(res), mean - 2 * stddev) def test_dropout(self): x = ops.ones((3, 5)) self.assertAllClose(random.dropout(x, rate=0, seed=0), x) x_res = random.dropout(x, rate=0.8, seed=0) self.assertGreater(ops.max(x_res), ops.max(x)) self.assertGreater(ops.sum(x_res == 0), 2) @pytest.mark.skipif( keras.backend.backend() != "jax", reason="This test requires `jax` as the backend.", ) def test_dropout_jax_jit_stateless(self): import jax import jax.numpy as jnp x = ops.ones(3) @jax.jit def train_step(x): with keras.backend.StatelessScope(): x = keras.layers.Dropout(rate=0.1)(x, training=True) return x x = train_step(x) self.assertIsInstance(x, jnp.ndarray) def test_dropout_noise_shape(self): inputs = ops.ones((2, 3, 5, 7)) x = random.dropout( inputs, rate=0.3, noise_shape=[None, 3, 5, None], seed=0 ) self.assertEqual(x.shape, (2, 3, 5, 7)) @pytest.mark.skipif( keras.backend.backend() != "jax", reason="This test requires `jax` as the backend.", ) def test_jax_rngkey_seed(self): import jax import jax.numpy as jnp seed = 1234 rng = jax.random.PRNGKey(seed) self.assertEqual(rng.shape, (2,)) self.assertEqual(rng.dtype, jnp.uint32) x = random.randint((3, 5), 0, 10, seed=rng) self.assertIsInstance(x, jnp.ndarray) @pytest.mark.skipif( keras.backend.backend() != "jax", reason="This test requires `jax` as the backend.", ) def test_jax_unseed_disallowed_during_tracing(self): import jax @jax.jit def jit_fn(): return random.randint((2, 2), 0, 10, seed=None) with self.assertRaisesRegex( ValueError, "you should only use seeded random ops" ): jit_fn() def test_global_seed_generator(self): # Check that unseeded RNG calls use and update global_rng_state() def random_numbers(seed): rng_state = seed_generator.global_seed_generator().state rng_state.assign(seed) x = random.normal((), seed=None) y = random.normal((), seed=None) return x, y, rng_state.value if backend.backend() == "tensorflow": import tensorflow as tf random_numbers = tf.function(jit_compile=True)(random_numbers) seed = ops.zeros((2,)) seed0 = ops.convert_to_numpy(seed) x1, y1, seed = random_numbers(seed) x1 = ops.convert_to_numpy(x1) y1 = ops.convert_to_numpy(y1) seed1 = ops.convert_to_numpy(seed) x2, y2, seed = random_numbers(seed) x2 = ops.convert_to_numpy(x2) y2 = ops.convert_to_numpy(y2) seed2 = ops.convert_to_numpy(seed) x3, y3, seed = random_numbers(seed) x3 = ops.convert_to_numpy(x3) y3 = ops.convert_to_numpy(y3) seed3 = ops.convert_to_numpy(seed) self.assertNotEqual(seed0[1], seed1[1]) self.assertNotEqual(seed1[1], seed2[1]) self.assertNotEqual(seed2[1], seed3[1]) self.assertGreater(np.abs(x1 - y1), 1e-4) self.assertGreater(np.abs(x1 - y1), 1e-4) self.assertGreater(np.abs(x2 - y2), 1e-4) self.assertGreater(np.abs(x3 - y3), 1e-4) self.assertGreater(np.abs(x1 - x2), 1e-4) self.assertGreater(np.abs(x1 - x3), 1e-4) self.assertGreater(np.abs(x2 - x3), 1e-4) self.assertGreater(np.abs(y1 - y2), 1e-4) self.assertGreater(np.abs(y1 - y3), 1e-4) self.assertGreater(np.abs(y2 - y3), 1e-4) seed_generator.global_seed_generator().state.assign(seed) def test_shuffle(self): x = np.arange(100).reshape(10, 10) # Test axis=0 y = random.shuffle(x, seed=0) self.assertFalse(np.all(x == ops.convert_to_numpy(y))) self.assertAllClose(np.sum(x, axis=0), ops.sum(y, axis=0)) self.assertNotAllClose(np.sum(x, axis=1), ops.sum(y, axis=1)) # Test axis=1 y = random.shuffle(x, axis=1, seed=0) self.assertFalse(np.all(x == ops.convert_to_numpy(y))) self.assertAllClose(np.sum(x, axis=1), ops.sum(y, axis=1)) self.assertNotAllClose(np.sum(x, axis=0), ops.sum(y, axis=0)) def test_randint_dtype_validation(self): with self.assertRaisesRegex( ValueError, "`keras.random.randint` requires an integer `dtype`." ): random.randint((3, 4), minval=0, maxval=10, dtype="float64") def test_uniform_dtype_validation(self): with self.assertRaisesRegex( ValueError, "`keras.random.uniform` requires a floating point `dtype`.", ): random.uniform((3, 4), minval=0, maxval=10, dtype="int64") @parameterized.parameters( {"seed": 10, "shape": (5, 2), "alpha": 2.0, "dtype": "float16"}, {"seed": 10, "shape": (2,), "alpha": 1.5, "dtype": "float32"}, {"seed": 10, "shape": (2, 3), "alpha": 0.5, "dtype": "float32"}, ) def test_gamma(self, seed, shape, alpha, dtype): values = random.gamma(shape, alpha=alpha, seed=seed, dtype=dtype) self.assertEqual(ops.shape(values), shape) self.assertEqual(backend.standardize_dtype(values.dtype), dtype) self.assertGreater(np.min(ops.convert_to_numpy(values)), 0.0) @parameterized.parameters( { "seed": 10, "shape": (5, 2), "counts": 5e4, "probabilities": 0.5, "dtype": "float16", }, { "seed": 10, "shape": (2,), "counts": 1e5, "probabilities": 0.5, "dtype": "float32", }, { "seed": 10, "shape": (2, 3), "counts": [[1e5, 2e5, 3e5], [4e5, 5e5, 6e5]], "probabilities": [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], "dtype": "float32", }, ) def test_binomial(self, seed, shape, counts, probabilities, dtype): set_random_seed(1337) values = random.binomial( shape=shape, counts=counts, probabilities=probabilities, seed=seed, dtype=dtype, ) self.assertEqual(ops.shape(values), shape) self.assertEqual(backend.standardize_dtype(values.dtype), dtype) # The following test that ensures that the number of time # each event occurs doesn't exceed the total input count specified # by the user for that event. # Hence, we do an element wise comparison between `counts` array # and the (generated) `values` array. values_np = ops.convert_to_numpy(values) assert np.greater_equal(np.array(counts), values_np).all() # Following test computes the probabilities of each event # by dividing number of times an event occurs (which is the generated # value) by the corresponding value in the (total) counts array. # and then makes sure that the computed probabilities approximate # the input probabilities generated_probabilities = values_np / np.array(counts) probabilities = np.ones(shape) * np.array(probabilities) self.assertAllClose( probabilities, generated_probabilities, rtol=0.005, atol=0.005 ) @parameterized.parameters( { "seed": 10, "shape": (10000,), "alpha": 3.0, "beta": 2.0, "dtype": "float16", }, { "seed": 10, "shape": (10000, 3), "alpha": [[7.0, 0.5, 1.5]], "beta": [[15.0, 0.9, 4.5]], "dtype": "float32", }, { "seed": 10, "shape": (10000, 30), "alpha": 1.0, "beta": 1.0, "dtype": "float32", }, ) def test_beta(self, seed, shape, alpha, beta, dtype): set_random_seed(1337) values = random.beta( shape=shape, alpha=alpha, beta=beta, seed=seed, dtype=dtype ) self.assertEqual(ops.shape(values), shape) self.assertEqual(backend.standardize_dtype(values.dtype), dtype) values_np = ops.convert_to_numpy(values) self.assertGreaterEqual(np.min(values_np), b=0.0) self.assertLessEqual(np.max(values_np), b=1.0) _alpha_is_an_array = False if isinstance(alpha, list): alpha = np.array(alpha) beta = np.array(beta) _alpha_is_an_array = True # Mean check: # For a beta distributed random variable, # mean = alpha / (alpha + beta) expected_mean = alpha / (alpha + beta) if _alpha_is_an_array: actual_mean = np.mean(values_np, axis=0) self.assertAllClose( expected_mean.flatten(), actual_mean, atol=0.005, rtol=0.005 ) else: actual_mean = np.mean(values_np.flatten()) self.assertAlmostEqual(expected_mean, actual_mean, decimal=2) # Variance check: # For a beta distributed random variable, # variance = (alpha * beta) / ((alpha + beta)^2)(alpha + beta + 1) expected_variance = (alpha * beta) / ( np.square(alpha + beta) * (alpha + beta + 1) ) if _alpha_is_an_array: actual_variance = np.var(values_np, axis=0) self.assertAllClose( expected_variance.flatten(), actual_variance, atol=0.005, rtol=0.005, ) else: actual_variance = np.var(values_np.flatten()) self.assertAlmostEqual( expected_variance, actual_variance, decimal=2 )
keras/keras/random/random_test.py/0
{ "file_path": "keras/keras/random/random_test.py", "repo_id": "keras", "token_count": 7358 }
158
import json import shutil import tempfile import unittest import numpy as np import tree from keras import backend from keras import ops from keras import utils from keras.backend.common import is_float_dtype from keras.backend.common import standardize_dtype from keras.backend.common.global_state import clear_session from keras.backend.common.keras_tensor import KerasTensor from keras.models import Model from keras.utils import traceback_utils from keras.utils.shape_utils import map_shape_structure class TestCase(unittest.TestCase): maxDiff = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def setUp(self): # clear global state so that test cases are independent # required for the jit enabled torch tests since dynamo has # a global cache for guards, compiled fn, etc clear_session() if traceback_utils.is_traceback_filtering_enabled(): traceback_utils.disable_traceback_filtering() def get_temp_dir(self): temp_dir = tempfile.mkdtemp() self.addCleanup(lambda: shutil.rmtree(temp_dir)) return temp_dir def assertAllClose(self, x1, x2, atol=1e-6, rtol=1e-6, msg=None): if not isinstance(x1, np.ndarray): x1 = backend.convert_to_numpy(x1) if not isinstance(x2, np.ndarray): x2 = backend.convert_to_numpy(x2) np.testing.assert_allclose(x1, x2, atol=atol, rtol=rtol) def assertNotAllClose(self, x1, x2, atol=1e-6, rtol=1e-6, msg=None): try: self.assertAllClose(x1, x2, atol=atol, rtol=rtol, msg=msg) except AssertionError: return msg = msg or "" raise AssertionError( f"The two values are close at all elements. \n" f"{msg}.\n" f"Values: {x1}" ) def assertAlmostEqual(self, x1, x2, decimal=3, msg=None): if not isinstance(x1, np.ndarray): x1 = backend.convert_to_numpy(x1) if not isinstance(x2, np.ndarray): x2 = backend.convert_to_numpy(x2) np.testing.assert_almost_equal(x1, x2, decimal=decimal) def assertAllEqual(self, x1, x2, msg=None): self.assertEqual(len(x1), len(x2), msg=msg) for e1, e2 in zip(x1, x2): if isinstance(e1, (list, tuple)) or isinstance(e2, (list, tuple)): self.assertAllEqual(e1, e2, msg=msg) else: e1 = backend.convert_to_numpy(e1) e2 = backend.convert_to_numpy(e2) self.assertEqual(e1, e2, msg=msg) def assertLen(self, iterable, expected_len, msg=None): self.assertEqual(len(iterable), expected_len, msg=msg) def run_class_serialization_test(self, instance, custom_objects=None): from keras.saving import custom_object_scope from keras.saving import deserialize_keras_object from keras.saving import serialize_keras_object # get_config roundtrip cls = instance.__class__ config = instance.get_config() config_json = json.dumps(config, sort_keys=True, indent=4) ref_dir = dir(instance)[:] with custom_object_scope(custom_objects): revived_instance = cls.from_config(config) revived_config = revived_instance.get_config() revived_config_json = json.dumps( revived_config, sort_keys=True, indent=4 ) self.assertEqual(config_json, revived_config_json) self.assertEqual(set(ref_dir), set(dir(revived_instance))) # serialization roundtrip serialized = serialize_keras_object(instance) serialized_json = json.dumps(serialized, sort_keys=True, indent=4) with custom_object_scope(custom_objects): revived_instance = deserialize_keras_object( json.loads(serialized_json) ) revived_config = revived_instance.get_config() revived_config_json = json.dumps( revived_config, sort_keys=True, indent=4 ) self.assertEqual(config_json, revived_config_json) new_dir = dir(revived_instance)[:] for lst in [ref_dir, new_dir]: if "__annotations__" in lst: lst.remove("__annotations__") self.assertEqual(set(ref_dir), set(new_dir)) return revived_instance def run_layer_test( self, layer_cls, init_kwargs, input_shape=None, input_dtype="float32", input_sparse=False, input_data=None, call_kwargs=None, expected_output_shape=None, expected_output_dtype=None, expected_output_sparse=False, expected_output=None, expected_num_trainable_weights=None, expected_num_non_trainable_weights=None, expected_num_non_trainable_variables=None, expected_num_seed_generators=None, expected_num_losses=None, supports_masking=None, expected_mask_shape=None, custom_objects=None, run_training_check=True, run_mixed_precision_check=True, ): """Run basic checks on a layer. Args: layer_cls: The class of the layer to test. init_kwargs: Dict of arguments to be used to instantiate the layer. input_shape: Shape tuple (or list/dict of shape tuples) to call the layer on. input_dtype: Corresponding input dtype. input_sparse: Whether the input is a sparse tensor (this requires the backend to support sparse tensors). input_data: Tensor (or list/dict of tensors) to call the layer on. call_kwargs: Dict of arguments to use when calling the layer (does not include the first input tensor argument) expected_output_shape: Shape tuple (or list/dict of shape tuples) expected as output. expected_output_dtype: dtype expected as output. expected_output_sparse: Whether the output is expected to be sparse (this requires the backend to support sparse tensors). expected_output: Expected output tensor -- only to be specified if input_data is provided. expected_num_trainable_weights: Expected number of trainable weights of the layer once built. expected_num_non_trainable_weights: Expected number of non-trainable weights of the layer once built. expected_num_seed_generators: Expected number of SeedGenerators objects of the layer once built. expected_num_losses: Expected number of loss tensors produced when calling the layer. supports_masking: If True, will check that the layer supports masking. expected_mask_shape: Expected mask shape tuple returned by compute_mask() (only supports 1 shape). custom_objects: Dict of any custom objects to be considered during deserialization. run_training_check: Whether to attempt to train the layer (if an input shape or input data was provided). run_mixed_precision_check: Whether to test the layer with a mixed precision dtype policy. """ if input_shape is not None and input_data is not None: raise ValueError( "input_shape and input_data cannot be passed " "at the same time." ) if expected_output_shape is not None and expected_output is not None: raise ValueError( "expected_output_shape and expected_output cannot be passed " "at the same time." ) if expected_output is not None and input_data is None: raise ValueError( "In order to use expected_output, input_data must be provided." ) if expected_mask_shape is not None and supports_masking is not True: raise ValueError( """In order to use expected_mask_shape, supports_masking must be True.""" ) init_kwargs = init_kwargs or {} call_kwargs = call_kwargs or {} # Serialization test. layer = layer_cls(**init_kwargs) self.run_class_serialization_test(layer, custom_objects) # Basic masking test. if supports_masking is not None: self.assertEqual( layer.supports_masking, supports_masking, msg="Unexpected supports_masking value", ) def run_build_asserts(layer): self.assertTrue(layer.built) if expected_num_trainable_weights is not None: self.assertLen( layer.trainable_weights, expected_num_trainable_weights, msg="Unexpected number of trainable_weights", ) if expected_num_non_trainable_weights is not None: self.assertLen( layer.non_trainable_weights, expected_num_non_trainable_weights, msg="Unexpected number of non_trainable_weights", ) if expected_num_non_trainable_variables is not None: self.assertLen( layer.non_trainable_variables, expected_num_non_trainable_variables, msg="Unexpected number of non_trainable_variables", ) if expected_num_seed_generators is not None: self.assertLen( layer._seed_generators, expected_num_seed_generators, msg="Unexpected number of _seed_generators", ) def run_output_asserts(layer, output, eager=False): if expected_output_shape is not None: if isinstance(expected_output_shape, tuple): self.assertEqual( expected_output_shape, output.shape, msg="Unexpected output shape", ) elif isinstance(expected_output_shape, dict): self.assertIsInstance(output, dict) self.assertEqual( set(output.keys()), set(expected_output_shape.keys()), msg="Unexpected output dict keys", ) output_shape = { k: v.shape for k, v in expected_output_shape.items() } self.assertEqual( expected_output_shape, output_shape, msg="Unexpected output shape", ) elif isinstance(expected_output_shape, list): self.assertIsInstance(output, list) self.assertEqual( len(output), len(expected_output_shape), msg="Unexpected number of outputs", ) output_shape = [v.shape for v in expected_output_shape] self.assertEqual( expected_output_shape, output_shape, msg="Unexpected output shape", ) if expected_output_dtype is not None: output_dtype = tree.flatten(output)[0].dtype self.assertEqual( expected_output_dtype, backend.standardize_dtype(output_dtype), msg="Unexpected output dtype", ) if expected_output_sparse: for x in tree.flatten(output): if isinstance(x, KerasTensor): self.assertTrue(x.sparse) elif backend.backend() == "tensorflow": import tensorflow as tf self.assertIsInstance(x, tf.SparseTensor) elif backend.backend() == "jax": import jax.experimental.sparse as jax_sparse self.assertIsInstance(x, jax_sparse.JAXSparse) else: self.fail( "Sparse is unsupported with " f"backend {backend.backend()}" ) if eager: if expected_output is not None: self.assertEqual(type(expected_output), type(output)) for ref_v, v in zip( tree.flatten(expected_output), tree.flatten(output) ): self.assertAllClose( ref_v, v, msg="Unexpected output value" ) if expected_num_losses is not None: self.assertLen(layer.losses, expected_num_losses) def run_training_step(layer, input_data, output_data): class TestModel(Model): def __init__(self, layer): super().__init__() self.layer = layer def call(self, x): return self.layer(x) model = TestModel(layer) data = (input_data, output_data) if backend.backend() == "torch": data = tree.map_structure(backend.convert_to_numpy, data) def data_generator(): while True: yield data # test the "default" path for each backend by setting # jit_compile="auto". # for tensorflow and jax backends auto is jitted # Note that tensorflow cannot be jitted with sparse tensors # for torch backend auto is eager # # NB: for torch, jit_compile=True turns on torchdynamo # which may not always succeed in tracing depending # on the model. Run your program with these env vars # to get debug traces of dynamo: # TORCH_LOGS="+dynamo" # TORCHDYNAMO_VERBOSE=1 # TORCHDYNAMO_REPORT_GUARD_FAILURES=1 jit_compile = "auto" if backend.backend() == "tensorflow" and input_sparse: jit_compile = False model.compile(optimizer="sgd", loss="mse", jit_compile=jit_compile) model.fit(data_generator(), steps_per_epoch=1, verbose=0) # Build test. if input_data is not None or input_shape is not None: if input_shape is None: build_shape = tree.map_structure( lambda x: ops.shape(x), input_data ) else: build_shape = input_shape layer = layer_cls(**init_kwargs) if isinstance(build_shape, dict): layer.build(**build_shape) else: layer.build(build_shape) run_build_asserts(layer) # Symbolic call test. if input_shape is None: keras_tensor_inputs = tree.map_structure( lambda x: create_keras_tensors( ops.shape(x), x.dtype, input_sparse ), input_data, ) else: keras_tensor_inputs = create_keras_tensors( input_shape, input_dtype, input_sparse ) layer = layer_cls(**init_kwargs) if isinstance(keras_tensor_inputs, dict): keras_tensor_outputs = layer( **keras_tensor_inputs, **call_kwargs ) else: keras_tensor_outputs = layer(keras_tensor_inputs, **call_kwargs) run_build_asserts(layer) run_output_asserts(layer, keras_tensor_outputs, eager=False) if expected_mask_shape is not None: output_mask = layer.compute_mask(keras_tensor_inputs) self.assertEqual(expected_mask_shape, output_mask.shape) # Eager call test and compiled training test. if input_data is not None or input_shape is not None: if input_data is None: input_data = create_eager_tensors( input_shape, input_dtype, input_sparse ) layer = layer_cls(**init_kwargs) if isinstance(input_data, dict): output_data = layer(**input_data, **call_kwargs) else: output_data = layer(input_data, **call_kwargs) run_output_asserts(layer, output_data, eager=True) if run_training_check: run_training_step(layer, input_data, output_data) # Never test mixed precision on torch CPU. Torch lacks support. if run_mixed_precision_check and backend.backend() == "torch": import torch run_mixed_precision_check = torch.cuda.is_available() if run_mixed_precision_check: layer = layer_cls(**{**init_kwargs, "dtype": "mixed_float16"}) if isinstance(input_data, dict): output_data = layer(**input_data, **call_kwargs) else: output_data = layer(input_data, **call_kwargs) for tensor in tree.flatten(output_data): dtype = standardize_dtype(tensor.dtype) if is_float_dtype(dtype): self.assertEqual(dtype, "float16") for weight in layer.weights: dtype = standardize_dtype(weight.dtype) if is_float_dtype(dtype): self.assertEqual(dtype, "float32") def create_keras_tensors(input_shape, dtype, sparse): if isinstance(input_shape, dict): return { utils.removesuffix(k, "_shape"): KerasTensor( v, dtype=dtype, sparse=sparse ) for k, v in input_shape.items() } return map_shape_structure( lambda shape: KerasTensor(shape, dtype=dtype, sparse=sparse), input_shape, ) def create_eager_tensors(input_shape, dtype, sparse): from keras.backend import random if dtype not in [ "float16", "float32", "float64", "int16", "int32", "int64", ]: raise ValueError( "dtype must be a standard float or int dtype. " f"Received: dtype={dtype}" ) if sparse: if backend.backend() == "tensorflow": import tensorflow as tf def create_fn(shape): rng = np.random.default_rng(0) x = (4 * rng.standard_normal(shape)).astype(dtype) x = np.multiply(x, rng.random(shape) < 0.7) return tf.sparse.from_dense(x) elif backend.backend() == "jax": import jax.experimental.sparse as jax_sparse def create_fn(shape): rng = np.random.default_rng(0) x = (4 * rng.standard_normal(shape)).astype(dtype) x = np.multiply(x, rng.random(shape) < 0.7) return jax_sparse.BCOO.fromdense(x, n_batch=1) else: raise ValueError( f"Sparse is unsupported with backend {backend.backend()}" ) else: def create_fn(shape): return ops.cast( random.uniform(shape, dtype="float32") * 3, dtype=dtype ) if isinstance(input_shape, dict): return { utils.removesuffix(k, "_shape"): create_fn(v) for k, v in input_shape.items() } return map_shape_structure(create_fn, input_shape)
keras/keras/testing/test_case.py/0
{ "file_path": "keras/keras/testing/test_case.py", "repo_id": "keras", "token_count": 10297 }
159
from unittest import mock import jax import numpy as np import tensorflow as tf import torch from absl.testing import parameterized from keras import testing from keras.testing.test_utils import named_product from keras.trainers.data_adapters import tf_dataset_adapter class TestTFDatasetAdapter(testing.TestCase, parameterized.TestCase): @parameterized.named_parameters( named_product(iterator_type=["np", "tf", "jax", "torch"]) ) def test_basic_flow(self, iterator_type): x = tf.random.normal((34, 4)) y = tf.random.normal((34, 2)) base_ds = tf.data.Dataset.from_tensor_slices((x, y)).batch(16) adapter = tf_dataset_adapter.TFDatasetAdapter(base_ds) self.assertEqual(adapter.num_batches, 3) self.assertEqual(adapter.batch_size, None) self.assertEqual(adapter.has_partial_batch, None) self.assertEqual(adapter.partial_batch_size, None) if iterator_type == "np": it = adapter.get_numpy_iterator() expected_class = np.ndarray elif iterator_type == "tf": it = adapter.get_tf_dataset() expected_class = tf.Tensor elif iterator_type == "jax": it = adapter.get_jax_iterator() expected_class = jax.Array elif iterator_type == "torch": it = adapter.get_torch_dataloader() expected_class = torch.Tensor for i, batch in enumerate(it): self.assertEqual(len(batch), 2) bx, by = batch self.assertIsInstance(bx, expected_class) self.assertIsInstance(by, expected_class) self.assertEqual(bx.dtype, by.dtype) self.assertContainsExactSubsequence(str(bx.dtype), "float32") if i < 2: self.assertEqual(bx.shape, (16, 4)) self.assertEqual(by.shape, (16, 2)) else: self.assertEqual(bx.shape, (2, 4)) self.assertEqual(by.shape, (2, 2)) def _test_class_weights(self, target_encoding="int"): x = np.random.random((4, 2)) if target_encoding == "int": y = np.array([[0], [1], [2], [3]], dtype="int64") else: y = np.array( [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype="float32", ) class_weight = { 0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4, } base_ds = tf.data.Dataset.from_tensor_slices((x, y)).batch(16) adapter = tf_dataset_adapter.TFDatasetAdapter( base_ds, class_weight=class_weight ) gen = adapter.get_numpy_iterator() for batch in gen: self.assertEqual(len(batch), 3) _, _, bw = batch self.assertAllClose(bw, [0.1, 0.2, 0.3, 0.4]) def test_class_weights_int_targets(self): self._test_class_weights(target_encoding="int") def test_class_weights_categorical_targets(self): self._test_class_weights(target_encoding="categorical") def test_num_batches(self): dataset = tf.data.Dataset.range(42) cardinality = int(dataset.cardinality()) self.assertEqual(cardinality, 42) adapter = tf_dataset_adapter.TFDatasetAdapter(dataset) self.assertEqual(adapter.num_batches, 42) # Test for Infiniate Cardinality dataset = tf.data.Dataset.range(42) dataset = dataset.repeat() cardinality = int(dataset.cardinality()) self.assertEqual(cardinality, tf.data.INFINITE_CARDINALITY) adapter = tf_dataset_adapter.TFDatasetAdapter(dataset) self.assertIsNone(adapter.num_batches) # Test for Unknown Cardinality dataset = dataset.filter(lambda x: True) cardinality = int(dataset.cardinality()) self.assertEqual(cardinality, tf.data.UNKNOWN_CARDINALITY) adapter = tf_dataset_adapter.TFDatasetAdapter(dataset) self.assertIsNone(adapter.num_batches) def test_invalid_dataset_type(self): with self.assertRaisesRegex( ValueError, "Expected argument `dataset` to be a tf.data.Dataset" ): invalid_data = "This is not a tf.data.Dataset" tf_dataset_adapter.TFDatasetAdapter(invalid_data) def test_class_weight_and_sample_weight_together(self): x = np.random.random((4, 2)) y = np.array([[0], [1], [2], [3]], dtype="int64") sw = np.array([0.5, 0.5, 0.5, 0.5]) base_ds = tf.data.Dataset.from_tensor_slices((x, y, sw)).batch(16) class_weight = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4} with self.assertRaisesRegex( ValueError, "You cannot `class_weight` and `sample_weight` at the same time.", ): tf_dataset_adapter.TFDatasetAdapter( base_ds, class_weight=class_weight ) def test_different_y_shapes_with_class_weight(self): x = np.random.random((4, 2)) y = np.array( [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype="float32", ) base_ds = tf.data.Dataset.from_tensor_slices((x, y)).batch(16) class_weight = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4} adapter = tf_dataset_adapter.TFDatasetAdapter( base_ds, class_weight=class_weight ) gen = adapter.get_numpy_iterator() for batch in gen: _, _, bw = batch self.assertAllClose(bw, [0.1, 0.2, 0.3, 0.4]) y_sparse = np.array([0, 1, 2, 3], dtype="int64") base_ds = tf.data.Dataset.from_tensor_slices((x, y_sparse)).batch(16) adapter = tf_dataset_adapter.TFDatasetAdapter( base_ds, class_weight=class_weight ) gen = adapter.get_numpy_iterator() for batch in gen: _, _, bw = batch self.assertAllClose(bw, [0.1, 0.2, 0.3, 0.4]) def test_nested_y_with_class_weight(self): x = np.random.random((4, 2)) # Define two target outputs, y1 and y2, for the dataset y1 = np.array([0, 1, 2, 3], dtype="int64") y2 = np.array([0, 1, 2, 3], dtype="int64") # Create a tf.data Dataset from the input data and two target outputs base_ds = tf.data.Dataset.from_tensor_slices((x, (y1, y2))).batch(16) # Define class weights for potential classes in the output class_weight = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4} with self.assertRaisesRegex( ValueError, "`class_weight` is only supported for Models with a single output.", ): tf_dataset_adapter.TFDatasetAdapter( base_ds, class_weight=class_weight ) def test_class_weights_map_fn_with_sample_weight(self): class_weight = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4} class_weights_map_fn = tf_dataset_adapter.make_class_weight_map_fn( class_weight ) x = np.array([[0.5, 0.5], [0.5, 0.5]]) y = np.array([[1, 0], [0, 1]]) sw = np.array([1.0, 1.0]) with self.assertRaisesRegex( ValueError, "You cannot `class_weight` and `sample_weight` at the same time.", ): class_weights_map_fn(x, y, sw) def test_class_weights_map_fn_nested_y(self): class_weight = {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4} class_weights_map_fn = tf_dataset_adapter.make_class_weight_map_fn( class_weight ) x = np.array([[0.5, 0.5]]) y1 = np.array([1]) y2 = np.array([0]) with self.assertRaisesRegex( ValueError, "`class_weight` is only supported for Models with a single output.", ): class_weights_map_fn(x, (y1, y2)) def test_distribute_dataset(self): x = tf.random.normal((34, 4)) y = tf.random.normal((34, 2)) base_ds = tf.data.Dataset.from_tensor_slices((x, y)).batch(16) data_distribution = mock.Mock() # Mimic that there are 2 worker, and each of the worker will get batch # size of 8 data_distribution.distribute_dataset = mock.MagicMock( return_value=base_ds.rebatch(8).shard(2, index=0) ) adapter = tf_dataset_adapter.TFDatasetAdapter( base_ds, distribution=data_distribution ) self.assertEqual(adapter.num_batches, None) self.assertEqual(adapter.batch_size, None) self.assertEqual(adapter.has_partial_batch, None) self.assertEqual(adapter.partial_batch_size, None) gen = adapter.get_numpy_iterator() for i, batch in enumerate(gen): self.assertEqual(len(batch), 2) bx, by = batch self.assertIsInstance(bx, np.ndarray) self.assertIsInstance(by, np.ndarray) self.assertEqual(bx.dtype, by.dtype) self.assertEqual(bx.dtype, "float32") if i < 2: self.assertEqual(bx.shape, (8, 4)) self.assertEqual(by.shape, (8, 2)) else: self.assertEqual(bx.shape, (2, 4)) self.assertEqual(by.shape, (2, 2)) ds = adapter.get_tf_dataset() for i, batch in enumerate(ds): self.assertEqual(len(batch), 2) bx, by = batch self.assertIsInstance(bx, tf.Tensor) self.assertIsInstance(by, tf.Tensor) self.assertEqual(bx.dtype, by.dtype) self.assertEqual(bx.dtype, "float32") if i < 2: self.assertEqual(tuple(bx.shape), (8, 4)) self.assertEqual(tuple(by.shape), (8, 2)) else: self.assertEqual(tuple(bx.shape), (2, 4)) self.assertEqual(tuple(by.shape), (2, 2)) @parameterized.named_parameters( named_product(iterator_type=["np", "tf", "jax"]) ) def test_tf_sparse_tensors(self, iterator_type): x = tf.SparseTensor( indices=[[0, 0], [1, 2]], values=[1.0, 2.0], dense_shape=(2, 4) ) y = tf.SparseTensor( indices=[[0, 0], [1, 1]], values=[3.0, 4.0], dense_shape=(2, 2) ) base_ds = tf.data.Dataset.from_tensors((x, y)) adapter = tf_dataset_adapter.TFDatasetAdapter(base_ds) if iterator_type == "np": it = adapter.get_numpy_iterator() expected_class = np.ndarray elif iterator_type == "tf": it = adapter.get_tf_dataset() expected_class = tf.SparseTensor elif iterator_type == "jax": it = adapter.get_jax_iterator() expected_class = jax.experimental.sparse.BCOO for batch in it: self.assertEqual(len(batch), 2) bx, by = batch self.assertIsInstance(bx, expected_class) self.assertIsInstance(by, expected_class) self.assertEqual(bx.shape, (2, 4)) self.assertEqual(by.shape, (2, 2))
keras/keras/trainers/data_adapters/tf_dataset_adapter_test.py/0
{ "file_path": "keras/keras/trainers/data_adapters/tf_dataset_adapter_test.py", "repo_id": "keras", "token_count": 5635 }
160
from keras import backend from keras import ops DTYPE_TO_SIZE = { **{f"float{i}": i for i in (16, 32, 64)}, **{f"int{i}": i for i in (8, 16, 32, 64)}, **{f"uint{i}": i for i in (8, 16, 32, 64)}, "bfloat16": 16, "bool": 1, } def dtype_size(dtype): size = DTYPE_TO_SIZE.get(dtype, None) if size is None: raise ValueError(f"Invalid dtype: {dtype}") return size def is_float(dtype): return "float" in dtype def cast_to_common_dtype(tensors): """Cast a list of tensors to a common dtype. If any tensor is floating-point, they will all be casted to the most-precise floating-point dtype. Otherwise the tensors are not casted. Args: tensors: A list of tensors. Returns: Same list, casted to a common dtype. """ highest_float = None highest_float_size = ( -1 ) # Initially set to an impossible value for comparison for x in tensors: dtype = backend.standardize_dtype(x.dtype) if is_float(dtype): if highest_float is None or dtype_size(dtype) > highest_float_size: highest_float = dtype highest_float_size = dtype_size(dtype) elif dtype == "float16" and highest_float == "bfloat16": highest_float = "float32" highest_float_size = dtype_size(highest_float) if highest_float: tensors = [ops.cast(x, highest_float) for x in tensors] return tensors
keras/keras/utils/dtype_utils.py/0
{ "file_path": "keras/keras/utils/dtype_utils.py", "repo_id": "keras", "token_count": 655 }
161
import numpy as np from absl.testing import parameterized from keras import backend from keras import testing from keras.utils import numerical_utils NUM_CLASSES = 5 class TestNumericalUtils(testing.TestCase, parameterized.TestCase): @parameterized.parameters( [ ((1,), (1, NUM_CLASSES)), ((3,), (3, NUM_CLASSES)), ((4, 3), (4, 3, NUM_CLASSES)), ((5, 4, 3), (5, 4, 3, NUM_CLASSES)), ((3, 1), (3, NUM_CLASSES)), ((3, 2, 1), (3, 2, NUM_CLASSES)), ] ) def test_to_categorical(self, shape, expected_shape): label = np.random.randint(0, NUM_CLASSES, shape) one_hot = numerical_utils.to_categorical(label, NUM_CLASSES) # Check shape self.assertEqual(one_hot.shape, expected_shape) # Make sure there is only one 1 in a row self.assertTrue(np.all(one_hot.sum(axis=-1) == 1)) # Get original labels back from one hots self.assertTrue( np.all(np.argmax(one_hot, -1).reshape(label.shape) == label) ) def test_to_categorial_without_num_classes(self): label = [0, 2, 5] one_hot = numerical_utils.to_categorical(label) self.assertEqual(one_hot.shape, (3, 5 + 1)) def test_to_categorical_with_backend_tensor(self): label = backend.convert_to_tensor(np.array([0, 2, 1, 3, 4])) expected = backend.convert_to_tensor( np.array( [ [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], ] ) ) one_hot = numerical_utils.to_categorical(label, NUM_CLASSES) assert backend.is_tensor(one_hot) self.assertAllClose(one_hot, expected) @parameterized.parameters([1, 2, 3]) def test_normalize(self, order): xb = backend.random.uniform((3, 3), seed=1337) xnp = backend.convert_to_numpy(xb) # Expected result l2 = np.atleast_1d(np.linalg.norm(xnp, order, axis=-1)) l2[l2 == 0] = 1 expected = xnp / np.expand_dims(l2, axis=-1) # Test NumPy out = numerical_utils.normalize(xnp, axis=-1, order=order) self.assertIsInstance(out, np.ndarray) self.assertAllClose(out, expected) # Test backend out = numerical_utils.normalize(xb, axis=-1, order=order) self.assertTrue(backend.is_tensor(out)) self.assertAllClose(backend.convert_to_numpy(out), expected)
keras/keras/utils/numerical_utils_test.py/0
{ "file_path": "keras/keras/utils/numerical_utils_test.py", "repo_id": "keras", "token_count": 1307 }
162
import io from packaging.version import parse from keras.api_export import keras_export from keras.layers import Layer from keras.ops import convert_to_numpy from keras.ops import convert_to_tensor @keras_export("keras.layers.TorchModuleWrapper") class TorchModuleWrapper(Layer): """Torch module wrapper layer. `TorchModuleWrapper` is a wrapper class that can turn any `torch.nn.Module` into a Keras layer, in particular by making its parameters trackable by Keras. Args: module: `torch.nn.Module` instance. If it's a `LazyModule` instance, then its parameters must be initialized before passing the instance to `TorchModuleWrapper` (e.g. by calling it once). name: The name of the layer (string). Examples: Here's an example of how the `TorchModuleWrapper` can be used with vanilla PyTorch modules. ```python import torch.nn as nn import torch.nn.functional as F import keras from keras.layers import TorchModuleWrapper class Classifier(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) # Wrap `torch.nn.Module`s with `TorchModuleWrapper` # if they contain parameters self.conv1 = TorchModuleWrapper( nn.Conv2d(in_channels=1, out_channels=32, kernel_size=(3, 3)) ) self.conv2 = TorchModuleWrapper( nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)) ) self.pool = nn.MaxPool2d(kernel_size=(2, 2)) self.flatten = nn.Flatten() self.dropout = nn.Dropout(p=0.5) self.fc = TorchModuleWrapper(nn.Linear(1600, 10)) def call(self, inputs): x = F.relu(self.conv1(inputs)) x = self.pool(x) x = F.relu(self.conv2(x)) x = self.pool(x) x = self.flatten(x) x = self.dropout(x) x = self.fc(x) return F.softmax(x, dim=1) model = Classifier() model.build((1, 28, 28)) print("Output shape:", model(torch.ones(1, 1, 28, 28).to("cuda")).shape) model.compile( loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"] ) model.fit(train_loader, epochs=5) ``` """ def __init__(self, module, name=None, **kwargs): super().__init__(name=name, **kwargs) import torch.nn as nn from keras.backend.torch.core import get_device if ( isinstance(module, nn.modules.lazy.LazyModuleMixin) and module.has_uninitialized_params() ): raise ValueError( "LazyModules are not supported unless they " "are already initialized. " f"Received uninitialized LazyModule: module={module}" ) self.module = module.to(get_device()) self._track_module_parameters() def parameters(self, recurse=True): return self.module.parameters(recurse=recurse) def _track_module_parameters(self): from keras.backend.torch import Variable for param in self.module.parameters(): # The Variable will reuse the raw `param` # and simply wrap it. variable = Variable( initializer=param, trainable=param.requires_grad ) self._track_variable(variable) self.built = True def call(self, *args, **kwargs): return self.module.forward(*args, **kwargs) def save_own_variables(self, store): """Saves model's state from `state_dict`. `model.parameters` excludes some of model's state like `BatchNorm` mean and variance. So, use `state_dict` to obtain all of model's state. """ state_dict = self.module.state_dict() for key in state_dict.keys(): store[key] = convert_to_numpy(state_dict[key]) def load_own_variables(self, store): """Loads model's state via `state_dict`.""" state_dict = {} for key in store.keys(): if isinstance(key, bytes): key = key.decode() state_dict[key] = convert_to_tensor(store[key]) self.module.load_state_dict(state_dict) def get_config(self): base_config = super().get_config() import torch buffer = io.BytesIO() torch.save(self.module, buffer) config = {"module": buffer.getvalue()} return {**base_config, **config} @classmethod def from_config(cls, config): import torch if "module" in config: buffer = io.BytesIO(config["module"]) config["module"] = torch.load(buffer) return cls(**config) def no_grad(orig_func): import torch if parse(torch.__version__) >= parse("2.1.0"): return torch.no_grad(orig_func) else: return orig_func
keras/keras/utils/torch_utils.py/0
{ "file_path": "keras/keras/utils/torch_utils.py", "repo_id": "keras", "token_count": 2267 }
163
#!/bin/bash set -Eeuo pipefail base_dir=$(dirname $(dirname $0)) isort --sp "${base_dir}/pyproject.toml" --check . black --config "${base_dir}/pyproject.toml" --check . flake8 --config "${base_dir}/setup.cfg" .
keras/shell/lint.sh/0
{ "file_path": "keras/shell/lint.sh", "repo_id": "keras", "token_count": 90 }
164
Please go to Stack Overflow for help and support: https://stackoverflow.com/questions/tagged/keras If you open a GitHub issue, here is our policy: 1. It must be a bug, a feature request, or a significant problem with the documentation (for small docs fixes please send a PR instead). 2. The form below must be filled out. **Here's why we have that policy**: TF-Keras developers respond to issues. We want to focus on work that benefits the whole community, e.g., fixing bugs and adding features. Support only helps individuals. GitHub also notifies thousands of people when issues are filed. We want them to see you communicating an interesting problem, rather than being redirected to Stack Overflow. ------------------------ ### System information - **Have I written custom code (as opposed to using a stock example script provided in Keras)**: - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: - **TensorFlow installed from (source or binary)**: - **TensorFlow version (use command below)**: - **Python version**: - **Bazel version (if compiling from source)**: - **GPU model and memory**: - **Exact command to reproduce**: You can collect some of this information using our environment capture script: https://github.com/tensorflow/tensorflow/tree/master/tools/tf_env_collect.sh You can obtain the TensorFlow version with: ```bash python -c "import tensorflow as tf; print(tf.version.GIT_VERSION, tf.version.VERSION)" ``` ### Describe the problem Describe the problem clearly here. Be sure to convey here why it's a bug in TF-Keras or why the requested feature is needed. ### Source code / logs Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem.
tf-keras/ISSUE_TEMPLATE.md/0
{ "file_path": "tf-keras/ISSUE_TEMPLATE.md", "repo_id": "tf-keras", "token_count": 511 }
165
"""Rules to generate the TensorFlow public API from annotated files.""" # Placeholder: load unaliased PyInfo # Placeholder: load if_indexing_source_code _TARGET_PATTERNS = [ "//tf_keras:", "//tf_keras/", ] _DECORATOR = "tensorflow.python.util.tf_export.keras_export" def _any_match(label): full_target = "//" + label.package + ":" + label.name for pattern in _TARGET_PATTERNS: if pattern in full_target: return True return False def _join(path, *others): result = path for p in others: if not result or result.endswith("/"): result += p else: result += "/" + p return result ApiInfo = provider( doc = "Provider for API symbols and docstrings extracted from Python files.", fields = { "transitive_api": "depset of files with extracted API.", }, ) def _py_files(f): if f.basename.endswith(".py") or f.basename.endswith(".py3"): return f.path return None def _merge_py_info( deps, direct_sources = None, direct_imports = None, has_py2_only_sources = False, has_py3_only_sources = False, uses_shared_libraries = False): transitive_sources = [] transitive_imports = [] for dep in deps: if PyInfo in dep: transitive_sources.append(dep[PyInfo].transitive_sources) transitive_imports.append(dep[PyInfo].imports) has_py2_only_sources = has_py2_only_sources or dep[PyInfo].has_py2_only_sources has_py3_only_sources = has_py3_only_sources or dep[PyInfo].has_py3_only_sources uses_shared_libraries = uses_shared_libraries or dep[PyInfo].uses_shared_libraries return PyInfo( transitive_sources = depset(direct = direct_sources, transitive = transitive_sources), imports = depset(direct = direct_imports, transitive = transitive_imports), has_py2_only_sources = has_py2_only_sources, has_py3_only_sources = has_py3_only_sources, uses_shared_libraries = uses_shared_libraries, ) def _merge_api_info( deps, direct_api = None): transitive_api = [] for dep in deps: if ApiInfo in dep: transitive_api.append(dep[ApiInfo].transitive_api) return ApiInfo(transitive_api = depset(direct = direct_api, transitive = transitive_api)) def _api_extractor_impl(target, ctx): direct_api = [] # Make sure the rule has a non-empty srcs attribute. if ( _any_match(target.label) and hasattr(ctx.rule.attr, "srcs") and ctx.rule.attr.srcs ): output = ctx.actions.declare_file("_".join([ target.label.name, "extracted_keras_api.json", ])) args = ctx.actions.args() args.set_param_file_format("multiline") args.use_param_file("--flagfile=%s") args.add("--output", output) args.add("--decorator", _DECORATOR) args.add("--api_name", "keras") args.add_all(ctx.rule.files.srcs, expand_directories = True, map_each = _py_files) ctx.actions.run( mnemonic = "ExtractAPI", executable = ctx.executable._extractor_bin, inputs = ctx.rule.files.srcs, outputs = [output], arguments = [args], progress_message = "Extracting keras APIs for %{label} to %{output}.", use_default_shell_env = True, ) direct_api.append(output) return [ _merge_api_info(ctx.rule.attr.deps if hasattr(ctx.rule.attr, "deps") else [], direct_api = direct_api), ] api_extractor = aspect( doc = "Extracts the exported API for the given target and its dependencies.", implementation = _api_extractor_impl, attr_aspects = ["deps"], provides = [ApiInfo], # Currently the Python rules do not correctly advertise their providers. # required_providers = [PyInfo], attrs = { "_extractor_bin": attr.label( default = Label("//tf_keras/api:extractor_wrapper"), executable = True, cfg = "exec", ), }, ) def _extract_api_impl(ctx): return [ _merge_api_info(ctx.attr.deps), _merge_py_info(ctx.attr.deps), ] extract_api = rule( doc = "Extract Python API for all targets in transitive dependencies.", implementation = _extract_api_impl, attrs = { "deps": attr.label_list( doc = "Targets to extract API from.", allow_empty = False, aspects = [api_extractor], providers = [PyInfo], mandatory = True, ), }, provides = [ApiInfo, PyInfo], ) def _generate_api_impl(ctx): args = ctx.actions.args() args.set_param_file_format("multiline") args.use_param_file("--flagfile=%s", use_always = True) args.add_joined("--output_files", ctx.outputs.output_files, join_with = ",") args.add("--output_dir", _join(ctx.bin_dir.path, ctx.label.package, ctx.attr.output_dir)) if ctx.file.root_init_template: args.add("--root_init_template", ctx.file.root_init_template) args.add("--apiversion", ctx.attr.api_version) args.add_joined("--compat_api_versions", ctx.attr.compat_api_versions, join_with = ",") args.add_joined("--compat_init_templates", ctx.files.compat_init_templates, join_with = ",") args.add("--output_package", ctx.attr.output_package) args.add_joined("--packages_to_ignore", ctx.attr.packages_to_ignore, join_with = ",") if ctx.attr.use_lazy_loading: args.add("--use_lazy_loading") else: args.add("--nouse_lazy_loading") args.add_joined("--file_prefixes_to_strip", [ctx.bin_dir.path, ctx.genfiles_dir.path, "third_party/py"], join_with = ",") inputs = depset(transitive = [ dep[ApiInfo].transitive_api for dep in ctx.attr.deps ]) args.add_all( inputs, expand_directories = True, ) transitive_inputs = [inputs] if ctx.attr.root_init_template: transitive_inputs.append(ctx.attr.root_init_template.files) ctx.actions.run( mnemonic = "GenerateAPI", executable = ctx.executable._generator_bin, inputs = depset( direct = ctx.files.compat_init_templates, transitive = transitive_inputs, ), outputs = ctx.outputs.output_files, arguments = [args], progress_message = "Generating APIs for %{label} to %{output}.", use_default_shell_env = True, ) generate_api = rule( doc = "Generate Python API for all targets in transitive dependencies.", implementation = _generate_api_impl, attrs = { "deps": attr.label_list( doc = "extract_api targets to generate API from.", allow_empty = True, providers = [ApiInfo, PyInfo], mandatory = True, ), "root_init_template": attr.label( doc = "Template for the top level __init__.py file", allow_single_file = True, ), "api_version": attr.int( doc = "The API version to generate (1 or 2)", values = [1, 2], ), "compat_api_versions": attr.int_list( doc = "Additional versions to generate in compat/ subdirectory.", ), "compat_init_templates": attr.label_list( doc = "Template for top-level __init__files under compat modules. This list must be " + "in the same order as the list of versions in compat_apiversions", allow_files = True, ), "output_package": attr.string( doc = "Root output package.", ), "output_dir": attr.string( doc = "Subdirectory to output API to. If non-empty, must end with '/'.", ), "output_files": attr.output_list( doc = "List of __init__.py files that should be generated. This list should include " + "file name for every module exported using tf_export. For e.g. if an op is " + "decorated with @tf_export('module1.module2', 'module3'). Then, output_files " + "should include module1/module2/__init__.py and module3/__init__.py.", ), "use_lazy_loading": attr.bool( doc = "If true, lazy load imports in the generated API rather then imporing them all statically.", ), "packages_to_ignore": attr.string_list( doc = "List of packages to ignore tf_exports from.", ), "_generator_bin": attr.label( default = Label("//tf_keras/api:generator_wrapper"), executable = True, cfg = "exec", ), }, ) def generate_apis( name, deps = [ "//tf_keras", ], output_files = [], root_init_template = None, api_version = 2, compat_api_versions = [], compat_init_templates = [], output_package = "tf_keras.api", output_dir = "", packages_to_ignore = [], visibility = ["//visibility:public"]): """Generate TensorFlow APIs for a set of libraries. Args: name: name of generate_api target. deps: python_library targets to serve as roots for extracting APIs. output_files: The list of files that the API generator is exected to create. root_init_template: The template for the top level __init__.py file generated. "#API IMPORTS PLACEHOLDER" comment will be replaced with imports. api_version: THhe API version to generate. (1 or 2) compat_api_versions: Additional versions to generate in compat/ subdirectory. compat_init_templates: Template for top level __init__.py files under the compat modules. The list must be in the same order as the list of versions in 'compat_api_versions' output_package: Root output package. output_dir: Directory where the generated output files are placed. This should be a prefix of every directory in 'output_files' packages_to_ignore: List of packages to ignore tf_exports from. visibility: Visibility of the target containing the generated files. """ extract_name = name + ".extract-keras" extract_api( name = extract_name, deps = deps, visibility = ["//visibility:private"], ) all_output_files = [_join(output_dir, f) for f in output_files] generate_api( name = name, deps = [":" + extract_name], output_files = all_output_files, output_dir = output_dir, root_init_template = root_init_template, compat_api_versions = compat_api_versions, compat_init_templates = compat_init_templates, api_version = api_version, visibility = visibility, packages_to_ignore = packages_to_ignore, use_lazy_loading = False, output_package = output_package, )
tf-keras/tf_keras/api/api_gen.bzl/0
{ "file_path": "tf-keras/tf_keras/api/api_gen.bzl", "repo_id": "tf-keras", "token_count": 4827 }
166
# Copyright 2019 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 imagenet_utils.""" import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized import tf_keras as keras from tf_keras.applications import imagenet_utils as utils from tf_keras.mixed_precision.policy import set_global_policy from tf_keras.testing_infra import test_combinations class TestImageNetUtils(test_combinations.TestCase): def test_preprocess_input(self): # Test invalid mode check x = np.random.uniform(0, 255, (10, 10, 3)) with self.assertRaises(ValueError): utils.preprocess_input(x, mode="some_unknown_mode") # Test image batch with float and int image input x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype("int32") self.assertEqual(utils.preprocess_input(x).shape, x.shape) self.assertEqual(utils.preprocess_input(xint).shape, xint.shape) out1 = utils.preprocess_input(x, "channels_last") out1int = utils.preprocess_input(xint, "channels_last") out2 = utils.preprocess_input( np.transpose(x, (0, 3, 1, 2)), "channels_first" ) out2int = utils.preprocess_input( np.transpose(xint, (0, 3, 1, 2)), "channels_first" ) self.assertAllClose(out1, out2.transpose(0, 2, 3, 1)) self.assertAllClose(out1int, out2int.transpose(0, 2, 3, 1)) # Test single image x = np.random.uniform(0, 255, (10, 10, 3)) xint = x.astype("int32") self.assertEqual(utils.preprocess_input(x).shape, x.shape) self.assertEqual(utils.preprocess_input(xint).shape, xint.shape) out1 = utils.preprocess_input(x, "channels_last") out1int = utils.preprocess_input(xint, "channels_last") out2 = utils.preprocess_input( np.transpose(x, (2, 0, 1)), "channels_first" ) out2int = utils.preprocess_input( np.transpose(xint, (2, 0, 1)), "channels_first" ) self.assertAllClose(out1, out2.transpose(1, 2, 0)) self.assertAllClose(out1int, out2int.transpose(1, 2, 0)) # Test that writing over the input data works predictably for mode in ["torch", "tf"]: x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype("int") x2 = utils.preprocess_input(x, mode=mode) xint2 = utils.preprocess_input(xint) self.assertAllClose(x, x2) self.assertNotEqual(xint.astype("float").max(), xint2.max()) # Caffe mode works differently from the others x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype("int") x2 = utils.preprocess_input( x, data_format="channels_last", mode="caffe" ) xint2 = utils.preprocess_input(xint) self.assertAllClose(x, x2[..., ::-1]) self.assertNotEqual(xint.astype("float").max(), xint2.max()) @parameterized.named_parameters( [ {"testcase_name": "mode_torch", "mode": "torch"}, {"testcase_name": "mode_tf", "mode": "tf"}, {"testcase_name": "mode_caffe", "mode": "caffe"}, ] ) def test_preprocess_input_symbolic(self, mode): # Test image batch x = np.random.uniform(0, 255, (2, 10, 10, 3)) inputs = keras.layers.Input(shape=x.shape[1:]) outputs = keras.layers.Lambda( lambda x: utils.preprocess_input(x, mode=mode), output_shape=x.shape[1:], )(inputs) model = keras.Model(inputs, outputs) self.assertEqual(model.predict(x).shape, x.shape) outputs1 = keras.layers.Lambda( lambda x: utils.preprocess_input(x, "channels_last", mode=mode), output_shape=x.shape[1:], )(inputs) model1 = keras.Model(inputs, outputs1) out1 = model1.predict(x) x2 = np.transpose(x, (0, 3, 1, 2)) inputs2 = keras.layers.Input(shape=x2.shape[1:]) outputs2 = keras.layers.Lambda( lambda x: utils.preprocess_input(x, "channels_first", mode=mode), output_shape=x2.shape[1:], )(inputs2) model2 = keras.Model(inputs2, outputs2) out2 = model2.predict(x2) self.assertAllClose(out1, out2.transpose(0, 2, 3, 1)) # Test single image x = np.random.uniform(0, 255, (10, 10, 3)) inputs = keras.layers.Input(shape=x.shape) outputs = keras.layers.Lambda( lambda x: utils.preprocess_input(x, mode=mode), output_shape=x.shape )(inputs) model = keras.Model(inputs, outputs) self.assertEqual(model.predict(x[np.newaxis])[0].shape, x.shape) outputs1 = keras.layers.Lambda( lambda x: utils.preprocess_input(x, "channels_last", mode=mode), output_shape=x.shape, )(inputs) model1 = keras.Model(inputs, outputs1) out1 = model1.predict(x[np.newaxis])[0] x2 = np.transpose(x, (2, 0, 1)) inputs2 = keras.layers.Input(shape=x2.shape) outputs2 = keras.layers.Lambda( lambda x: utils.preprocess_input(x, "channels_first", mode=mode), output_shape=x2.shape, )(inputs2) model2 = keras.Model(inputs2, outputs2) out2 = model2.predict(x2[np.newaxis])[0] self.assertAllClose(out1, out2.transpose(1, 2, 0)) @parameterized.named_parameters( [ {"testcase_name": "mode_torch", "mode": "torch"}, {"testcase_name": "mode_tf", "mode": "tf"}, {"testcase_name": "mode_caffe", "mode": "caffe"}, ] ) def test_preprocess_input_symbolic_mixed_precision(self, mode): if not tf.__internal__.tf2.enabled(): self.skipTest( "The global policy can only be tested in TensorFlow 2" ) set_global_policy("mixed_float16") shape = (20, 20, 3) inputs = keras.layers.Input(shape=shape) try: keras.layers.Lambda( lambda x: utils.preprocess_input(x, mode=mode), output_shape=shape, )(inputs) finally: set_global_policy("float32") @parameterized.named_parameters( [ { "testcase_name": "channels_last_format", "data_format": "channels_last", }, { "testcase_name": "channels_first_format", "data_format": "channels_first", }, ] ) def test_obtain_input_shape(self, data_format): # input_shape and default_size are not identical. with self.assertRaises(ValueError): utils.obtain_input_shape( input_shape=(224, 224, 3), default_size=299, min_size=139, data_format="channels_last", require_flatten=True, weights="imagenet", ) # Test invalid use cases shape = (139, 139) if data_format == "channels_last": input_shape = shape + (99,) else: input_shape = (99,) + shape # input_shape is smaller than min_size. shape = (100, 100) if data_format == "channels_last": input_shape = shape + (3,) else: input_shape = (3,) + shape with self.assertRaises(ValueError): utils.obtain_input_shape( input_shape=input_shape, default_size=None, min_size=139, data_format=data_format, require_flatten=False, ) # shape is 1D. shape = (100,) if data_format == "channels_last": input_shape = shape + (3,) else: input_shape = (3,) + shape with self.assertRaises(ValueError): utils.obtain_input_shape( input_shape=input_shape, default_size=None, min_size=139, data_format=data_format, require_flatten=False, ) # the number of channels is 5 not 3. shape = (100, 100) if data_format == "channels_last": input_shape = shape + (5,) else: input_shape = (5,) + shape with self.assertRaises(ValueError): utils.obtain_input_shape( input_shape=input_shape, default_size=None, min_size=139, data_format=data_format, require_flatten=False, ) # require_flatten=True with dynamic input shape. with self.assertRaises(ValueError): utils.obtain_input_shape( input_shape=None, default_size=None, min_size=139, data_format="channels_first", require_flatten=True, ) # test include top self.assertEqual( utils.obtain_input_shape( input_shape=(3, 200, 200), default_size=None, min_size=139, data_format="channels_first", require_flatten=True, ), (3, 200, 200), ) self.assertEqual( utils.obtain_input_shape( input_shape=None, default_size=None, min_size=139, data_format="channels_last", require_flatten=False, ), (None, None, 3), ) self.assertEqual( utils.obtain_input_shape( input_shape=None, default_size=None, min_size=139, data_format="channels_first", require_flatten=False, ), (3, None, None), ) self.assertEqual( utils.obtain_input_shape( input_shape=None, default_size=None, min_size=139, data_format="channels_last", require_flatten=False, ), (None, None, 3), ) self.assertEqual( utils.obtain_input_shape( input_shape=(150, 150, 3), default_size=None, min_size=139, data_format="channels_last", require_flatten=False, ), (150, 150, 3), ) self.assertEqual( utils.obtain_input_shape( input_shape=(3, None, None), default_size=None, min_size=139, data_format="channels_first", require_flatten=False, ), (3, None, None), ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/applications/imagenet_utils_test.py/0
{ "file_path": "tf-keras/tf_keras/applications/imagenet_utils_test.py", "repo_id": "tf-keras", "token_count": 5932 }
167
# Copyright 2019 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 backend_config.""" import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras import backend_config from tf_keras.testing_infra import test_combinations @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class BackendConfigTest(tf.test.TestCase): def test_backend(self): self.assertEqual(backend.backend(), "tensorflow") def test_epsilon(self): epsilon = 1e-2 backend_config.set_epsilon(epsilon) self.assertEqual(backend_config.epsilon(), epsilon) backend_config.set_epsilon(1e-7) self.assertEqual(backend_config.epsilon(), 1e-7) def test_floatx(self): floatx = "float64" backend_config.set_floatx(floatx) self.assertEqual(backend_config.floatx(), floatx) backend_config.set_floatx("float32") self.assertEqual(backend_config.floatx(), "float32") def test_image_data_format(self): image_data_format = "channels_first" backend_config.set_image_data_format(image_data_format) self.assertEqual(backend_config.image_data_format(), image_data_format) backend_config.set_image_data_format("channels_last") self.assertEqual(backend_config.image_data_format(), "channels_last") if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/backend_config_test.py/0
{ "file_path": "tf-keras/tf_keras/backend_config_test.py", "repo_id": "tf-keras", "token_count": 717 }
168
# Copyright 2020 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. # ============================================================================== """Benchmarks using custom training loop on MNIST dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import timeit import numpy as np import tensorflow.compat.v2 as tf import tf_keras as keras from tf_keras.benchmarks import benchmark_util from tf_keras.benchmarks import distribution_util class CustomMnistBenchmark(tf.test.Benchmark): """Benchmarks for custom training loop using `tf.test.Benchmark`.""" def __init__(self): super().__init__() self.num_classes = 10 self.input_shape = (28, 28, 1) self.epochs = 15 (x_train, y_train), _ = keras.datasets.mnist.load_data() x_train = x_train.astype("float32") / 255 x_train = np.expand_dims(x_train, -1) y_train = keras.utils.to_categorical(y_train, self.num_classes) self.num_examples = x_train.shape[0] # Use `tf.data.Dataset` for custom training loop. self.train_dataset = tf.data.Dataset.from_tensor_slices( (x_train, y_train) ) def _build_model(self): """Model from https://keras.io/examples/vision/mnist_convnet/.""" model = keras.Sequential( [ keras.Input(shape=self.input_shape), keras.layers.Conv2D(32, kernel_size=(3, 3), activation="relu"), keras.layers.MaxPooling2D(pool_size=(2, 2)), keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"), keras.layers.MaxPooling2D(pool_size=(2, 2)), keras.layers.Flatten(), keras.layers.Dropout(0.5), keras.layers.Dense(self.num_classes, activation="softmax"), ] ) return model def compute_loss(self, targets, predictions, loss_fn, batch_size): """Compute average loss.""" per_example_loss = loss_fn(targets, predictions) return tf.nn.compute_average_loss( per_example_loss, global_batch_size=batch_size ) @tf.function(reduce_retracing=True) def train_step(self, inputs, model, loss_fn, optimizer, batch_size): """Compute loss and optimize model by optimizer. Args: inputs: `tf.data`. model: See `model` in `train_function()` method. loss_fn: See `loss_fn` in `train_function()` method. optimizer: See `optimizer` in `train_function()` method. batch_size: See `batch_size` in `train_function()` method. Returns: Loss value. """ train_x, train_y = inputs with tf.GradientTape() as tape: predictions = model(train_x, training=True) loss = self.compute_loss(train_y, predictions, loss_fn, batch_size) grads = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(grads, model.trainable_weights)) return loss @tf.function(reduce_retracing=True) def distributed_train_step( self, batch_dataset, model, loss_fn, optimizer, batch_size, distribution_strategy, ): """Train step in distribution strategy setting. Args: batch_dataset: `tf.data`. model: See `model` in `train_function()` method. loss_fn: See `loss_fn` in `train_function()` method. optimizer: See `optimizer` in `train_function()` method. batch_size: See `batch_size` in `train_function()` method. distribution_strategy: See `distribution_strategy` in `train_function()` method. Returns: Sum of per_replica_losses. """ per_replica_losses = distribution_strategy.run( self.train_step, args=( batch_dataset, model, loss_fn, optimizer, batch_size, ), ) return distribution_strategy.reduce( tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None ) def train_function( self, model, train_dataset, loss_fn, optimizer, epochs=2, distribution_strategy=None, batch_size=256, ): """Train model in custom training loop and return average train_step_time. Args: model: Model function to be benchmarked. train_dataset: `tf.data` dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights). loss_fn: `keras.losses.Loss` instance. optimizer: `keras.optimizers` instance. epochs: Integer. Number of epochs to train the model. If unspecified, `epochs` will default to 2. distribution_strategy: Distribution strategies. It could be `multi_worker_mirrored`, `one_device`, `mirrored`. If unspecified, `distribution_strategy` will default to 'off'. Note that, `TPU` and `parameter_server` are not supported yet. batch_size: Integer. Number of samples per gradient update. If unspecified, `batch_size` will default to 32. Returns: Average train_step_time. """ train_step_time_list = [] timer = timeit.default_timer total_loss = 0.0 num_batches = 0 for _ in range(epochs): # Iterate over the batches of the dataset. for batch_dataset in train_dataset: start_time = timer() if distribution_strategy is not None: total_loss += self.distributed_train_step( batch_dataset, model, loss_fn, optimizer, batch_size, distribution_strategy, ) else: total_loss += self.train_step( batch_dataset, model, loss_fn, optimizer, batch_size ) num_batches += 1 end_time = timer() train_step_time_list.append(end_time - start_time) return np.mean(train_step_time_list) def measure_performance( self, model, dataset, loss_fn, optimizer, batch_size=32, run_iters=4, epochs=10, distribution_strategy=None, ): """Run models and measure the performance. Args: model_fn: Model function to be benchmarked. dataset: `tf.data` dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights). loss_fn: `keras.losses.Loss` instance. optimizer: `keras.optimizers` instance. batch_size: Integer. Number of samples per gradient update. If unspecified, `batch_size` will default to 32. run_iters: Integer. Number of iterations to run the performance measurement. If unspecified, `run_iters` will default to 4. epochs: Integer. Number of epochs to train the model. If unspecified, `epochs` will default to 10. distribution_strategy: Distribution strategies. It could be `multi_worker_mirrored`, `one_device`, `mirrored`. If unspecified, `distribution_strategy` will default to 'off'. Note that, `TPU` and `parameter_server` are not supported yet. Returns: Performance summary, which contains build_time, avg_epoch_time, wall_time, exp_per_sec, epochs, warmup_time, train_step_time. Raise: ValueError: if `dataset` is None or if `optimizer` instance is not provided or if `loss_fn` instance is not provided. """ if distribution_strategy is not None and not isinstance( dataset, tf.distribute.DistributedDataset ): raise ValueError( "tf.distribute.DistributedDataset" " required in distribution strategy." ) if distribution_strategy is None and not isinstance( dataset, tf.data.Dataset ): raise ValueError("`tf.data` is required.") if not isinstance(loss_fn, keras.losses.Loss): raise ValueError( "`keras.losses.Loss` instance for loss_fn is required." ) if not isinstance(optimizer, keras.optimizers.Optimizer): raise ValueError( "`keras.optimizers` instance for optimizer is required." ) avg_epoch_time_list, train_step_time_list = [], [] wall_time_list, exp_per_sec_list, warmup_time_list = [], [], [] total_num_examples = epochs * self.num_examples for _ in range(run_iters): timer = timeit.default_timer start_time = timer() t1 = timer() self.train_function( model, dataset, loss_fn, optimizer, 1, distribution_strategy, batch_size, ) warmup_time = timer() - t1 t2 = timer() train_step_time = self.train_function( model, dataset, loss_fn, optimizer, epochs, distribution_strategy, batch_size, ) end_time = timer() train_step_time_list.append(train_step_time) warmup_time_list.append(warmup_time) wall_time_list.append(end_time - start_time) exp_per_sec_list.append(total_num_examples / (end_time - t2)) avg_epoch_time_list.append((end_time - t2) / epochs) metrics = [] metrics.append( {"name": "avg_epoch_time", "value": np.mean(avg_epoch_time_list)} ) metrics.append( {"name": "exp_per_sec", "value": np.mean(exp_per_sec_list)} ) metrics.append( {"name": "warmup_time", "value": np.mean(warmup_time_list)} ) metrics.append( {"name": "train_step_time", "value": np.mean(train_step_time_list)} ) metrics.append({"name": "epochs", "value": epochs}) wall_time = np.mean(wall_time_list) return metrics, wall_time def benchmark_custom_training_mnist_bs_128(self): """Measure performance with batch_size=128 and run_iters=5.""" batch_size = 128 run_iters = 5 train_dataset = self.train_dataset.shuffle(buffer_size=1024).batch( batch_size ) # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy( reduction=keras.losses.Reduction.NONE ) # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam() model = self._build_model() metrics, wall_time = self.measure_performance( model, train_dataset, loss_fn, optimizer, batch_size, run_iters, self.epochs, ) extras = benchmark_util.get_keras_examples_metadata( "conv", batch_size, ".keras.ctl_graph" ) self.report_benchmark( iters=run_iters, wall_time=wall_time, metrics=metrics, extras=extras ) def benchmark_custom_training_mnist_bs_256(self): """Measure performance with batch_size=256 and run_iters=5.""" batch_size = 256 run_iters = 5 train_dataset = self.train_dataset.shuffle(buffer_size=1024).batch( batch_size ) # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy( reduction=keras.losses.Reduction.NONE ) # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam() model = self._build_model() metrics, wall_time = self.measure_performance( model, train_dataset, loss_fn, optimizer, batch_size, run_iters, self.epochs, ) extras = benchmark_util.get_keras_examples_metadata( "conv", batch_size, ".keras.ctl_graph" ) self.report_benchmark( iters=run_iters, wall_time=wall_time, metrics=metrics, extras=extras ) def benchmark_custom_training_mnist_bs_512(self): """Measure performance with batch_size=512 and run_iters=10.""" batch_size = 512 run_iters = 5 train_dataset = self.train_dataset.shuffle(buffer_size=1024).batch( batch_size ) # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy( reduction=keras.losses.Reduction.NONE ) # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam() model = self._build_model() metrics, wall_time = self.measure_performance( model, train_dataset, loss_fn, optimizer, batch_size, run_iters, self.epochs, ) extras = benchmark_util.get_keras_examples_metadata( "conv", batch_size, ".keras.ctl_graph" ) self.report_benchmark( iters=run_iters, wall_time=wall_time, metrics=metrics, extras=extras ) def benchmark_custom_training_mnist_bs_512_gpu_2(self): """Measure performance with batch_size=512, run_iters=10, gpu=2 and distribution_strategy='mirrored'. """ batch_size = 512 run_iters = 10 train_dataset = self.train_dataset.shuffle(buffer_size=1024).batch( batch_size ) distribution_strategy = "mirrored" strategy = distribution_util.get_distribution_strategy( distribution_strategy=distribution_strategy, num_gpus=2 ) if distribution_strategy != "off": train_dataset = strategy.experimental_distribute_dataset( train_dataset ) strategy_scope = distribution_util.get_strategy_scope(strategy) with strategy_scope: # Instantiate a loss function. loss_fn = keras.losses.CategoricalCrossentropy( reduction=keras.losses.Reduction.NONE ) # Instantiate an optimizer to train the model. optimizer = keras.optimizers.Adam() model = self._build_model() metrics, wall_time = self.measure_performance( model, train_dataset, loss_fn, optimizer, batch_size, run_iters, self.epochs, strategy, ) extras = benchmark_util.get_keras_examples_metadata( "conv", batch_size, ".keras.ctl_graph" ) self.report_benchmark( iters=run_iters, wall_time=wall_time, metrics=metrics, extras=extras ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/benchmarks/keras_examples_benchmarks/mnist_conv_custom_training_benchmark_test.py/0
{ "file_path": "tf-keras/tf_keras/benchmarks/keras_examples_benchmarks/mnist_conv_custom_training_benchmark_test.py", "repo_id": "tf-keras", "token_count": 7669 }
169
# 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. # ============================================================================== """Utilities common to CIFAR10 and CIFAR100 datasets.""" import _pickle as cPickle def load_batch(fpath, label_key="labels"): """Internal utility for parsing CIFAR data. Args: fpath: path the file to parse. label_key: key for label data in the retrieve dictionary. Returns: A tuple `(data, labels)`. """ with open(fpath, "rb") as f: d = cPickle.load(f, encoding="bytes") # decode utf8 d_decoded = {} for k, v in d.items(): d_decoded[k.decode("utf8")] = v d = d_decoded data = d["data"] labels = d[label_key] data = data.reshape(data.shape[0], 3, 32, 32) return data, labels
tf-keras/tf_keras/datasets/cifar.py/0
{ "file_path": "tf-keras/tf_keras/datasets/cifar.py", "repo_id": "tf-keras", "token_count": 483 }
170
# Copyright 2021 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 `DatasetCreator` with `Model.fit` across usages and strategies.""" import tensorflow.compat.v2 as tf from tf_keras import callbacks as callbacks_lib from tf_keras.distribute import dataset_creator_model_fit_test_base as test_base from tf_keras.distribute import strategy_combinations from tf_keras.testing_infra import test_utils @test_utils.run_v2_only @tf.__internal__.distribute.combinations.generate( tf.__internal__.test.combinations.combine( strategy=strategy_combinations.parameter_server_strategies_multi_worker, use_dataset_creator=[True, False], mode="eager", ) ) class DatasetCreatorModelFitParameterServerStrategyOnlyTest( test_base.DatasetCreatorModelFitTestBase ): def testModelFitWithRunEagerly(self, strategy, use_dataset_creator): with self.assertRaisesRegex( ValueError, "When using `Model` with `ParameterServerStrategy`, " "`run_eagerly` is not supported.", ): self._model_fit( strategy, run_eagerly=True, use_dataset_creator=use_dataset_creator, ) def testModelPredict(self, strategy, use_dataset_creator): if use_dataset_creator: self.skipTest("Unused option.") model, _ = self._model_compile(strategy) test_data = ( tf.data.Dataset.from_tensor_slices( [[1.0], [2.0], [3.0], [1.0], [5.0], [1.0]] ) .repeat() .batch(2) ) model.predict(x=test_data, steps=3) def testClusterCoordinatorSingleInstance( self, strategy, use_dataset_creator ): model = self._model_fit( strategy, use_dataset_creator=use_dataset_creator ) strategy = model.distribute_strategy self.assertIs( strategy._cluster_coordinator, tf.distribute.experimental.coordinator.ClusterCoordinator(strategy), ) def testModelFitErrorOnBatchLevelCallbacks( self, strategy, use_dataset_creator ): class BatchLevelCallback(callbacks_lib.Callback): def on_train_batch_end(self, batch, logs=None): pass with self.assertRaisesRegex( ValueError, "Batch-level `Callback`s are not supported" ): callbacks = [BatchLevelCallback()] self._model_fit( strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator, ) def testModelFitCallbackSupportsTFLogs(self, strategy, use_dataset_creator): class MyCallback(callbacks_lib.Callback): def __init__(self): super().__init__() # Fetches the RemoteValues if necessary. self._supports_tf_logs = True def on_train_batch_end(self, batch, logs=None): assert isinstance( logs, tf.distribute.experimental.coordinator.RemoteValue ) my_callback = MyCallback() callbacks = [my_callback] self._model_fit( strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator, ) def testModelFitVerbosity(self, strategy, use_dataset_creator): class MyCallback(callbacks_lib.Callback): pass my_callback = MyCallback() callbacks = [my_callback] self._model_fit( strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator, ) # PSStrategy should default to epoch-level logging. self.assertEqual(my_callback.params["verbose"], 2) def testModelFitTensorBoardEpochLevel(self, strategy, use_dataset_creator): log_dir = self.get_temp_dir() callbacks = [callbacks_lib.TensorBoard(log_dir)] self._model_fit( strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator, ) self.assertTrue(tf.compat.v1.gfile.Exists(log_dir)) files = tf.compat.v1.gfile.ListDirectory(log_dir) self.assertGreaterEqual(len(files), 1) def testModelFitVerbose1(self, strategy, use_dataset_creator): with self.assertRaisesRegex( ValueError, "`verbose=1` is not allowed with " "`ParameterServerStrategy` for performance " "reasons. Received: verbose=1", ): self._model_fit( strategy, use_dataset_creator=use_dataset_creator, verbose=1 ) def testModelEvaluateErrorOnBatchLevelCallbacks( self, strategy, use_dataset_creator ): class BatchLevelCallback(callbacks_lib.Callback): def on_train_batch_end(self, batch, logs=None): pass with self.assertRaisesRegex( ValueError, "Batch-level `Callback`s are not supported" ): callbacks = [BatchLevelCallback()] self._model_evaluate( strategy, callbacks=callbacks, use_dataset_creator=use_dataset_creator, ) def testClusterCoordinatorSingleInstanceWithJitCompileTrue( self, strategy, use_dataset_creator ): model = self._model_fit( strategy, use_dataset_creator=use_dataset_creator, jit_compile=True ) strategy = model.distribute_strategy self.assertIs( strategy._cluster_coordinator, tf.distribute.experimental.coordinator.ClusterCoordinator(strategy), ) if __name__ == "__main__": tf.__internal__.distribute.multi_process_runner.test_main()
tf-keras/tf_keras/distribute/dataset_creator_model_fit_ps_only_test.py/0
{ "file_path": "tf-keras/tf_keras/distribute/dataset_creator_model_fit_ps_only_test.py", "repo_id": "tf-keras", "token_count": 2884 }
171
# Copyright 2018 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 that show that DistributionStrategy works with optimizer v2.""" import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized import tf_keras as keras from tf_keras.optimizers.legacy import adam from tf_keras.optimizers.legacy import gradient_descent def get_model(): x = keras.layers.Input(shape=(3,), name="input") y = keras.layers.Dense(4, name="dense")(x) model = keras.Model(x, y) return model class MirroredStrategyOptimizerV2Test(tf.test.TestCase, parameterized.TestCase): @tf.__internal__.distribute.combinations.generate( tf.__internal__.test.combinations.combine( distribution=[ tf.__internal__.distribute.combinations.central_storage_strategy_with_two_gpus, # noqa: E501 ], mode=["graph", "eager"], ) ) def testKerasOptimizerWithUnequalInput(self, distribution): with distribution.scope(): var = tf.Variable( 2.0, name="var", aggregation=tf.VariableAggregation.SUM ) optimizer = adam.Adam(learning_rate=0.01, beta_1=0.2, beta_2=0.2) all_vars = [] def model_fn(): def loss_fn(): replica_id = _replica_id() return tf.cast(replica_id + 1, dtype=tf.float32) * 0.5 * var train_op = optimizer.minimize(loss_fn, var_list=[var]) return train_op, optimizer def train_fn(): ( train_op, optimizer, ) = distribution.extended.call_for_each_replica(model_fn) if not all_vars: all_vars.append(var) all_vars.append(optimizer.get_slot(var, "m")) all_vars.append(optimizer.get_slot(var, "v")) return distribution.group(train_op) if not tf.executing_eagerly(): with self.cached_session() as sess: train_fn = sess.make_callable(train_fn()) self.evaluate(tf.compat.v1.global_variables_initializer()) # first step. train_fn() # var(1) = var(0) - lr * m(1) * sqrt(1 - beta2) / sqrt(v(1)) / (1 - # beta1) # = 2.0 - 0.01 * 1.2 * sqrt(0.8) / sqrt(1.8) / 0.8 self.assertAllClose(1.99, self.evaluate(all_vars[0])) # m(1) = beta1 * m(0) + (1-beta1) * grad = 0.2 * 0 + 0.8 * (1 + 2) / # 2 self.assertAllClose(1.2, self.evaluate(all_vars[1])) # v(1) = beta2 * v(0) + (1-beta2) * grad^2 = 0.2 * 0 + 0.8 * 2.25 self.assertAllClose(1.8, self.evaluate(all_vars[2])) # second step. train_fn() # var(1) = var(0) - lr * 2 = 1.98 self.assertAllClose(1.98, self.evaluate(all_vars[0])) # m(2) = beta1 * m(1) + (1-beta1) * grad = 0.2 * 1.2 + 0.8 * 1.5 self.assertAllClose(1.44, self.evaluate(all_vars[1])) # v(2) = beta2 * v(1) + (1-beta2) * grad^2 = 0.2 * 1.8 + 0.8 * 2.25 self.assertAllClose(2.16, self.evaluate(all_vars[2])) @tf.__internal__.distribute.combinations.generate( tf.__internal__.test.combinations.combine( distribution=[ tf.__internal__.distribute.combinations.central_storage_strategy_with_two_gpus, # noqa: E501 ], mode=["graph", "eager"], ) ) def testOptimizerWithKerasModelAndNumpyArrays(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.SGD(0.001) loss = "mse" metrics = ["mae"] model.compile(optimizer, loss, metrics=metrics) inputs = np.zeros((64, 3), dtype=np.float32) targets = np.zeros((64, 4), dtype=np.float32) model.fit( inputs, targets, epochs=1, batch_size=2, verbose=0, validation_data=(inputs, targets), ) model.evaluate(inputs, targets) model.predict(inputs) def _replica_id(): replica_id = tf.distribute.get_replica_context().replica_id_in_sync_group if not isinstance(replica_id, tf.Tensor): replica_id = tf.constant(replica_id) return replica_id if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/distribute/keras_optimizer_v2_test.py/0
{ "file_path": "tf-keras/tf_keras/distribute/keras_optimizer_v2_test.py", "repo_id": "tf-keras", "token_count": 2570 }
172
# Copyright 2020 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 evaluation using TF-Keras model and ParameterServerStrategy.""" import time import tensorflow.compat.v2 as tf import tf_keras as keras from tf_keras.testing_infra import test_utils # isort: off from tensorflow.python.distribute import ( multi_worker_test_base, ) from tensorflow.python.distribute.cluster_resolver import ( SimpleClusterResolver, ) from tensorflow.python.ops import resource_variable_ops # TODO(yuefengz): move the following implementation to TF-Keras core. class MeanMetricSpec(tf.TypeSpec): def __init__(self, config, weights): self._config = config self._weights = weights def _serialize(self): return (self._config, self._weights) @property def value_type(self): return MeanMetricAsCompositeTensor @property def _component_specs(self): return self._weights def _to_components(self, value): return value.weights def _from_components(self, weights): counter = [0] def fetch_variable(next_creator, **kwargs): del next_creator, kwargs # TODO(yuefengz): verify the var creation order matches the weights # property var = weights[counter[0]] counter[0] += 1 return var with tf.variable_creator_scope(fetch_variable): ret = MeanMetricAsCompositeTensor.from_config(self._config) assert len(weights) == len(ret.weights) return ret class MeanMetricAsCompositeTensor( keras.metrics.Mean, tf.__internal__.CompositeTensor ): def element_spec(self): raise NotImplementedError("element_spec not implemented") @property def _type_spec(self): weight_specs = [ resource_variable_ops.VariableSpec.from_value(w) for w in self.weights ] return MeanMetricSpec(self.get_config(), weight_specs) @test_utils.run_v2_only class EvaluationTest(tf.test.TestCase): @classmethod def setUpClass(cls): super(EvaluationTest, cls).setUpClass() cls._cluster = multi_worker_test_base.create_multi_process_cluster( num_workers=3, num_ps=2, rpc_layer="grpc" ) cls._cluster_def = ( cls._cluster.cluster_resolver.cluster_spec().as_dict() ) cluster_resolver = SimpleClusterResolver( tf.train.ClusterSpec(cls._cluster_def), rpc_layer="grpc" ) cls.strategy = tf.distribute.experimental.ParameterServerStrategy( cluster_resolver ) cls.cluster_coord = ( tf.distribute.experimental.coordinator.ClusterCoordinator( cls.strategy ) ) @classmethod def tearDownClass(cls): cls._cluster.stop() cls._cluster = None super(EvaluationTest, cls).tearDownClass() def testPassMetricToTfFunction(self): metric1 = MeanMetricAsCompositeTensor() metric2 = MeanMetricAsCompositeTensor() self.assertEqual(metric1.result(), 0.0) self.assertEqual(metric2.result(), 0.0) tf.nest.assert_same_structure( metric1, metric2._type_spec, expand_composites=True ) tf.nest.assert_same_structure( metric1._type_spec, metric2, expand_composites=True ) @tf.function def func(m): m.update_state([1.0, 2.0]) func(metric1) self.assertEqual(metric1.result(), 1.5) self.assertEqual(metric2.result(), 0.0) concrete_f = func.get_concrete_function(metric1._type_spec) concrete_f(metric2) self.assertEqual(metric1.result(), 1.5) self.assertEqual(metric2.result(), 1.5) def testModelEvaluatePrototype(self): def metric_fn(): return MeanMetricAsCompositeTensor() # TODO(yuefengz): make _create_per_worker_resources public and get rid # of the type_spec hack. per_worker_metric = self.cluster_coord._create_per_worker_resources( metric_fn ) metric_on_coordinator = metric_fn() for metric_remote_value in per_worker_metric._values: metric_remote_value._type_spec = metric_on_coordinator._type_spec def dataset_fn(): return tf.data.Dataset.range(1024) # TODO(yuefengz): integrate it into model.evaluate. @tf.function def eval_fn(total_shard, shard_id, metric): metric.reset_states() dataset_shard = dataset_fn().shard(total_shard, shard_id) for i in dataset_shard: metric.update_state(i) # TODO(yuefengz): we should return the internal state of the metric # and then use the combiner API. return metric.result() total_shards = 128 result_remote_values = [] for i in range(total_shards): result_remote_values.append( self.cluster_coord.schedule( eval_fn, args=(total_shards, i, per_worker_metric) ) ) self._cluster.kill_task("worker", 0) self._cluster.kill_task("worker", 1) time.sleep(1) self._cluster.start_task("worker", 0) self._cluster.start_task("worker", 1) results = [r.fetch() for r in result_remote_values] result = sum(results) / len(results) self.assertEqual(result, 511.5) if __name__ == "__main__": tf.__internal__.distribute.multi_process_runner.test_main()
tf-keras/tf_keras/distribute/parameter_server_evaluation_test.py/0
{ "file_path": "tf-keras/tf_keras/distribute/parameter_server_evaluation_test.py", "repo_id": "tf-keras", "token_count": 2685 }
173
# Copyright 2022 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 layers.""" import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized from tf_keras import backend from tf_keras import layers from tf_keras.dtensor import dtensor_api as dtensor from tf_keras.dtensor import test_util from tf_keras.utils import tf_utils class LayersTest(test_util.DTensorBaseTest): def setUp(self): super().setUp() backend.enable_tf_random_generator() tf_utils.set_random_seed(1337) global_ids = test_util.create_device_ids_array((2, 2)) local_device_ids = np.ravel(global_ids).tolist() mesh_dict = { "CPU": dtensor.Mesh( ["X", "Y"], global_ids, local_device_ids, test_util.create_device_list((2, 2), "CPU"), ) } self.mesh = self.configTestMesh(mesh_dict) @parameterized.named_parameters( ( "dense", layers.Dense, {"units": 4}, {"kernel": 2, "bias": 1}, [10, 8], ), # TODO(b/224861663): Enable this test. # ('embedding', layers.Embedding, {'input_dim': 100, 'output_dim': 32}, # {'embeddings': 2}, [10,], np.int32), ( "conv1d", layers.Conv1D, {"filters": 4, "kernel_size": 3}, {"kernel": 3, "bias": 1}, [10, 28, 3], ), ( "conv1d_transpose", layers.Conv1DTranspose, {"filters": 4, "kernel_size": 3}, {"kernel": 3, "bias": 1}, [10, 28, 3], ), ( "conv2d", layers.Conv2D, {"filters": 4, "kernel_size": (3, 3)}, {"kernel": 4, "bias": 1}, [10, 28, 28, 3], ), ( "conv2d_transpose", layers.Conv2DTranspose, {"filters": 4, "kernel_size": (3, 3)}, {"kernel": 4, "bias": 1}, [10, 28, 28, 3], ), ( "conv3d", layers.Conv3D, {"filters": 4, "kernel_size": (3, 3, 3)}, {"kernel": 5, "bias": 1}, [10, 28, 28, 28, 3], ), # TODO(b/224862394): Add support for tf.Conv3DBackpropInputV2 # ('conv3dtranspose', layers.Conv3DTranspose, # {'filters': 4, 'kernel_size': (3, 3, 3)}, # {'kernel': 5, 'bias': 1}, [10, 28, 28, 28, 3]), ( "batch_norm", layers.BatchNormalization, {"fused": False}, {"beta": 1, "gamma": 1, "moving_mean": 1, "moving_variance": 1}, [10, 28, 28, 3], ), ( "layer_norm", layers.LayerNormalization, {"dtype": tf.float64}, {"beta": 1, "gamma": 1}, [10, 28, 28, 3], ), ) def test_layer( self, layer_cls, init_args, variable_settings, input_shape, input_dtype=np.float32, ): args_with_layout = init_args.copy() for variable_name, variable_rank in variable_settings.items(): args_with_layout[ variable_name + "_layout" ] = dtensor.Layout.replicated(self.mesh, variable_rank) layer = layer_cls(**args_with_layout) # inputs = np.random.random(input_shape) inputs = np.random.randn(*input_shape).astype(input_dtype) d_inputs = dtensor.copy_to_mesh( inputs, dtensor.Layout.replicated(self.mesh, len(input_shape)) ) d_output = layer(d_inputs) for variable_name, variable_rank in variable_settings.items(): self.assertIsInstance( getattr(layer, variable_name), dtensor.DVariable ) expected_layout = dtensor.Layout.replicated( self.mesh, d_output.shape.rank ) self.assertEqual(dtensor.fetch_layout(d_output), expected_layout) # Make sure to produce same output when layout is not used tf_utils.set_random_seed(1337) layer_2 = layer_cls(**init_args) output = layer_2(inputs) self.assertAllClose(d_output, output) for variable_name, variable_rank in variable_settings.items(): self.assertNotIsInstance( getattr(layer_2, variable_name), dtensor.DVariable ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/dtensor/layers_test.py/0
{ "file_path": "tf-keras/tf_keras/dtensor/layers_test.py", "repo_id": "tf-keras", "token_count": 2531 }
174
# Copyright 2018 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. # ============================================================================== """Contains private utilities used mainly by the base Layer class.""" import functools import threading import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras.dtensor import dtensor_api as dtensor from tf_keras.utils import control_flow_util from tf_keras.utils import tf_inspect from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export _call_context = threading.local() def create_mean_metric(value, name=None): # import keras will import base_layer and then this module, and metric # relies on base_layer, which result into a cyclic dependency. from tf_keras import metrics as metrics_module metric_obj = metrics_module.Mean(name=name, dtype=value.dtype) return metric_obj, metric_obj(value) def infer_init_val_and_dtype(initializer, dtype, shape, layout=None): if initializer is not None and not callable(initializer): init_val = initializer variable_dtype = None else: # Instantiate initializer if provided initializer is a type object. if tf_inspect.isclass(initializer): initializer = initializer() if layout: init_val = functools.partial( initializer, shape, dtype=dtype, layout=layout ) else: init_val = functools.partial(initializer, shape, dtype=dtype) variable_dtype = dtype.base_dtype return init_val, variable_dtype def make_variable( name, shape=None, dtype=tf.float32, initializer=None, trainable=None, caching_device=None, validate_shape=True, constraint=None, use_resource=None, collections=None, synchronization=tf.VariableSynchronization.AUTO, aggregation=tf.VariableAggregation.NONE, partitioner=None, layout=None, experimental_enable_variable_lifting=True, ): """Util to create a variable (relies on `variable_scope.variable`). Some reuse-related technicalities prevent us from using `variable_scope.get_variable()` directly, so we use a subcomponent that has fewer constraints (`variable_scope.variable()`). In the longer term, it seems like a similar "default variable creator" method should exist in `Trackable` instead. When this happens, we can get rid of this temporary solution. TODO(fchollet): remove this method when no longer needed. Args: name: Variable name. shape: Variable shape. dtype: The type of the variable. Defaults to `self.dtype` or `float32`. initializer: Initializer instance (callable). trainable: Whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean, stddev). Note, if the current variable scope is marked as non-trainable then this parameter is ignored and any added variables are also marked as non-trainable. `trainable` becomes `True` unless `synchronization` is set to `ON_READ`. Defaults to `None`. caching_device: Passed to `tf.Variable`. validate_shape: Passed to `tf.Variable`. constraint: Constraint instance (callable). use_resource: Whether to use a `ResourceVariable`. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class `tf.VariableSynchronization`. By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. If `synchronization` is set to `ON_READ`, `trainable` must not be set to `True`. aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class `tf.VariableAggregation`. partitioner: Not handled at this time. layout: the optional DTensor layout, used for creating DVariable. Returns: Variable instance. """ init_val, variable_dtype = infer_init_val_and_dtype( initializer, dtype, shape, layout ) variable_shape = tf.TensorShape(shape) if use_resource is None: use_resource = True if layout is None: # In theory, in `use_resource` is True and `collections` is empty # (that is to say, in TF2), we can use tf.Variable. # However, this breaks legacy (Estimator) checkpoints because # it changes variable names. Remove this when V1 is fully deprecated. return tf1.Variable( initial_value=init_val, name=name, trainable=trainable, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint, use_resource=use_resource, collections=collections, synchronization=synchronization, aggregation=aggregation, shape=variable_shape if variable_shape else None, experimental_enable_variable_lifting=experimental_enable_variable_lifting, # noqa: E501 ) else: return dtensor.DVariable( initial_value=init_val, name=name, trainable=trainable, caching_device=caching_device, dtype=variable_dtype, validate_shape=validate_shape, constraint=constraint, collections=collections, synchronization=synchronization, aggregation=aggregation, shape=variable_shape if variable_shape else None, ) def collect_previous_mask(input_tensors): """Retrieves the output mask(s) of the previous node. Args: input_tensors: An arbitrary structure of Tensors. Returns: A mask tensor or list of mask tensors. """ def _collect_previous_mask(x): return getattr(x, "_keras_mask", None) return tf.nest.map_structure(_collect_previous_mask, input_tensors) def have_all_keras_metadata(tensors): return all(hasattr(x, "_keras_history") for x in tf.nest.flatten(tensors)) def generate_placeholders_from_shape(shape): return tf1.placeholder(shape=shape, dtype=backend.floatx()) def create_keras_history(tensors): """Wraps TensorFlow Operations for compatibility with the Functional API. This method checks to see if a Tensor in `tensors` is missing TF-Keras metadata and has its origin in a TF-Keras `Input` Layer. If so, this method will replace the raw TensorFlow Operations that created this tensor with `TensorFlowOpLayer` instances that create identical operations. Any Tensors not originating from a TF-Keras `Input` Layer will be treated as constants when constructing `TensorFlowOpLayer` instances. Args: tensors: A structure of Tensors, some of which come from raw TensorFlow operations and need to have TF-Keras metadata assigned to them. Returns: created_layers: List. The `TensorFlowOpLayer` instances created to wrap the raw Tensorflow operations. """ _, created_layers = _create_keras_history_helper(tensors, set(), []) return created_layers # Unsafe Internal attribute. # If True, TF-Keras will not evaluate the constant-foldable inputs to tf op # layers in TF1 graphs. This *might* speed up model construction time in # certain settings, but it means # the models will not be serializable/deserializable via get_config # (Only via Savedmodels). It may also change the semantics of whether # generated random numbers are generated once and re-used, or recomputed # each time. # Note: This path triggers for TPUEstimators / xla compiled graphs regardless # of this setting. _UNSAFE_GRAPH_OP_LAYER_CREATION = False def _create_keras_history_helper(tensors, processed_ops, created_layers): """Helper method for `create_keras_history`. Args: tensors: A structure of Tensors for which to create TF-Keras metadata. processed_ops: Set. TensorFlow operations that have already been wrapped in `TensorFlowOpLayer` instances. created_layers: List. The `TensorFlowOpLayer` instances created. Returns: Tuple. First element is the updated set of TensorFlow Operations that have been wrapped in `TensorFlowOpLayer` instances. Second element is a list of the `TensorFlowOpLayer` instances created. """ if tf1.executing_eagerly_outside_functions(): raise ValueError( "`create_keras_history` should only be called if eager is disabled!" ) # Import of `base_layer` needed in order to create `TensorFlowOpLayer`. # Cannot be imported at top because of circular dependencies. # TODO(omalleyt): Resolve circular dependency. from tf_keras.engine import base_layer tensor_list = tf.nest.flatten(tensors) sparse_ops = [] ragged_tensors = [] for tensor in tensor_list: if getattr(tensor, "_keras_history", None) is not None: continue if isinstance(tensor, (tf.SparseTensor, tf1.SparseTensorValue)): sparse_ops.append(tensor.op) continue if tf_utils.is_ragged(tensor): # Ragged tensors don't have an op property ragged_tensors.append(tensor) continue op = tensor.op # The Op that created this Tensor. if op not in processed_ops: # Recursively set `_keras_history`. op_inputs = list(op.inputs) constants = {} layer_inputs = [] for i, op_input in enumerate(op_inputs): if uses_keras_history(op_input): layer_inputs.append(op_input) else: # Treat any value not originating from a `keras.Input` as # a constant. Variables cannot be supported. ds_with_session = ( tf.distribute.in_cross_replica_context() and not tf1.executing_eagerly_outside_functions() ) using_xla = control_flow_util.GraphOrParentsInXlaContext( tf1.get_default_graph() ) if ( ds_with_session or using_xla or _UNSAFE_GRAPH_OP_LAYER_CREATION ): # In Legacy Graph mode, evaluating here makes Session be # configured improperly. The downside of this is that # saving via `get_config` breaks, but SavedModel still # works. constants[i] = op_input else: with tf.init_scope(): constants[i] = backend.function([], op_input)([]) layer_inputs = unnest_if_single_tensor(layer_inputs) processed_ops, created_layers = _create_keras_history_helper( layer_inputs, processed_ops, created_layers ) name = op.name node_def = op.node_def.SerializeToString() op_layer = base_layer.TensorFlowOpLayer( node_def, constants=constants, name=name ) created_layers.append(op_layer) op_layer._set_connectivity_metadata( args=(layer_inputs,), kwargs={}, outputs=op.outputs ) processed_ops.update([op]) if sparse_ops or ragged_tensors: lambda_example = """ weights_mult = lambda x: tf.sparse.sparse_dense_matmul(x, weights) output = tf.keras.layers.Lambda(weights_mult)(input) """ raise ValueError( "Tensorflow ops that generate ragged or sparse tensor " "outputs are currently not supported by TF-Keras automatic " "op wrapping. Please wrap these ops in a Lambda layer: " "\n\n```\n{example}\n```\n" "Sparse ops encountered: {sparse_ops}\n" "Ragged tensors encountered: {ragged_tensors}\n".format( example=lambda_example, sparse_ops=str(sparse_ops), ragged_tensors=str(ragged_tensors), ) ) return processed_ops, created_layers def unnest_if_single_tensor(input_tensors): # Preserve compatibility with older configs flat_input_tensors = tf.nest.flatten(input_tensors) # If this is a single element but not a dict, unwrap. If this is a dict, # assume the first layer expects a dict (as is the case with a # DenseFeatures layer); pass through. if not isinstance(input_tensors, dict) and len(flat_input_tensors) == 1: input_tensors = flat_input_tensors[0] return input_tensors def needs_keras_history(tensors, ignore_call_context=False): """Check if any Tensors need to be wrapped in TensorFlowOpLayers. This will never return True inside a sublayer, because sublayers do not need to create TF-Keras History. Otherwise, this returns True if one or more of `tensors` originates from a `keras.Input` and does not have `_keras_history` set. Args: tensors: An arbitrary nested structure of Tensors. ignore_call_context: Whether to ignore the check of if currently outside of a `call` context. This is `True` when creating KerasHistory inside `Node`, where we always know that Tensors are being used with the Functional API. Returns: Bool, whether at least one Tensor needs to be wrapped. """ input_tensors = tf.nest.flatten(tensors) if call_context().in_call and not ignore_call_context: return False if all( getattr(tensor, "_keras_history", None) is not None for tensor in input_tensors ): # KerasHistory already set. return False return uses_keras_history(tensors) def is_in_keras_graph(): """Returns if currently executing inside of a TF-Keras graph.""" return call_context().in_keras_graph def is_in_eager_or_tf_function(): """Returns if in eager mode or inside of a tf.function.""" return tf.executing_eagerly() or is_in_tf_function() def is_in_tf_function(): """Returns if inside of a tf.function.""" # Check if running in V1 graph mode. if not tf1.executing_eagerly_outside_functions(): return False if not tf.inside_function(): return False # Check if inside TF-Keras FuncGraph. if is_in_keras_graph(): return False # Check for a v1 `wrap_function` FuncGraph. graph = tf1.get_default_graph() if getattr(graph, "name", False) and graph.name.startswith( "wrapped_function" ): return False return True def uses_keras_history(tensors): """Check if at least one Tensor originates from a `keras.Input`. This is `True` if at least one Tensor has its origin in a `keras.Input`. Any Tensor that originates from a `keras.Input` will have a dependency Tensor with a `_keras_history` attribute attached. Tensors that have already been checked to not originate from a `keras.Input` are marked as `_keras_history_checked`. Args: tensors: An arbitrary nested structure of Tensors. Returns: Bool, whether at least one Tensor originates from a `keras.Input`. """ checked_tensors = set() tensors_to_check = tf.nest.flatten(tensors) while tensors_to_check: new_tensors_to_check = [] for tensor in tensors_to_check: if id(tensor) in checked_tensors: continue checked_tensors.add(id(tensor)) if getattr(tensor, "_keras_history_checked", None) is not None: continue if getattr(tensor, "_keras_history", None) is not None: return True try: new_tensors_to_check.extend(tensor.op.inputs) except AttributeError: # In case `tensor` is a Variable created in an Eager context. pass tensors_to_check = new_tensors_to_check # Mark that these Tensors have been checked once for `_keras_history`, # and should not be checked again for performance reasons. mark_checked(tensors) return False def mark_checked(tensors): """Marks that these Tensors should not be tracked. This prevents Layers from attempting to create TensorFlowOpLayers for these Tensors. Args: tensors: An arbitrary structure of Tensors. """ def _mark_checked(tensor): tensor._keras_history_checked = True tf.nest.map_structure(_mark_checked, tensors) def call_context(): """Returns currently active `CallContext`.""" call_ctx = getattr(_call_context, "call_context", None) if call_ctx is None: call_ctx = CallContext() _call_context.call_context = call_ctx return call_ctx # Inject the call_context function to keras_deps to remove the dependency # from TFLite to TF-Keras. tf.__internal__.register_call_context_function(call_context) class CallContext: """Keeps track of properties currently inside a Layer/Model's `call`. Attributes: in_call: Whether currently inside the `call` of a Layer. layer: The `Layer` whose `call` is currently active. inputs: The inputs to the currently active `Layer`. build_graph: Whether currently inside a Graph or FuncGraph. training: Whether currently executing in training or inference mode. saving: Whether currently saving to SavedModel. frozen: Whether currently executing inside a `Layer` with `trainable` set to `False`. in_keras_graph: Whether executing inside the TF-Keras Graph. """ def __init__(self): # Handle `in_call` separately as it is the most-read attr and reading it # is on the hot path. self.in_call = False self._state = { "layer": None, "inputs": None, "build_graph": False, "training": None, "saving": None, } # TODO(b/150169018): This logic can be replaced after the Functional API # refactor. self._in_keras_graph = False def enter(self, layer, inputs, build_graph, training, saving=None): """Push a Layer and its inputs and state onto the current call context. Args: layer: The `Layer` whose `call` is currently active. inputs: The inputs to the currently active `Layer`. build_graph: Whether currently inside a Graph or FuncGraph. training: Whether currently executing in training or inference mode. saving: Whether currently saving to SavedModel. Returns: Context manager. """ state = { "layer": layer, "inputs": inputs, "build_graph": build_graph, "training": training, "saving": saving, } return CallContextManager(self, state) @property def layer(self): return self._state["layer"] @property def inputs(self): return self._state["inputs"] @property def build_graph(self): return self._state["build_graph"] @property def training(self): return self._state["training"] @property def saving(self): return self._state["saving"] @property def frozen(self): layer = self._state["layer"] if not layer: return False return not layer.trainable @property def in_keras_graph(self): # Returns True even if in a subgraph of the TF-Keras graph, such as # those created by control flow ops. if tf.executing_eagerly(): return False return ( self._in_keras_graph or getattr(backend.get_graph(), "name", None) == "keras_graph" ) class CallContextManager: """Context manager for `CallContext`.""" def __init__(self, call_ctx, state): self._call_ctx = call_ctx self._state = state self._build_graph = state["build_graph"] def __enter__(self): call_ctx = self._call_ctx self._prev_in_call = call_ctx.in_call self._prev_state = call_ctx._state call_ctx.in_call = True call_ctx._state = self._state # TODO(b/150169018): This logic can be removed after the Functional API # refactor. if self._build_graph: self._prev_in_keras_graph = call_ctx._in_keras_graph call_ctx._in_keras_graph = ( call_ctx._in_keras_graph or getattr(backend.get_graph(), "name", None) == "keras_graph" ) def __exit__(self, *exc_info): call_ctx = self._call_ctx call_ctx.in_call = self._prev_in_call call_ctx._state = self._prev_state if self._build_graph: call_ctx._in_keras_graph = self._prev_in_keras_graph def training_arg_passed_to_call(argspec, args, kwargs): """Returns whether a user passed the `training` argument in `__call__`.""" # `argspec.args` starts with ['self', 'inputs'] full_args = dict(zip(argspec.args[2:], args)) full_args.update(kwargs) return "training" in full_args and full_args["training"] is not None def is_subclassed(layer): """Returns True if the object is a subclassed layer or subclassed model.""" return ( "keras.engine" not in layer.__module__ and "keras.src.engine" not in layer.__module__ and "keras.layers" not in layer.__module__ and "keras.src.layers" not in layer.__module__ ) def from_saved_model(layer): """Returns whether the layer is loaded from a SavedModel.""" return "legacy.saved_model" in layer.__module__ def check_graph_consistency(tensor=None, method="add_loss", force_raise=False): """Checks that tensors passed to `add_*` method match the TF-Keras graph. When one of the `add_*` method is called inside a V2 conditional branch, the underlying tensor gets created in a FuncGraph managed by control_flow_v2. We need to raise clear error messages in such cases. Args: tensor: Tensor to check, or `False` if it is known that an error should be raised. method: Caller method, one of {'add_metric', 'add_loss', 'add_update'}. force_raise: If an error should be raised regardless of `tensor`. Raises: RuntimeError: In case of an out-of-graph tensor. """ if force_raise or ( tf1.executing_eagerly_outside_functions() and hasattr(tensor, "graph") and tensor.graph.is_control_flow_graph ): if method == "activity_regularizer": bad_example = """ class TestModel(tf.keras.Model): def __init__(self): super(TestModel, self).__init__(name='test_model') self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') def call(self, x, training=None): if training: return self.dense(x) else: return self.dense(x) """ correct_example = """ class TestModel(tf.keras.Model): def __init__(self): super(TestModel, self).__init__(name='test_model') self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') def call(self, x, training=None): return self.dense(x) """ raise RuntimeError( "You are using a layer with `activity_regularizer` in a " f"control flow branch, e.g.:\n{bad_example}\nThis is currently " "not supported. Please move your call to the layer with " "`activity_regularizer` out of the control flow branch, " f"e.g.:\n{correct_example}\nYou can also resolve this by " "marking your outer model/layer dynamic (eager-only) by " "passing `dynamic=True` to the layer constructor. Any kind of " "control flow is supported with dynamic layers. Note that " "using `dynamic=True` requires you to implement static shape " "inference in the `compute_output_shape(input_shape)` " "method." ) if method == "add_metric": bad_example = """ def call(self, inputs, training=None): if training: metric = compute_metric(inputs) self.add_metric(metric, name='my_metric', aggregation='mean') return inputs """ correct_example = """ def call(self, inputs, training=None): if training: metric = compute_metric(inputs) else: metric = 0. self.add_metric(metric, name='my_metric', aggregation='mean') return inputs """ elif method == "add_loss": bad_example = """ def call(self, inputs, training=None): if training: loss = compute_loss(inputs) self.add_loss(loss) return inputs """ correct_example = """ def call(self, inputs, training=None): if training: loss = compute_loss(inputs) else: loss = 0. self.add_loss(loss) return inputs """ else: bad_example = """ def call(self, inputs, training=None): if training: self.add_update(self.w.assign_add(1)) return inputs """ correct_example = """ def call(self, inputs, training=None): if training: increment = 1 else: increment = 0 self.add_update(self.w.assign_add(increment)) return inputs """ raise RuntimeError( "You are using the method `{method}` in a control flow branch " "in your layer, e.g.:\n{bad_example}\n" "This is not currently supported. " "Please move your call to {method} out of the control flow branch, " "e.g.:\n{correct_example}\n" "You can also resolve this by marking your layer " "as dynamic (eager-only) by passing " "`dynamic=True` to the layer constructor. " "Any kind of control flow is supported with dynamic layers. " "Note that using `dynamic=True` requires you " "to implement static shape inference " "in the `compute_output_shape(input_shape)` method.".format( method=method, bad_example=bad_example, correct_example=correct_example, ) ) def mark_as_return(outputs, acd): """Marks `outputs` as the return values for automatic control deps.""" def _mark_as_return(tensor): """Marks `tensor` as the return value for automatic control deps.""" if not tf.is_tensor(tensor): return tensor return_tensor = acd.mark_as_return(tensor) if getattr(tensor, "_keras_mask", None) is not None: return_tensor._keras_mask = acd.mark_as_return(tensor._keras_mask) else: return_tensor._keras_mask = None # Handle TensorFlow Probability attached metadata. # TODO(b/132076537): Remove this once TFP uses `CompositeTensor`. if getattr(tensor, "_tfp_distribution", None) is not None: return_tensor._tfp_distribution = tensor._tfp_distribution return return_tensor return tf.nest.map_structure(_mark_as_return, outputs) V2_DTYPE_BEHAVIOR = None @keras_export(v1=["keras.layers.enable_v2_dtype_behavior"]) def enable_v2_dtype_behavior(): """Enable the V2 dtype behavior for TF-Keras layers. By default, the V2 dtype behavior is enabled in TensorFlow 2, so this function is only useful if `tf.compat.v1.disable_v2_behavior` has been called. Since mixed precision requires V2 dtype behavior to be enabled, this function allows you to use mixed precision in TF-Keras layers if `disable_v2_behavior` has been called. When enabled, the dtype of TF-Keras layers defaults to floatx (which is typically float32) instead of None. In addition, layers will automatically cast floating-point inputs to the layer's dtype. >>> x = tf.ones((4, 4, 4, 4), dtype='float64') >>> layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2) >>> print(layer.dtype) # float32 since V2 dtype behavior is enabled float32 >>> y = layer(x) # Layer casts inputs since V2 dtype behavior is enabled >>> print(y.dtype.name) float32 A layer author can opt-out their layer from the automatic input casting by passing `autocast=False` to the base Layer's constructor. This disables the autocasting part of the V2 behavior for that layer, but not the defaulting to floatx part of the V2 behavior. When a global `tf.keras.mixed_precision.Policy` is set, a TF-Keras layer's dtype will default to the global policy instead of floatx. Layers will automatically cast inputs to the policy's compute_dtype. """ global V2_DTYPE_BEHAVIOR V2_DTYPE_BEHAVIOR = True @keras_export(v1=["keras.layers.disable_v2_dtype_behavior"]) def disable_v2_dtype_behavior(): """Disables the V2 dtype behavior for TF-Keras layers. See `tf.compat.v1.keras.layers.enable_v2_dtype_behavior`. """ global V2_DTYPE_BEHAVIOR V2_DTYPE_BEHAVIOR = False def v2_dtype_behavior_enabled(): """Returns True if the V2 dtype behavior is enabled.""" if V2_DTYPE_BEHAVIOR is None: return tf.__internal__.tf2.enabled() return V2_DTYPE_BEHAVIOR class TrackableWeightHandler: """Keras wrapper for handling Trackable object saving and restoring. This class handles Trackables in both V1 and V2 modes, ensuring that they can be saved and restored with the correct data and without adding additional ops on every save. Attributes: trackable: The trackable to wrap. num_tensors: The number of tensors that this trackable requires for saving. """ def __init__(self, trackable): if not isinstance(trackable, tf.__internal__.tracking.Trackable): raise ValueError(f"{trackable} is not a Trackable object.") self._trackable = trackable self._distribute_strategy = tf.distribute.get_strategy() saveables = tf.__internal__.tracking.saveable_objects_from_trackable( trackable ).values() # 'Saveables' won't exist when we're passed a legacy TF1 table like # a StaticHashTable. if not saveables: self._num_tensors = 0 self._setter = lambda weights: None self._getter = lambda: [] elif len(saveables) == 1: saveable = list(saveables)[0] if tf1.executing_eagerly_outside_functions(): # If we're in eager mode, we need to defer calling the # Trackable's saveable() callable until data export time. # However, it is safe to call the saveable as many times as we # want, so we will call it now to figure out how many tensors # this Trackable will produce. self._saveable = saveable self._num_tensors = len(self._saveable().specs) self._setter = lambda weights: self._saveable().restore( weights, None ) self._getter = lambda: [ spec.tensor for spec in self._saveable().specs ] else: # If we're in Graph mode, we need to evaluate the Saveable only # once and cache the resulting restore graph. Failing to do this # will result in new assignment ops being added to the graph # each time set_weights() is called. self._placeholder_tensors = [] self._saveable = saveable() self._num_tensors = len(self._saveable.specs) for spec in self._saveable.specs: tensor = spec.tensor self._placeholder_tensors.append( tf1.placeholder(tensor.dtype, tensor.shape) ) self._assign_op = self._saveable.restore( self._placeholder_tensors, None ) self._setter = self._set_weights_v1 self._getter = lambda: [ spec.tensor for spec in self._saveable.specs ] else: raise ValueError( "Only Trackables with one Saveable are supported. " f"The Trackable {trackable} has {len(saveables)} Saveables." ) @property def num_tensors(self): return self._num_tensors def set_weights(self, weights): if len(weights) != self._num_tensors: raise ValueError( f"Weight handler for trackable {self._trackable} received " "an incorrect number of weights: " f"expected {self._num_tensors} weights, " f"got {len(weights)} weights." ) self._setter(weights) def get_tensors(self): return self._getter() def _set_weights_v1(self, weights): feed_dict = {} for idx, tensor in enumerate(weights): feed_dict[self._placeholder_tensors[idx]] = tensor backend.get_session().run(self._assign_op, feed_dict) def no_ragged_support(inputs, layer_name): input_list = tf.nest.flatten(inputs) if any(isinstance(x, tf.RaggedTensor) for x in input_list): raise ValueError( f"Layer {layer_name} does not support RaggedTensors as input. " f"Inputs received: {inputs}. You can try converting your " "input to a dense (uniform) tensor." ) def is_split_variable(v): """Returns True if `v` is a PartitionedVariable or a ShardedVariable.""" return not {clz.__name__ for clz in v.__class__.__mro__}.isdisjoint( {"PartitionedVariable", "ShardedVariable"} ) def has_weights(obj): obj_type = type(obj) return ( hasattr(obj_type, "trainable_weights") and hasattr(obj_type, "non_trainable_weights") and not isinstance(obj, type) ) # TODO(kathywu): This is a temporary hack. When a network of layers is revived # from SavedModel, only the top-level layer will have losses. This causes issues # in eager mode because the child layers may have graph losses # (thus model.losses returns a mix of Eager and graph tensors). To fix this, # whenever eager losses are added to one layer, add eager losses to all # child layers. This causes `.losses` to only return eager losses. REVIVED_LOSS_PLACEHOLDER = ( "This layer's losses have been added to the parent layer." )
tf-keras/tf_keras/engine/base_layer_utils.py/0
{ "file_path": "tf-keras/tf_keras/engine/base_layer_utils.py", "repo_id": "tf-keras", "token_count": 14800 }
175
# Copyright 2021 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 functional_utils.""" import collections import os import numpy as np import tensorflow.compat.v2 as tf from tf_keras import layers from tf_keras import models from tf_keras.engine import functional_utils from tf_keras.engine import input_layer as input_layer_lib from tf_keras.testing_infra import test_combinations @test_combinations.run_all_keras_modes(always_skip_v1=True) class FunctionalModelSlideTest(test_combinations.TestCase): def test_find_nodes_by_inputs_and_outputs(self): inputs = input_layer_lib.Input((10,)) unconnected_inputs = input_layer_lib.Input((10,)) x = layers.Dense(8)(inputs) y = layers.Dense(6)(x) output = layers.Dense(4)(y) nodes_in_graph = functional_utils.find_nodes_by_inputs_and_outputs( x, output ) self.assertLen(nodes_in_graph, 2) expected_nodes = [output.node, y.node] self.assertCountEqual(nodes_in_graph, expected_nodes) # Make sure we raise error if we specify invalid input/output pair with self.assertRaisesRegex( ValueError, "Found input tensor cannot be reached" ): functional_utils.find_nodes_by_inputs_and_outputs(output, x) with self.assertRaisesRegex( ValueError, "Found input tensor cannot be reached" ): functional_utils.find_nodes_by_inputs_and_outputs( unconnected_inputs, output ) with self.assertRaisesRegex( ValueError, "Found unvisited input tensors that are disconnected" ): functional_utils.find_nodes_by_inputs_and_outputs( [inputs, unconnected_inputs], output ) def test_find_nodes_by_inputs_and_outputs_with_complicated_network(self): input1 = input_layer_lib.Input((10,)) input2 = input_layer_lib.Input((10,)) input3 = input_layer_lib.Input((10,)) unconnected_input = input_layer_lib.Input((10,)) dense1 = layers.Dense(4, name="dense1") dense2 = layers.Dense(4, name="dense2") # dense1 are shared between input1 and input2 a = dense1(input1) b = dense1(input2) c = layers.Add()([a, b]) d = dense2(input3) e = layers.Add()([c, d]) # There are 5 nodes (invoke of __call__) in the graph. nodes = functional_utils.find_nodes_by_inputs_and_outputs(input1, a) self.assertCountEqual(nodes, [a.node]) nodes = functional_utils.find_nodes_by_inputs_and_outputs(input2, b) self.assertCountEqual(nodes, [b.node]) nodes = functional_utils.find_nodes_by_inputs_and_outputs( [input2, input1], c ) # This should contains 2 dense call and 1 add self.assertCountEqual(nodes, [a.node, b.node, c.node]) # Missing input3 with self.assertRaisesRegex( ValueError, "Found input tensor cannot be reached" ): functional_utils.find_nodes_by_inputs_and_outputs( [input1, input2], e ) nodes = functional_utils.find_nodes_by_inputs_and_outputs( [input1, input2, input3], e ) self.assertCountEqual(nodes, [a.node, b.node, c.node, d.node, e.node]) # Make sure we can create from intermediate tensors nodes = functional_utils.find_nodes_by_inputs_and_outputs( [a, b, input3], e ) self.assertCountEqual(nodes, [c.node, d.node, e.node]) # Also make sure we can add intermediate outputs nodes = functional_utils.find_nodes_by_inputs_and_outputs( [a, b, input3], [d, e] ) self.assertCountEqual(nodes, [c.node, d.node, e.node]) # input1 and 2 are not needed for computing d with self.assertRaisesRegex( ValueError, "Found unvisited input tensors that are disconnected" ): functional_utils.find_nodes_by_inputs_and_outputs( [input1, input2, input3], d ) with self.assertRaisesRegex( ValueError, "Found unvisited input tensors that are disconnected" ): functional_utils.find_nodes_by_inputs_and_outputs( [a, b, input3, unconnected_input], [e, d, c] ) def test_build_model_from_intermediate_tensor(self): batch_size = 4 inputs = input_layer_lib.Input(shape=(8,)) layer1 = layers.Dense(32) layer2 = layers.Dense(16) x = layer1(inputs) y = layer2(x) model = models.Model(x, y) # Make sure a new node is attached to layer2, which mimic y = layer2(x) self.assertLen(layer2.inbound_nodes, 2) self.assertIsInstance(model, models.Model) # The model only contains 1 dense layer and 1 input layer. self.assertLen(model.layers, 2) self.assertIs(model.layers[1], layer2) model.compile("rmsprop", "mse") model.fit( np.random.randn(batch_size, 32), np.random.randn(batch_size, 16) ) # Also make sure the original inputs and y can still be used to build # model new_model = models.Model(inputs, y) # Make sure no new node is attached to layer2 self.assertLen(layer2.inbound_nodes, 2) self.assertLen(new_model.layers, 3) self.assertIs(new_model.layers[1], layer1) self.assertIs(new_model.layers[2], layer2) # Test for model saving with self.subTest("savedmodel"): output_path = os.path.join( self.get_temp_dir(), "tf_keras_saved_model" ) model.save(output_path, save_format="tf") loaded_model = models.load_model(output_path) self.assertEqual(model.summary(), loaded_model.summary()) with self.subTest("keras_v3"): if not tf.__internal__.tf2.enabled(): self.skipTest( "TF2 must be enabled to use the new `.keras` saving." ) output_path = os.path.join( self.get_temp_dir(), "tf_keras_v3_model.keras" ) model.save(output_path, save_format="keras_v3") loaded_model = models.load_model(output_path) self.assertEqual(model.summary(), loaded_model.summary()) def test_build_model_from_intermediate_tensor_with_complicated_model(self): # The topology is like below: # input1 -> dense1 -> a # + -> c - + --> d - + --> output # input2 -> dense1 -> b -------^ ^ # input3 -> dense2 -> e -----------------| batch_size = 8 input1 = input_layer_lib.Input((2,)) input2 = input_layer_lib.Input((2,)) input3 = input_layer_lib.Input((8,)) dense1 = layers.Dense(8, name="dense1") dense2 = layers.Dense(8, name="dense2") # dense1 are shared between input1 and input2 a = dense1(input1) b = dense1(input2) c = layers.Add()([a, b]) # d has a residual connection from b. d = layers.Add()([b, c]) e = dense2(input3) output = layers.Add()([d, e]) # We skip the input2 here and use b instead. model = models.Model([input1, b, input3], output) # Make sure we have 8 layers, 3 for inputs, 2 for dense and 3 for Add. # Note that dense1 is still in use by input1. self.assertLen(model.layers, 8) # Since the layers are not ordered, let's check class of the layers to # make sure it match the expectation. class_count = collections.Counter([l.__class__ for l in model.layers]) self.assertEqual(class_count[input_layer_lib.InputLayer], 3) self.assertEqual(class_count[layers.Dense], 2) self.assertEqual(class_count[layers.Add], 3) model.compile("rmsprop", "mse") model.fit( [ np.random.randn(batch_size, 2), np.random.randn(batch_size, 8), # The shape of b is (batch, 8) np.random.randn(batch_size, 8), ], np.random.randn(batch_size, 8), ) model2 = models.Model([a, b], d) # 2 input layers and 2 Add layer. self.assertLen(model2.layers, 4) class_count = collections.Counter([l.__class__ for l in model2.layers]) self.assertEqual(class_count[input_layer_lib.InputLayer], 2) self.assertEqual(class_count[layers.Add], 2) model2.compile("rmsprop", "mse") model2.fit( [np.random.randn(batch_size, 8), np.random.randn(batch_size, 8)], np.random.randn(batch_size, 8), ) with self.subTest("savedmodel"): output_path = os.path.join( self.get_temp_dir(), "tf_keras_saved_model" ) model.save(output_path, save_format="tf") loaded_model = models.load_model(output_path) self.assertEqual(model.summary(), loaded_model.summary()) with self.subTest("keras_v3"): if not tf.__internal__.tf2.enabled(): self.skipTest( "TF2 must be enabled to use the new `.keras` saving." ) output_path = os.path.join( self.get_temp_dir(), "tf_keras_v3_model.keras" ) model.save(output_path, save_format="keras_v3") loaded_model = models.load_model(output_path) self.assertEqual(model.summary(), loaded_model.summary()) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/engine/functional_utils_test.py/0
{ "file_path": "tf-keras/tf_keras/engine/functional_utils_test.py", "repo_id": "tf-keras", "token_count": 4728 }
176
# Copyright 2018 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. # ============================================================================== """Part of the TF-Keras training engine related to plain array data.""" import functools import numpy as np import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras import callbacks as cbks from tf_keras.distribute import distributed_training_utils_v1 from tf_keras.engine import training_utils_v1 from tf_keras.utils import io_utils from tf_keras.utils.generic_utils import make_batches from tf_keras.utils.generic_utils import slice_arrays from tf_keras.utils.mode_keys import ModeKeys # isort: off from tensorflow.python.platform import tf_logging as logging try: from scipy.sparse import issparse except ImportError: issparse = None def model_iteration( model, inputs, targets=None, sample_weights=None, batch_size=None, epochs=1, verbose=1, callbacks=None, val_inputs=None, val_targets=None, val_sample_weights=None, shuffle=True, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, mode=ModeKeys.TRAIN, validation_in_fit=False, prepared_feed_values_from_dataset=False, steps_name="steps", **kwargs, ): """Loop function for arrays of data with modes TRAIN/TEST/PREDICT. Args: model: TF-Keras Model instance. inputs: Either a list or dictionary of arrays, or a dataset instance. targets: List/dictionary of input arrays. sample_weights: Optional list of sample weight arrays. batch_size: Integer batch size or None if unknown. epochs: Number of times to iterate over the data verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of callbacks to be called during training val_inputs: Either a list or dictionary of arrays, or a dataset instance. val_targets: List/dictionary of target arrays. val_sample_weights: Optional list of sample weight arrays. shuffle: Whether to shuffle the data at the beginning of each epoch concatenation of list the display names of the outputs of `f` and the list of display names of the outputs of `f_val`. initial_epoch: Epoch at which to start training (useful for resuming a previous training run) steps_per_epoch: Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. Ignored with the default value of `None`. validation_steps: Number of steps to run validation for (only if doing validation from data tensors). Ignored with the default value of `None`. validation_freq: Only relevant if validation data is provided. Integer or `collections.abc.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. validation_in_fit: if true, then this method is invoked from within training iteration (for validation). In the case where `val_inputs` is a dataset, this flag indicates that its iterator and feed values are already created so should properly reuse resources. prepared_feed_values_from_dataset: if True, `inputs` is a list of feed tensors returned from `_prepare_feed_values` call on the validation dataset, so do not call it again on `inputs`. Should only be used for inline validation (i.e., only if `validation_in_fit` is also True). steps_name: The string name of the steps argument, either `steps`, `validation_steps`, or `steps_per_epoch`. Only used for error message formatting. **kwargs: Additional arguments for backwards compatibility. Returns: - In TRAIN mode: `History` object. - In TEST mode: Evaluation metrics. - In PREDICT mode: Outputs of the Model called on inputs. Raises: ValueError: in case of invalid arguments. """ # Backwards compatibility. if "steps" in kwargs: steps_per_epoch = kwargs.pop("steps") if kwargs: raise TypeError(f"Unknown arguments: {kwargs}") # In case we were passed a dataset, we extract symbolic tensors from it. reset_dataset_after_each_epoch = False input_iterator = None is_dataset = isinstance( inputs, (tf.compat.v1.data.Dataset, tf.data.Dataset) ) # TODO(fchollet): consider moving `steps_per_epoch` inference to # _standardize_user_data and set reset_dataset_after_each_epoch as an # attribute on the dataset instance. if is_dataset: if steps_per_epoch is None: reset_dataset_after_each_epoch = True steps_per_epoch = training_utils_v1.infer_steps_for_dataset( model, inputs, steps_per_epoch, epochs=epochs, steps_name=steps_name, ) input_iterator = _get_iterator(inputs, model._distribution_strategy) # Enter tf.distribute.Strategy scope. if model._distribution_strategy: scope = distributed_training_utils_v1.distributed_scope( strategy=model._distribution_strategy, learning_phase=(1 if mode == ModeKeys.TRAIN else 0), ) scope.__enter__() use_steps = is_dataset or steps_per_epoch is not None do_validation = val_inputs is not None # Prepare input data. inputs = input_iterator or inputs if validation_in_fit and prepared_feed_values_from_dataset: # When invoking validation in training loop, avoid creating iterator and # list of feed values for the same validation dataset multiple times # (which essentially would call `iterator.get_next()` that slows down # execution and leads to OOM errors eventually. ins = inputs else: ins = _prepare_feed_values(model, inputs, targets, sample_weights, mode) # `ins` is a function when a distribute strategy is used in Eager mode. # In that case `is_dataset` is True. The code branches that have # requirements about the type of `ins` do not trigger in the distributed # case. if not is_dataset: num_samples_or_steps = _get_num_samples_or_steps( ins, batch_size, steps_per_epoch ) else: num_samples_or_steps = steps_per_epoch # Update sample_weight_mode of the model if sample_weights is specified by # the user. We need to call this function after we have a handle on the # inputs (both numpy arrays and datasets) in order to determine if the user # has specified sample_weights. _update_sample_weight_mode(model, mode, ins) # Get step function and loop type. As part of building the execution # function we recompile the metrics based on the updated # sample_weight_mode value. f = _make_execution_function(model, mode) # Prepare validation data. Hold references to the iterator and the input # list to properly reinitialize and reuse in multiple validation passes. val_iterator = None if isinstance(val_inputs, (tf.compat.v1.data.Dataset, tf.data.Dataset)): if validation_steps is None: # Because we pass an iterator feed instead of a Dataset to the eval # model_iteration() call, it will not trigger the dataset-input path # that determines the number of steps required. To avoid this issue, # set validation_steps here if validation_steps is None. validation_steps = training_utils_v1.infer_steps_for_dataset( model, val_inputs, validation_steps, epochs=epochs, steps_name="validation_steps", ) val_iterator = _get_iterator(val_inputs, model._distribution_strategy) val_inputs = _prepare_feed_values( model, val_iterator, val_targets, val_sample_weights, ModeKeys.TEST ) # Get num steps for printing. val_samples_or_steps = validation_steps else: # Get num samples for printing. val_samples_or_steps = ( val_inputs and tf.nest.flatten(val_inputs)[0].shape[0] or None ) if mode == ModeKeys.TRAIN and verbose: _print_train_info( num_samples_or_steps, val_samples_or_steps, is_dataset ) # Configure callbacks. count_mode = "steps" if use_steps else "samples" callbacks = cbks.configure_callbacks( callbacks, model, do_validation=do_validation, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, samples=num_samples_or_steps, count_mode=count_mode, verbose=verbose, mode=mode, ) # Find beforehand arrays that need sparse-to-dense conversion. if issparse is not None and not use_steps: indices_for_conversion_to_dense = [] feed = _get_model_feed(model, mode) for i, (input_data, feed_tensor) in enumerate(zip(ins, feed)): if issparse(input_data) and not backend.is_sparse(feed_tensor): indices_for_conversion_to_dense.append(i) # Select aggregation method. if mode == ModeKeys.PREDICT: aggregator = training_utils_v1.OutputsAggregator( use_steps, num_samples=None if steps_per_epoch else num_samples_or_steps, steps=steps_per_epoch, ) else: aggregator = training_utils_v1.MetricsAggregator( use_steps, num_samples=None if steps_per_epoch else num_samples_or_steps, steps=steps_per_epoch, ) if model._compile_distribution: distributed_training_utils_v1._copy_weights_to_distributed_model( model, mode ) callbacks.model.stop_training = False callbacks._call_begin_hook(mode) initial_epoch = model._maybe_load_initial_epoch_from_ckpt( initial_epoch, mode ) for epoch in range(initial_epoch, epochs): if callbacks.model.stop_training: break # Setup work for each epoch epoch_logs = {} if mode != ModeKeys.PREDICT: # Collecting and resetting metrics has non-zero cost and will # needlessly slow down model.predict. model.reset_metrics() if mode == ModeKeys.TRAIN: callbacks.on_epoch_begin(epoch, epoch_logs) if use_steps: # Step-wise loop. if steps_per_epoch is None: # Loop over dataset until `OutOfRangeError` is raised. target_steps = np.inf else: # Loop over dataset for the specified number of steps. target_steps = steps_per_epoch step = 0 while step < target_steps: batch_logs = {"batch": step, "size": 1} callbacks._call_batch_hook(mode, "begin", step, batch_logs) # Get outputs. try: # `ins` can be callable in tf.distribute.Strategy + eager # case. if not callable(ins) or ( model._distribution_strategy and not distributed_training_utils_v1.is_distributing_by_cloning( # noqa: E501 model ) ): actual_inputs = ins else: actual_inputs = ins() batch_outs = f(actual_inputs) except tf.errors.OutOfRangeError: if is_dataset: # The dataset passed by the user ran out of batches. # Now we know the cardinality of the dataset. If # steps_per_epoch was specified, then running out of # data is unexpected, so we stop training and inform the # user. if steps_per_epoch: callbacks.model.stop_training = True logging.warning( "Your dataset ran out of data; interrupting " "training. Make sure that your dataset can " "generate at least `%s * epochs` batches (in " "this case, %d batches). You may need to use " "the repeat() function when building your " "dataset." % (steps_name, steps_per_epoch * epochs) ) elif step > 0: steps_per_epoch = step aggregator.steps = steps_per_epoch else: # We ran out of batches while the user passed an # iterator (legacy). callbacks.model.stop_training = True logging.warning( "Your dataset iterator ran out of data; " "interrupting training. Make sure that your " "iterator can generate at least `%s * epochs` " "batches (in this case, %d batches). You may need " "to use the repeat() function when building your " "dataset." % (steps_name, steps_per_epoch * epochs) ) break if not isinstance(batch_outs, list): batch_outs = [batch_outs] if model._distribution_strategy: batch_outs = distributed_training_utils_v1._per_replica_aggregate_batch( # noqa: E501 model._distribution_strategy, batch_outs, model, mode ) # Aggregate results. if step == 0: aggregator.create(batch_outs) aggregator.aggregate(batch_outs) # Callbacks batch end. batch_logs = callbacks.make_logs( model, batch_logs, batch_outs, mode ) callbacks._call_batch_hook(mode, "end", step, batch_logs) step += 1 if callbacks.model.stop_training: break else: # Sample-wise loop. index_array = np.arange(num_samples_or_steps) if shuffle == "batch": index_array = training_utils_v1.batch_shuffle( index_array, batch_size ) elif shuffle: np.random.shuffle(index_array) batches = make_batches(num_samples_or_steps, batch_size) for batch_index, (batch_start, batch_end) in enumerate(batches): batch_ids = index_array[batch_start:batch_end] # Slice into a batch. if len(batches) == 1: # If we only have one batch, do not slice. This takes care # of composite tensors in non-Dataset modes; we currently # don't support slicing them. # TODO(b/133517906): Add slicing support. ins_batch = ins else: try: if ins and isinstance(ins[-1], int): # Do not slice the training phase flag. ins_batch = slice_arrays(ins[:-1], batch_ids) + [ ins[-1] ] else: ins_batch = slice_arrays(ins, batch_ids) except TypeError: raise TypeError( "TypeError while preparing batch. " "If using HDF5 input data, " 'pass shuffle="batch".' ) # Sparse to dense conversion. if issparse is not None: for i in indices_for_conversion_to_dense: ins_batch[i] = ins_batch[i].toarray() # Callbacks batch_begin. batch_logs = {"batch": batch_index, "size": len(batch_ids)} callbacks._call_batch_hook( mode, "begin", batch_index, batch_logs ) # Get outputs. batch_outs = f(ins_batch) if not isinstance(batch_outs, list): batch_outs = [batch_outs] # Aggregate results. if batch_index == 0: aggregator.create(batch_outs) aggregator.aggregate(batch_outs, batch_start, batch_end) # Callbacks batch end. batch_logs = callbacks.make_logs( model, batch_logs, batch_outs, mode ) callbacks._call_batch_hook(mode, "end", batch_index, batch_logs) if callbacks.model.stop_training: break aggregator.finalize() results = aggregator.results epoch_logs = callbacks.make_logs(model, epoch_logs, results, mode) if len(results) == 1: results = results[0] # Run the test loop every `validation_freq` epochs during training. if ( do_validation and training_utils_v1.should_run_validation(validation_freq, epoch) and not callbacks.model.stop_training ): if model._compile_distribution: # Since we create a new clone from the original model we need to # copy the weights back to the original model before we can run # validation. distributed_training_utils_v1._copy_weights_to_original_model( model, ModeKeys.TRAIN ) val_results = model_iteration( model, val_inputs, targets=val_targets, sample_weights=val_sample_weights, batch_size=batch_size, steps_per_epoch=validation_steps, callbacks=callbacks, verbose=0, mode=ModeKeys.TEST, validation_in_fit=True, prepared_feed_values_from_dataset=(val_iterator is not None), steps_name="validation_steps", ) if not isinstance(val_results, list): val_results = [val_results] epoch_logs = callbacks.make_logs( model, epoch_logs, val_results, mode, prefix="val_" ) if val_iterator and epoch < epochs - 1: _reinitialize_iterator( val_iterator, model._distribution_strategy ) if mode == ModeKeys.TRAIN: # Epochs only apply to `fit`. callbacks.on_epoch_end(epoch, epoch_logs) # Reinitialize dataset iterator for the next epoch. if reset_dataset_after_each_epoch and epoch < epochs - 1: _reinitialize_iterator(input_iterator, model._distribution_strategy) model._successful_loop_finish = True callbacks._call_end_hook(mode) if model._distribution_strategy: if model._compile_distribution: # TODO(priyag, psv): Copy back metrics to the original model as # well? distributed_training_utils_v1._copy_weights_to_original_model( model, mode ) scope.__exit__(None, None, None) if mode == ModeKeys.TRAIN: return model.history return results def _get_model_feed(model, mode): if mode == ModeKeys.PREDICT: feed = model._feed_inputs else: feed = ( model._feed_inputs + model._feed_targets + model._feed_sample_weights ) return feed def _print_train_info(num_samples_or_steps, val_samples_or_steps, is_dataset): increment = "steps" if is_dataset else "samples" msg = f"Train on {num_samples_or_steps} {increment}" if val_samples_or_steps: msg += f", validate on {val_samples_or_steps} {increment}" io_utils.print_msg(msg) def _get_num_samples_or_steps(ins, batch_size, steps_per_epoch): """Returns total number of samples when training in batch mode or steps.""" if steps_per_epoch: return steps_per_epoch return training_utils_v1.check_num_samples( ins, batch_size, steps_per_epoch, "steps_per_epoch" ) def _prepare_feed_values(model, inputs, targets, sample_weights, mode): """Prepare feed values to the model execution function. Args: model: Model to prepare feed values for. inputs: List or dict of model inputs. targets: Optional list of model targets. sample_weights: Optional list of sample weight arrays. mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. Returns: Feed values for the model in the given mode. """ if model._distribution_strategy: if isinstance(inputs, (tf.compat.v1.data.Dataset, tf.data.Dataset)): inputs = distributed_training_utils_v1.get_iterator( inputs, model._distribution_strategy ) def get_distributed_inputs(): return distributed_training_utils_v1._prepare_feed_values( model, inputs, targets, sample_weights, mode ) # In the eager case, we want to call the input method per step, so # return a lambda from here that can be called. Note that this is # applicable only in Distribution Strategy case as it follows the same # code path for both eager and graph modes. # TODO(priyag,omalleyt): Either we should move the training DS with # IteratorBase to use training_generator code path, or figure out how to # set a symbolic Iterator out of a Dataset when in eager mode. if tf.executing_eagerly(): return get_distributed_inputs else: return get_distributed_inputs() if isinstance( inputs, ( tf.compat.v1.data.Dataset, tf.data.Dataset, tf.compat.v1.data.Iterator, ), ): inputs, targets, sample_weights = model._standardize_user_data( inputs, extract_tensors_from_dataset=True ) inputs = training_utils_v1.ModelInputs(inputs).as_list() targets = list(targets or []) sample_weights = list(sample_weights or []) ins = inputs + targets + sample_weights if mode == ModeKeys.TRAIN and not isinstance( backend.symbolic_learning_phase(), int ): ins += [True] # Add learning phase value. return ins def _get_iterator(inputs, distribution_strategy=None): if distribution_strategy: return distributed_training_utils_v1.get_iterator( inputs, distribution_strategy ) return training_utils_v1.get_iterator(inputs) def _reinitialize_iterator(iterator, distribution_strategy=None): if distribution_strategy: distributed_training_utils_v1.initialize_iterator( iterator, distribution_strategy ) else: training_utils_v1.initialize_iterator(iterator) def _make_execution_function(model, mode): """Makes function to run one step of model execution.""" if model._distribution_strategy: return distributed_training_utils_v1._make_execution_function( model, mode ) return model._make_execution_function(mode) def _update_sample_weight_mode(model, mode, inputs): """Updates the sample_weight_mode of a given model.""" # Add a quick return to prevent us from calling model._feed_targets that # accesses certain model properties that may not be set in the `PREDICT` # mode. if mode == ModeKeys.PREDICT: return sample_weights = None # `inputs` is the model's inputs + targets + sample_weights + # learning phase placeholder if specified. To update the sample_weight_mode # we need to determine if the user has passed sample weights as part of the # input. if not callable(inputs): sample_weights = inputs[ len(model._feed_inputs) + len(model._feed_targets) : ] has_learning_phase_pl = mode == ModeKeys.TRAIN and not isinstance( backend.symbolic_learning_phase(), int ) if has_learning_phase_pl: sample_weights = sample_weights[:-1] model._update_sample_weight_modes(sample_weights=sample_weights) # Call the DistributionStrategy specific function to update the # sample_weight_mode on the model. if model._distribution_strategy: distributed_training_utils_v1._update_sample_weight_modes( model, mode, sample_weights ) # For backwards compatibility for internal users of these loops. fit_loop = functools.partial(model_iteration, mode=ModeKeys.TRAIN) test_loop = functools.partial( model_iteration, mode=ModeKeys.TEST, shuffle=False ) predict_loop = functools.partial( model_iteration, mode=ModeKeys.PREDICT, shuffle=False ) class ArrayLikeTrainingLoop(training_utils_v1.TrainingLoop): """TrainingLoop that handle inputs like array. This is the default handler for most of the input data types, includes symbolic tensors or Numpy array-like, Datasets and iterators in graph mode (since they generate symbolic tensors). This Function is used to handle model with `run_eagerly` = False. """ def fit( self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, **kwargs, ): batch_size = model._validate_or_infer_batch_size( batch_size, steps_per_epoch, x ) x, y, sample_weights = model._standardize_user_data( x, y, sample_weight=sample_weight, class_weight=class_weight, batch_size=batch_size, check_steps=True, steps_name="steps_per_epoch", steps=steps_per_epoch, validation_split=validation_split, shuffle=shuffle, ) if validation_data: val_x, val_y, val_sample_weights = model._prepare_validation_data( validation_data, batch_size, validation_steps ) elif validation_split and 0.0 < validation_split < 1.0: ( x, y, sample_weights, val_x, val_y, val_sample_weights, ) = training_utils_v1.split_training_and_validation_data( x, y, sample_weights, validation_split ) else: if validation_steps: raise ValueError( "`validation_steps` should not be specified if " "`validation_data` is None." ) val_x, val_y, val_sample_weights = None, None, None return fit_loop( model, inputs=x, targets=y, sample_weights=sample_weights, batch_size=batch_size, epochs=epochs, verbose=verbose, callbacks=callbacks, val_inputs=val_x, val_targets=val_y, val_sample_weights=val_sample_weights, shuffle=shuffle, initial_epoch=initial_epoch, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, validation_freq=validation_freq, steps_name="steps_per_epoch", ) def evaluate( self, model, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, **kwargs, ): batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) x, y, sample_weights = model._standardize_user_data( x, y, sample_weight=sample_weight, batch_size=batch_size, check_steps=True, steps_name="steps", steps=steps, ) return test_loop( model, inputs=x, targets=y, sample_weights=sample_weights, batch_size=batch_size, verbose=verbose, steps=steps, callbacks=callbacks, ) def predict( self, model, x, batch_size=None, verbose=0, steps=None, callbacks=None, **kwargs, ): batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) x, _, _ = model._standardize_user_data( x, check_steps=True, steps_name="steps", steps=steps ) return predict_loop( model, x, batch_size=batch_size, verbose=verbose, steps=steps, callbacks=callbacks, )
tf-keras/tf_keras/engine/training_arrays_v1.py/0
{ "file_path": "tf-keras/tf_keras/engine/training_arrays_v1.py", "repo_id": "tf-keras", "token_count": 14390 }
177
# Description: # Contains the TF-Keras save model API (internal TensorFlow version). # Placeholder: load unaliased py_library load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test") package( # copybara:uncomment default_applicable_licenses = ["//tf_keras:license"], # TODO(scottzhu): Remove non-keras deps from TF. default_visibility = [ "//tf_keras:friends", ], licenses = ["notice"], ) py_library( name = "export_lib", srcs = [ "export_lib.py", ], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) tf_py_test( name = "export_lib_test", size = "medium", srcs = ["export_lib_test.py"], python_version = "PY3", deps = [ ":export_lib", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], )
tf-keras/tf_keras/export/BUILD/0
{ "file_path": "tf-keras/tf_keras/export/BUILD", "repo_id": "tf-keras", "token_count": 436 }
178
# Copyright 2020 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. # ============================================================================== """Keras initializers.""" import math import warnings import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras.dtensor import utils from tf_keras.saving import serialization_lib # isort: off from tensorflow.python.util.tf_export import keras_export _PARTITION_SHAPE = "partition_shape" _PARTITION_OFFSET = "partition_offset" _LAYOUT = "layout" _ALLOWED_INITIALIZER_KWARGS = [_PARTITION_SHAPE, _PARTITION_OFFSET, _LAYOUT] @keras_export("keras.initializers.Initializer") class Initializer: """Initializer base class: all TF-Keras initializers inherit from this class. Initializers should implement a `__call__()` method with the following signature: ```python def __call__(self, shape, dtype=None, **kwargs): # returns a tensor of shape `shape` and dtype `dtype` # containing values drawn from a distribution of your choice. return tf.random.uniform(shape=shape, dtype=dtype) ``` Optionally, you an also implement the method `get_config()` and the class method `from_config()` in order to support serialization -- just like with any TF-Keras object. Here's a simple example: a random normal initializer. ```python class ExampleRandomNormal(Initializer): def __init__(self, mean, stddev): self.mean = mean self.stddev = stddev def __call__(self, shape, dtype=None, **kwargs): return tf.random.normal( shape, mean=self.mean, stddev=self.stddev, dtype=dtype ) def get_config(self): # To support serialization return {"mean": self.mean, "stddev": self.stddev} ``` Note that we don't have to implement `from_config()` in the example above since the constructor arguments of the class the keys in the config returned by `get_config` are the same. In this case, the default `from_config()` works fine. """ def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. **kwargs: Additional keyword arguments. """ raise NotImplementedError( "Initializer subclasses must implement the `__call__()` method." ) def get_config(self): """Returns the initializer's configuration as a JSON-serializable dict. Returns: A JSON-serializable Python dict. """ return {} @classmethod def from_config(cls, config): """Instantiates an initializer from a configuration dictionary. Example: ```python initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) ``` Args: config: A Python dictionary, the output of `get_config()`. Returns: An `Initializer` instance. """ config.pop("dtype", None) return cls(**config) def _warn_reuse(self): if getattr(self, "_used", False): if getattr(self, "seed", None) is None: warnings.warn( f"The initializer {self.__class__.__name__} is unseeded " "and being called multiple times, which will return " "identical values each time (even if the initializer is " "unseeded). Please update your code to provide a seed to " "the initializer, or avoid using the same initializer " "instance more than once." ) else: self._used = True @keras_export("keras.initializers.Zeros", "keras.initializers.zeros", v1=[]) class Zeros(Initializer): """Initializer that generates tensors initialized to 0. Also available via the shortcut function `tf.keras.initializers.zeros`. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.Zeros() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.Zeros() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) """ def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. If not specified, `keras.backend.floatx()` is used, which defaults to `float32` unless you configured it otherwise (via `keras.backend.set_floatx(float_dtype)`). **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _get_dtype(dtype) if not dtype.is_numpy_compatible or dtype == tf.string: raise ValueError(f"Expected numeric or boolean dtype, got {dtype}.") if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] layout = kwargs.pop("layout", None) if layout: return utils.call_with_layout( tf.zeros, layout, shape=shape, dtype=dtype ) return tf.zeros(shape, dtype) @keras_export("keras.initializers.Ones", "keras.initializers.ones", v1=[]) class Ones(Initializer): """Initializer that generates tensors initialized to 1. Also available via the shortcut function `tf.keras.initializers.ones`. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.Ones() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.Ones() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) """ def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. If not specified, `keras.backend.floatx()` is used, which defaults to `float32` unless you configured it otherwise (via `keras.backend.set_floatx(float_dtype)`). **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _get_dtype(dtype) if not dtype.is_numpy_compatible or dtype == tf.string: raise ValueError(f"Expected numeric or boolean dtype, got {dtype}.") if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] layout = kwargs.pop("layout", None) if layout: return utils.call_with_layout( tf.ones, layout, shape=shape, dtype=dtype ) return tf.ones(shape, dtype) @keras_export( "keras.initializers.Constant", "keras.initializers.constant", v1=[] ) class Constant(Initializer): """Initializer that generates tensors with constant values. Also available via the shortcut function `tf.keras.initializers.constant`. Only scalar values are allowed. The constant value provided must be convertible to the dtype requested when calling the initializer. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.Constant(3.) >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.Constant(3.) >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: value: A Python scalar. """ def __init__(self, value=0): self.value = value def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized to `self.value`. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. If not specified, `keras.backend.floatx()` is used, which defaults to `float32` unless you configured it otherwise (via `keras.backend.set_floatx(float_dtype)`). **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _get_dtype(dtype) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] layout = kwargs.pop("layout", None) if layout: return utils.call_with_layout( tf.constant, layout, self.value, shape=shape, dtype=dtype ) return tf.constant(self.value, dtype=_get_dtype(dtype), shape=shape) def get_config(self): return {"value": self.value} @classmethod def from_config(cls, config): config.pop("dtype", None) if "value" in config: if isinstance(config["value"], dict): config["value"] = serialization_lib.deserialize_keras_object( config["value"] ) return cls(**config) @keras_export( "keras.initializers.RandomUniform", "keras.initializers.random_uniform", v1=[], ) class RandomUniform(Initializer): """Initializer that generates tensors with a uniform distribution. Also available via the shortcut function `tf.keras.initializers.random_uniform`. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.) >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.) >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: minval: A python scalar or a scalar tensor. Lower bound of the range of random values to generate (inclusive). maxval: A python scalar or a scalar tensor. Upper bound of the range of random values to generate (exclusive). seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will produce the same random values across multiple calls. """ def __init__(self, minval=-0.05, maxval=0.05, seed=None): self.minval = minval self.maxval = maxval self.seed = seed self._random_generator = backend.RandomGenerator( seed, rng_type="stateless" ) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point and integer types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`). **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _get_dtype(dtype) if not dtype.is_floating and not dtype.is_integer: raise ValueError(f"Expected float or integer dtype, got {dtype}.") if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] partition_offset = kwargs.get(_PARTITION_OFFSET, None) if partition_offset is None: # We skip the reuse warning for partitioned variable, since the same # initializer will be called multiple times for each partition. self._warn_reuse() nonce = hash(partition_offset) if partition_offset else None layout = kwargs.pop("layout", None) if layout: _ensure_keras_seeded() return utils.call_with_layout( self._random_generator.random_uniform, layout, shape, self.minval, self.maxval, dtype, nonce, ) return self._random_generator.random_uniform( shape, self.minval, self.maxval, dtype, nonce ) def get_config(self): return {"minval": self.minval, "maxval": self.maxval, "seed": self.seed} @keras_export( "keras.initializers.RandomNormal", "keras.initializers.random_normal", v1=[] ) class RandomNormal(Initializer): """Initializer that generates tensors with a normal distribution. Also available via the shortcut function `tf.keras.initializers.random_normal`. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.) >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.) >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: mean: a python scalar or a scalar tensor. Mean of the random values to generate. stddev: a python scalar or a scalar tensor. Standard deviation of the random values to generate. seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will produce the same random values across multiple calls. """ def __init__(self, mean=0.0, stddev=0.05, seed=None): self.mean = mean self.stddev = stddev self.seed = seed self._random_generator = backend.RandomGenerator( seed, rng_type="stateless" ) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized to random normal values. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`) **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _assert_float_dtype(_get_dtype(dtype)) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] partition_offset = kwargs.get(_PARTITION_OFFSET, None) if partition_offset is None: # We skip the reuse warning for partitioned variable, since the same # initializer will be called multiple times for each partition. self._warn_reuse() nonce = hash(partition_offset) if partition_offset else None layout = kwargs.pop("layout", None) if layout: _ensure_keras_seeded() return utils.call_with_layout( self._random_generator.random_normal, layout, shape, self.mean, self.stddev, dtype, nonce, ) return self._random_generator.random_normal( shape, self.mean, self.stddev, dtype, nonce ) def get_config(self): return {"mean": self.mean, "stddev": self.stddev, "seed": self.seed} @keras_export( "keras.initializers.TruncatedNormal", "keras.initializers.truncated_normal", v1=[], ) class TruncatedNormal(Initializer): """Initializer that generates a truncated normal distribution. Also available via the shortcut function `tf.keras.initializers.truncated_normal`. The values generated are similar to values from a `tf.keras.initializers.RandomNormal` initializer except that values more than two standard deviations from the mean are discarded and re-drawn. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.) >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.) >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: mean: a python scalar or a scalar tensor. Mean of the random values to generate. stddev: a python scalar or a scalar tensor. Standard deviation of the random values to generate before truncation. seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will produce the same random values across multiple calls. """ def __init__(self, mean=0.0, stddev=0.05, seed=None): self.mean = mean self.stddev = stddev self.seed = seed self._random_generator = backend.RandomGenerator( seed, rng_type="stateless" ) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor initialized to random normal values (truncated). Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`) **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _assert_float_dtype(_get_dtype(dtype)) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] partition_offset = kwargs.get(_PARTITION_OFFSET, None) if partition_offset is None: # We skip the reuse warning for partitioned variable, since the same # initializer will be called multiple times for each partition. self._warn_reuse() nonce = hash(partition_offset) if partition_offset else None layout = kwargs.pop("layout", None) if layout: # TODO(scottzhu): Remove this once the forward compat period above # is expired. self._random_generator._rng_type = ( self._random_generator.RNG_STATEFUL ) _ensure_keras_seeded() return utils.call_with_layout( self._random_generator.truncated_normal, layout, shape, self.mean, self.stddev, dtype, nonce, ) return self._random_generator.truncated_normal( shape, self.mean, self.stddev, dtype, nonce ) def get_config(self): return {"mean": self.mean, "stddev": self.stddev, "seed": self.seed} @keras_export( "keras.initializers.VarianceScaling", "keras.initializers.variance_scaling", v1=[], ) class VarianceScaling(Initializer): """Initializer that adapts its scale to the shape of its input tensors. Also available via the shortcut function `tf.keras.initializers.variance_scaling`. With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)`, where `n` is: - number of input units in the weight tensor, if `mode="fan_in"` - number of output units, if `mode="fan_out"` - average of the numbers of input and output units, if `mode="fan_avg"` With `distribution="uniform"`, samples are drawn from a uniform distribution within `[-limit, limit]`, where `limit = sqrt(3 * scale / n)`. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.VarianceScaling( ... scale=0.1, mode='fan_in', distribution='uniform') >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.VarianceScaling( ... scale=0.1, mode='fan_in', distribution='uniform') >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: scale: Scaling factor (positive float). mode: One of `"fan_in"`, `"fan_out"`, `"fan_avg"`. distribution: Random distribution to use. One of `"truncated_normal"`, `"untruncated_normal"`, or `"uniform"`. seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will produce the same random values across multiple calls. """ def __init__( self, scale=1.0, mode="fan_in", distribution="truncated_normal", seed=None, ): if scale <= 0.0: raise ValueError( f"`scale` must be positive float. Received: scale={scale}." ) allowed_modes = {"fan_in", "fan_out", "fan_avg"} if mode not in allowed_modes: raise ValueError( f"Invalid `mode` argument: {mode}. " f"Please use one of the {allowed_modes}." ) distribution = distribution.lower() # Compatibility with keras-team/keras. if distribution == "normal": distribution = "truncated_normal" allowed_distributions = { "uniform", "truncated_normal", "untruncated_normal", } if distribution not in allowed_distributions: raise ValueError( f"Invalid `distribution` argument: {distribution}." f"Allowed distributions: {allowed_distributions}." ) self.scale = scale self.mode = mode self.distribution = distribution self.seed = seed self._random_generator = backend.RandomGenerator( seed, rng_type="stateless" ) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`) **kwargs: Additional keyword arguments. """ _validate_kwargs(self.__class__.__name__, kwargs) dtype = _assert_float_dtype(_get_dtype(dtype)) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] partition_offset = kwargs.get(_PARTITION_OFFSET, None) if partition_offset is None: # We skip the reuse warning for partitioned variable, since the same # initializer will be called multiple times for each partition. self._warn_reuse() nonce = hash(partition_offset) if partition_offset else None layout = kwargs.pop("layout", None) if layout: _ensure_keras_seeded() return utils.call_with_layout( self._generate_init_val, layout, shape=shape, dtype=dtype, nonce=nonce, ) return self._generate_init_val(shape=shape, dtype=dtype, nonce=nonce) def _generate_init_val(self, shape, dtype, nonce): scale = self.scale fan_in, fan_out = _compute_fans(shape) if self.mode == "fan_in": scale /= max(1.0, fan_in) elif self.mode == "fan_out": scale /= max(1.0, fan_out) else: scale /= max(1.0, (fan_in + fan_out) / 2.0) if self.distribution == "truncated_normal": # constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., # scale=1.) stddev = math.sqrt(scale) / 0.87962566103423978 return self._random_generator.truncated_normal( shape, 0.0, stddev, dtype, nonce ) elif self.distribution == "untruncated_normal": stddev = math.sqrt(scale) return self._random_generator.random_normal( shape, 0.0, stddev, dtype, nonce ) else: limit = math.sqrt(3.0 * scale) return self._random_generator.random_uniform( shape, -limit, limit, dtype, nonce ) def get_config(self): return { "scale": self.scale, "mode": self.mode, "distribution": self.distribution, "seed": self.seed, } @keras_export( "keras.initializers.Orthogonal", "keras.initializers.orthogonal", v1=[] ) class Orthogonal(Initializer): """Initializer that generates an orthogonal matrix. Also available via the shortcut function `tf.keras.initializers.orthogonal`. If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix has fewer rows than columns then the output will have orthogonal rows. Otherwise, the output will have orthogonal columns. If the shape of the tensor to initialize is more than two-dimensional, a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])` is initialized, where `n` is the length of the shape vector. The matrix is subsequently reshaped to give a tensor of the desired shape. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.Orthogonal() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.Orthogonal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: gain: multiplicative factor to apply to the orthogonal matrix seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will produce the same random values across multiple calls. References: - [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) """ def __init__(self, gain=1.0, seed=None): self.gain = gain self.seed = seed self._random_generator = backend.RandomGenerator( seed, rng_type="stateless" ) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized to an orthogonal matrix. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`) **kwargs: Additional keyword arguments. """ _validate_kwargs( self.__class__.__name__, kwargs, support_partition=False ) dtype = _assert_float_dtype(_get_dtype(dtype)) # Check the shape if len(shape) < 2: raise ValueError( "The tensor to initialize must be " "at least two-dimensional. Received: " f"shape={shape} of rank {len(shape)}." ) self._warn_reuse() layout = kwargs.pop("layout", None) if layout: _ensure_keras_seeded() return utils.call_with_layout( self._generate_init_val, layout, shape=shape, dtype=dtype ) return self._generate_init_val(shape, dtype) def _generate_init_val(self, shape, dtype): # Flatten the input shape with the last dimension remaining # its original shape so it works for conv2d num_rows = 1 for dim in shape[:-1]: num_rows *= dim num_cols = shape[-1] flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows)) # Generate a random matrix a = self._random_generator.random_normal(flat_shape, dtype=dtype) # Compute the qr factorization q, r = tf.linalg.qr(a, full_matrices=False) # Make Q uniform d = tf.linalg.tensor_diag_part(r) q *= tf.sign(d) if num_rows < num_cols: q = tf.linalg.matrix_transpose(q) return self.gain * tf.reshape(q, shape) def get_config(self): return {"gain": self.gain, "seed": self.seed} @keras_export( "keras.initializers.Identity", "keras.initializers.identity", v1=[] ) class Identity(Initializer): """Initializer that generates the identity matrix. Also available via the shortcut function `tf.keras.initializers.identity`. Only usable for generating 2D matrices. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.Identity() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.Identity() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: gain: Multiplicative factor to apply to the identity matrix. """ def __init__(self, gain=1.0): self.gain = gain def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object initialized to a 2D identity matrix. Args: shape: Shape of the tensor. It should have exactly rank 2. dtype: Optional dtype of the tensor. Only floating point types are supported. If not specified, `tf.keras.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `tf.keras.backend.set_floatx(float_dtype)`) **kwargs: Additional keyword arguments. """ _validate_kwargs( self.__class__.__name__, kwargs, support_partition=False ) dtype = _assert_float_dtype(_get_dtype(dtype)) if len(shape) != 2: raise ValueError( "Identity matrix initializer can only be used for 2D matrices. " f"Received: shape={shape} of rank {len(shape)}." ) layout = kwargs.pop("layout", None) if layout: return utils.call_with_layout( self._generate_init_val, layout, shape=shape, dtype=dtype ) return self._generate_init_val(shape, dtype) def _generate_init_val(self, shape, dtype): initializer = tf.eye(*shape, dtype=dtype) return self.gain * initializer def get_config(self): return {"gain": self.gain} @keras_export( "keras.initializers.GlorotUniform", "keras.initializers.glorot_uniform", v1=[], ) class GlorotUniform(VarianceScaling): """The Glorot uniform initializer, also called Xavier uniform initializer. Also available via the shortcut function `tf.keras.initializers.glorot_uniform`. Draws samples from a uniform distribution within `[-limit, limit]`, where `limit = sqrt(6 / (fan_in + fan_out))` (`fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units). Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.GlorotUniform() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.GlorotUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) """ def __init__(self, seed=None): super().__init__( scale=1.0, mode="fan_avg", distribution="uniform", seed=seed ) def get_config(self): return {"seed": self.seed} @keras_export( "keras.initializers.GlorotNormal", "keras.initializers.glorot_normal", v1=[] ) class GlorotNormal(VarianceScaling): """The Glorot normal initializer, also called Xavier normal initializer. Also available via the shortcut function `tf.keras.initializers.glorot_normal`. Draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units in the weight tensor. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.GlorotNormal() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.GlorotNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) """ def __init__(self, seed=None): super().__init__( scale=1.0, mode="fan_avg", distribution="truncated_normal", seed=seed, ) def get_config(self): return {"seed": self.seed} @keras_export( "keras.initializers.LecunNormal", "keras.initializers.lecun_normal", v1=[] ) class LecunNormal(VarianceScaling): """Lecun normal initializer. Also available via the shortcut function `tf.keras.initializers.lecun_normal`. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(1 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.LecunNormal() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.LecunNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [Klambauer et al., 2017](https://arxiv.org/abs/1706.02515) """ def __init__(self, seed=None): super().__init__( scale=1.0, mode="fan_in", distribution="truncated_normal", seed=seed ) def get_config(self): return {"seed": self.seed} @keras_export( "keras.initializers.LecunUniform", "keras.initializers.lecun_uniform", v1=[] ) class LecunUniform(VarianceScaling): """Lecun uniform initializer. Also available via the shortcut function `tf.keras.initializers.lecun_uniform`. Draws samples from a uniform distribution within `[-limit, limit]`, where `limit = sqrt(3 / fan_in)` (`fan_in` is the number of input units in the weight tensor). Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.LecunUniform() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.LecunUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [Klambauer et al., 2017](https://arxiv.org/abs/1706.02515) """ def __init__(self, seed=None): super().__init__( scale=1.0, mode="fan_in", distribution="uniform", seed=seed ) def get_config(self): return {"seed": self.seed} @keras_export( "keras.initializers.HeNormal", "keras.initializers.he_normal", v1=[] ) class HeNormal(VarianceScaling): """He normal initializer. Also available via the shortcut function `tf.keras.initializers.he_normal`. It draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.HeNormal() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.HeNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [He et al., 2015](https://arxiv.org/abs/1502.01852) """ def __init__(self, seed=None): super().__init__( scale=2.0, mode="fan_in", distribution="truncated_normal", seed=seed ) def get_config(self): return {"seed": self.seed} @keras_export( "keras.initializers.HeUniform", "keras.initializers.he_uniform", v1=[] ) class HeUniform(VarianceScaling): """He uniform variance scaling initializer. Also available via the shortcut function `tf.keras.initializers.he_uniform`. Draws samples from a uniform distribution within `[-limit, limit]`, where `limit = sqrt(6 / fan_in)` (`fan_in` is the number of input units in the weight tensor). Examples: >>> # Standalone usage: >>> initializer = tf.keras.initializers.HeUniform() >>> values = initializer(shape=(2, 2)) >>> # Usage in a TF-Keras layer: >>> initializer = tf.keras.initializers.HeUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to make the behavior of the initializer deterministic. Note that a seeded initializer will not produce the same random values across multiple calls, but multiple initializers will produce the same sequence when constructed with the same seed value. References: - [He et al., 2015](https://arxiv.org/abs/1502.01852) """ def __init__(self, seed=None): super().__init__( scale=2.0, mode="fan_in", distribution="uniform", seed=seed ) def get_config(self): return {"seed": self.seed} def _get_dtype(dtype): if dtype is None: dtype = backend.floatx() return tf.as_dtype(dtype) def _assert_float_dtype(dtype): """Validate and return floating point type based on `dtype`. `dtype` must be a floating point type. Args: dtype: The data type to validate. Returns: Validated type. Raises: ValueError: if `dtype` is not a floating point type. """ dtype = tf.as_dtype(dtype) if not dtype.is_floating: raise ValueError(f"Expected floating point type, got {dtype}.") return dtype def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of integer scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) == 1: fan_in = fan_out = shape[0] elif len(shape) == 2: fan_in = shape[0] fan_out = shape[1] else: # Assuming convolution kernels (2D, 3D, or more). # kernel shape: (..., input_depth, depth) receptive_field_size = 1 for dim in shape[:-2]: receptive_field_size *= dim fan_in = shape[-2] * receptive_field_size fan_out = shape[-1] * receptive_field_size return int(fan_in), int(fan_out) def _validate_kwargs(cls_name, kwargs, support_partition=True): invalid_kwargs = [k for k in kwargs if k not in _ALLOWED_INITIALIZER_KWARGS] if invalid_kwargs: raise TypeError( f"Unknown keyword arguments: {invalid_kwargs}. Allowed " f"keyword arguments: {_ALLOWED_INITIALIZER_KWARGS}." ) if not support_partition and ( _PARTITION_SHAPE in kwargs or _PARTITION_OFFSET in kwargs ): raise ValueError( f"{cls_name} initializer doesn't support " "partition-related arguments." ) def _ensure_keras_seeded(): """Make sure the keras.backend global seed generator is set. This is important for DTensor use case to ensure that each client are initialized with same seed for tf.random.Generator, so that the value created are in sync among all the clients. """ if not getattr(backend._SEED_GENERATOR, "generator", None): raise ValueError( "When using DTensor APIs, you need to set the global seed " "before using any TF-Keras initializers. Please make sure " "to call `tf.keras.utils.set_random_seed()` in your code." )
tf-keras/tf_keras/initializers/initializers.py/0
{ "file_path": "tf-keras/tf_keras/initializers/initializers.py", "repo_id": "tf-keras", "token_count": 17617 }
179
# Copyright 2020 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. # ============================================================================== import numpy as np import tensorflow.compat.v1 as tf tf.disable_eager_execution() class KerasNetworkTFRNNs(tf.keras.Model): def __init__(self, name=None): super().__init__(name=name) self._cell = tf.nn.rnn_cell.MultiRNNCell( [tf.nn.rnn_cell.LSTMCell(1) for _ in range(2)] ) def call(self, inputs): return self._cell(inputs, self._cell.get_initial_state(inputs)) class KerasNetworkKerasRNNs(tf.keras.Model): def __init__(self, name=None): super().__init__(name=name) self._cell = tf.keras.layers.StackedRNNCells( [tf.keras.layers.LSTMCell(1) for _ in range(2)] ) def call(self, inputs): return self._cell(inputs, self._cell.get_initial_state(inputs)) class LegacyRNNTest(tf.test.TestCase): def setUp(self): super().setUp() self._seed = 23489 np.random.seed(self._seed) def testRNNWithKerasSimpleRNNCell(self): with self.cached_session() as sess: input_shape = 10 output_shape = 5 timestep = 4 batch = 100 (x_train, y_train), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) y_train = tf.keras.utils.to_categorical(y_train) cell = tf.keras.layers.SimpleRNNCell(output_shape) inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) predict = tf.placeholder(tf.float32, shape=(None, output_shape)) outputs, state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) self.assertEqual( outputs.shape.as_list(), [None, timestep, output_shape] ) self.assertEqual(state.shape.as_list(), [None, output_shape]) loss = tf.keras.losses.categorical_crossentropy(predict, state) train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss) sess.run([tf.global_variables_initializer()]) _, outputs, state = sess.run( [train_op, outputs, state], {inputs: x_train, predict: y_train} ) self.assertEqual(len(outputs), batch) self.assertEqual(len(state), batch) def testRNNWithKerasGRUCell(self): with self.cached_session() as sess: input_shape = 10 output_shape = 5 timestep = 4 batch = 100 (x_train, y_train), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) y_train = tf.keras.utils.to_categorical(y_train) cell = tf.keras.layers.GRUCell(output_shape) inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) predict = tf.placeholder(tf.float32, shape=(None, output_shape)) outputs, state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) self.assertEqual( outputs.shape.as_list(), [None, timestep, output_shape] ) self.assertEqual(state.shape.as_list(), [None, output_shape]) loss = tf.keras.losses.categorical_crossentropy(predict, state) train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss) sess.run([tf.global_variables_initializer()]) _, outputs, state = sess.run( [train_op, outputs, state], {inputs: x_train, predict: y_train} ) self.assertEqual(len(outputs), batch) self.assertEqual(len(state), batch) def testRNNWithKerasLSTMCell(self): with self.cached_session() as sess: input_shape = 10 output_shape = 5 timestep = 4 batch = 100 (x_train, y_train), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) y_train = tf.keras.utils.to_categorical(y_train) cell = tf.keras.layers.LSTMCell(output_shape) inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) predict = tf.placeholder(tf.float32, shape=(None, output_shape)) outputs, state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) self.assertEqual( outputs.shape.as_list(), [None, timestep, output_shape] ) self.assertEqual(len(state), 2) self.assertEqual(state[0].shape.as_list(), [None, output_shape]) self.assertEqual(state[1].shape.as_list(), [None, output_shape]) loss = tf.keras.losses.categorical_crossentropy(predict, state[0]) train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss) sess.run([tf.global_variables_initializer()]) _, outputs, state = sess.run( [train_op, outputs, state], {inputs: x_train, predict: y_train} ) self.assertEqual(len(outputs), batch) self.assertEqual(len(state), 2) self.assertEqual(len(state[0]), batch) self.assertEqual(len(state[1]), batch) def testRNNWithStackKerasCell(self): with self.cached_session() as sess: input_shape = 10 output_shape = 5 timestep = 4 batch = 100 (x_train, y_train), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) y_train = tf.keras.utils.to_categorical(y_train) cell = tf.keras.layers.StackedRNNCells( [ tf.keras.layers.LSTMCell(2 * output_shape), tf.keras.layers.LSTMCell(output_shape), ] ) inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) predict = tf.placeholder(tf.float32, shape=(None, output_shape)) outputs, state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) self.assertEqual( outputs.shape.as_list(), [None, timestep, output_shape] ) self.assertEqual(len(state), 2) state = tf.nest.flatten(state) self.assertEqual(len(state), 4) self.assertEqual(state[0].shape.as_list(), [None, 2 * output_shape]) self.assertEqual(state[1].shape.as_list(), [None, 2 * output_shape]) self.assertEqual(state[2].shape.as_list(), [None, output_shape]) self.assertEqual(state[3].shape.as_list(), [None, output_shape]) loss = tf.keras.losses.categorical_crossentropy(predict, state[2]) train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss) sess.run([tf.global_variables_initializer()]) _, outputs, state = sess.run( [train_op, outputs, state], {inputs: x_train, predict: y_train} ) self.assertEqual(len(outputs), batch) self.assertEqual(len(state), 4) for s in state: self.assertEqual(len(s), batch) def testStaticRNNWithKerasSimpleRNNCell(self): with self.cached_session() as sess: input_shape = 10 output_shape = 5 timestep = 4 batch = 100 (x_train, y_train), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) x_train = np.transpose(x_train, (1, 0, 2)) y_train = tf.keras.utils.to_categorical(y_train) cell = tf.keras.layers.SimpleRNNCell(output_shape) inputs = [ tf.placeholder(tf.float32, shape=(None, input_shape)) ] * timestep predict = tf.placeholder(tf.float32, shape=(None, output_shape)) outputs, state = tf.nn.static_rnn(cell, inputs, dtype=tf.float32) self.assertEqual(len(outputs), timestep) self.assertEqual(outputs[0].shape.as_list(), [None, output_shape]) self.assertEqual(state.shape.as_list(), [None, output_shape]) loss = tf.keras.losses.categorical_crossentropy(predict, state) train_op = tf.train.GradientDescentOptimizer(0.001).minimize(loss) sess.run([tf.global_variables_initializer()]) feed_dict = {i: d for i, d in zip(inputs, x_train)} feed_dict[predict] = y_train _, outputs, state = sess.run([train_op, outputs, state], feed_dict) self.assertEqual(len(outputs), timestep) self.assertEqual(len(outputs[0]), batch) self.assertEqual(len(state), batch) def testKerasAndTFRNNLayerOutputComparison(self): input_shape = 10 output_shape = 5 timestep = 4 batch = 20 (x_train, _), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) fix_weights_generator = tf.keras.layers.SimpleRNNCell(output_shape) fix_weights_generator.build((None, input_shape)) weights = fix_weights_generator.get_weights() with self.session(graph=tf.Graph()) as sess: inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) cell = tf.keras.layers.SimpleRNNCell(output_shape) tf_out, tf_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) cell.set_weights(weights) [tf_out, tf_state] = sess.run([tf_out, tf_state], {inputs: x_train}) with self.session(graph=tf.Graph()) as sess: k_input = tf.keras.Input( shape=(timestep, input_shape), dtype=tf.float32 ) cell = tf.keras.layers.SimpleRNNCell(output_shape) layer = tf.keras.layers.RNN( cell, return_sequences=True, return_state=True ) keras_out = layer(k_input) cell.set_weights(weights) k_out, k_state = sess.run(keras_out, {k_input: x_train}) self.assertAllClose(tf_out, k_out) self.assertAllClose(tf_state, k_state) def testSimpleRNNCellAndBasicRNNCellComparison(self): input_shape = 10 output_shape = 5 timestep = 4 batch = 20 (x_train, _), _ = get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape, ) fix_weights_generator = tf.keras.layers.SimpleRNNCell(output_shape) fix_weights_generator.build((None, input_shape)) # The SimpleRNNCell contains 3 weights: kernel, recurrent_kernel, and # bias The BasicRNNCell contains 2 weight: kernel and bias, where kernel # is zipped [kernel, recurrent_kernel] in SimpleRNNCell. keras_weights = fix_weights_generator.get_weights() kernel, recurrent_kernel, bias = keras_weights tf_weights = [np.concatenate((kernel, recurrent_kernel)), bias] with self.session(graph=tf.Graph()) as sess: inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) cell = tf.keras.layers.SimpleRNNCell(output_shape) k_out, k_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) cell.set_weights(keras_weights) [k_out, k_state] = sess.run([k_out, k_state], {inputs: x_train}) with self.session(graph=tf.Graph()) as sess: inputs = tf.placeholder( tf.float32, shape=(None, timestep, input_shape) ) cell = tf.nn.rnn_cell.BasicRNNCell(output_shape) tf_out, tf_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) cell.set_weights(tf_weights) [tf_out, tf_state] = sess.run([tf_out, tf_state], {inputs: x_train}) self.assertAllClose(tf_out, k_out, atol=1e-5) self.assertAllClose(tf_state, k_state, atol=1e-5) def testRNNCellSerialization(self): for cell in [ tf.nn.rnn_cell.LSTMCell(32, use_peepholes=True, cell_clip=True), tf.nn.rnn_cell.BasicLSTMCell(32, dtype=tf.float32), tf.nn.rnn_cell.BasicRNNCell( 32, activation="relu", dtype=tf.float32 ), tf.nn.rnn_cell.GRUCell(32, dtype=tf.float32), ]: with self.cached_session(): x = tf.keras.Input((None, 5)) layer = tf.keras.layers.RNN(cell) y = layer(x) model = tf.keras.models.Model(x, y) model.compile(optimizer="rmsprop", loss="mse") # Test basic case serialization. x_np = np.random.random((6, 5, 5)) y_np = model.predict(x_np) weights = model.get_weights() config = layer.get_config() # The custom_objects is important here since rnn_cell_impl is # not visible as a TF-Keras layer, and also has a name conflict # with keras.LSTMCell and GRUCell. layer = tf.keras.layers.RNN.from_config( config, custom_objects={ "BasicRNNCell": tf.nn.rnn_cell.BasicRNNCell, "GRUCell": tf.nn.rnn_cell.GRUCell, "LSTMCell": tf.nn.rnn_cell.LSTMCell, "BasicLSTMCell": tf.nn.rnn_cell.BasicLSTMCell, }, ) y = layer(x) model = tf.keras.models.Model(x, y) model.set_weights(weights) y_np_2 = model.predict(x_np) self.assertAllClose(y_np, y_np_2, atol=1e-4) def testRNNCellActsLikeKerasRNNCellInProperScope(self): with tf.layers.experimental.keras_style_scope(): kn1 = KerasNetworkTFRNNs(name="kn1") kn2 = KerasNetworkKerasRNNs(name="kn2") z = tf.zeros((2, 3)) kn1(z) kn2(z) self.assertTrue(all("kn1" in v.name for v in kn1._cell.variables)) self.assertTrue(all("kn2" in v.name for v in kn2._cell.variables)) with tf.layers.experimental.keras_style_scope(): kn1_new = KerasNetworkTFRNNs(name="kn1_new") kn2_new = KerasNetworkKerasRNNs(name="kn2_new") kn2_new(z) # Most importantly, this doesn't fail due to variable scope reuse # issues. kn1_new(z) self.assertTrue( all("kn1_new" in v.name for v in kn1_new._cell.variables) ) self.assertTrue( all("kn2_new" in v.name for v in kn2_new._cell.variables) ) def get_test_data(train_samples, test_samples, input_shape, num_classes): num_sample = train_samples + test_samples templates = 2 * num_classes * np.random.random((num_classes,) + input_shape) y = np.random.randint(0, num_classes, size=(num_sample,)) x = np.zeros((num_sample,) + input_shape, dtype=np.float32) for i in range(num_sample): x[i] = templates[y[i]] + np.random.normal( loc=0, scale=1.0, size=input_shape ) return ( (x[:train_samples], y[:train_samples]), (x[train_samples:], y[train_samples:]), ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/integration_test/legacy_rnn_test.py/0
{ "file_path": "tf-keras/tf_keras/integration_test/legacy_rnn_test.py", "repo_id": "tf-keras", "token_count": 8486 }
180
"""Machine translation model. Adapted from https://keras.io/examples/nlp/neural_machine_translation_with_transformer/ """ import tensorflow as tf from tensorflow import keras from tf_keras.integration_test.models.input_spec import InputSpec VOCAB_SIZE = 1500 SEQUENCE_LENGTH = 20 def get_data_spec(batch_size): return ( ( InputSpec((batch_size,), dtype="string"), InputSpec((batch_size,), dtype="string"), ), InputSpec( (batch_size, SEQUENCE_LENGTH), dtype="int64", range=[0, VOCAB_SIZE] ), ) def get_input_preprocessor(): encoder_input_vectorizer = keras.layers.TextVectorization( max_tokens=VOCAB_SIZE, output_mode="int", output_sequence_length=SEQUENCE_LENGTH, ) decoder_input_vectorizer = keras.layers.TextVectorization( max_tokens=VOCAB_SIZE, output_mode="int", output_sequence_length=SEQUENCE_LENGTH, ) text_ds = tf.data.Dataset.from_tensor_slices( [ "Lorem ipsum dolor sit amet", "consectetur adipiscing elit", "sed do eiusmod tempor incididunt ut", "labore et dolore magna aliqua.", "Ut enim ad minim veniam", "quis nostrud exercitation ullamco", "laboris nisi ut aliquip ex ea commodo consequat.", ] ) encoder_input_vectorizer.adapt(text_ds) decoder_input_vectorizer.adapt(text_ds) return lambda x: ( encoder_input_vectorizer(x[0]), decoder_input_vectorizer(x[1]), ) class TransformerEncoder(keras.layers.Layer): def __init__(self, embed_dim, dense_dim, num_heads, **kwargs): super().__init__(**kwargs) self.embed_dim = embed_dim self.dense_dim = dense_dim self.num_heads = num_heads self.attention = keras.layers.MultiHeadAttention( num_heads=num_heads, key_dim=embed_dim ) self.dense_proj = keras.Sequential( [ keras.layers.Dense(dense_dim, activation="relu"), keras.layers.Dense(embed_dim), ] ) self.layernorm_1 = keras.layers.LayerNormalization() self.layernorm_2 = keras.layers.LayerNormalization() self.supports_masking = True def call(self, inputs, mask=None): if mask is not None: padding_mask = tf.cast( mask[:, tf.newaxis, tf.newaxis, :], dtype="int32" ) attention_output = self.attention( query=inputs, value=inputs, key=inputs, attention_mask=padding_mask ) proj_input = self.layernorm_1(inputs + attention_output) proj_output = self.dense_proj(proj_input) return self.layernorm_2(proj_input + proj_output) class PositionalEmbedding(keras.layers.Layer): def __init__(self, sequence_length, vocab_size, embed_dim, **kwargs): super().__init__(**kwargs) self.token_embeddings = keras.layers.Embedding( input_dim=vocab_size, output_dim=embed_dim ) self.position_embeddings = keras.layers.Embedding( input_dim=sequence_length, output_dim=embed_dim ) self.sequence_length = sequence_length self.vocab_size = vocab_size self.embed_dim = embed_dim def call(self, inputs): length = tf.shape(inputs)[-1] positions = tf.range(start=0, limit=length, delta=1) embedded_tokens = self.token_embeddings(inputs) embedded_positions = self.position_embeddings(positions) return embedded_tokens + embedded_positions def compute_mask(self, inputs, mask=None): return tf.math.not_equal(inputs, 0) class TransformerDecoder(keras.layers.Layer): def __init__(self, embed_dim, latent_dim, num_heads, **kwargs): super().__init__(**kwargs) self.embed_dim = embed_dim self.latent_dim = latent_dim self.num_heads = num_heads self.attention_1 = keras.layers.MultiHeadAttention( num_heads=num_heads, key_dim=embed_dim ) self.attention_2 = keras.layers.MultiHeadAttention( num_heads=num_heads, key_dim=embed_dim ) self.dense_proj = keras.Sequential( [ keras.layers.Dense(latent_dim, activation="relu"), keras.layers.Dense(embed_dim), ] ) self.layernorm_1 = keras.layers.LayerNormalization() self.layernorm_2 = keras.layers.LayerNormalization() self.layernorm_3 = keras.layers.LayerNormalization() self.supports_masking = True def call(self, inputs, encoder_outputs, mask=None): causal_mask = self.get_causal_attention_mask(inputs) if mask is not None: padding_mask = tf.cast(mask[:, tf.newaxis, :], dtype="int32") padding_mask = tf.minimum(padding_mask, causal_mask) attention_output_1 = self.attention_1( query=inputs, value=inputs, key=inputs, attention_mask=causal_mask ) out_1 = self.layernorm_1(inputs + attention_output_1) attention_output_2 = self.attention_2( query=out_1, value=encoder_outputs, key=encoder_outputs, attention_mask=padding_mask, ) out_2 = self.layernorm_2(out_1 + attention_output_2) proj_output = self.dense_proj(out_2) return self.layernorm_3(out_2 + proj_output) def get_causal_attention_mask(self, inputs): input_shape = tf.shape(inputs) batch_size, sequence_length = input_shape[0], input_shape[1] i = tf.range(sequence_length)[:, tf.newaxis] j = tf.range(sequence_length) mask = tf.cast(i >= j, dtype="int32") mask = tf.reshape(mask, (1, input_shape[1], input_shape[1])) mult = tf.concat( [ tf.expand_dims(batch_size, -1), tf.constant([1, 1], dtype=tf.int32), ], axis=0, ) return tf.tile(mask, mult) def get_model( build=False, compile=False, jit_compile=False, include_preprocessing=True ): embed_dim = 256 latent_dim = 256 num_heads = 2 if include_preprocessing: encoder_inputs = keras.Input(shape=(), dtype="string") decoder_inputs = keras.Input(shape=(), dtype="string") encoder_x, decoder_x = get_input_preprocessor()( (encoder_inputs, decoder_inputs) ) else: encoder_inputs = keras.Input(shape=(None,), dtype="int64") decoder_inputs = keras.Input(shape=(None,), dtype="int64") encoder_x = encoder_inputs decoder_x = decoder_inputs x = PositionalEmbedding(SEQUENCE_LENGTH, VOCAB_SIZE, embed_dim)(encoder_x) encoder_outputs = TransformerEncoder(embed_dim, latent_dim, num_heads)(x) encoded_seq_inputs = keras.Input(shape=(None, embed_dim)) x = PositionalEmbedding(SEQUENCE_LENGTH, VOCAB_SIZE, embed_dim)(decoder_x) x = TransformerDecoder(embed_dim, latent_dim, num_heads)( x, encoded_seq_inputs ) x = keras.layers.Dropout(0.5)(x) decoder_outputs = keras.layers.Dense(VOCAB_SIZE, activation="softmax")(x) decoder = keras.Model([decoder_inputs, encoded_seq_inputs], decoder_outputs) decoder_outputs = decoder([decoder_inputs, encoder_outputs]) model = keras.Model( [encoder_inputs, decoder_inputs], decoder_outputs, name="transformer" ) if compile: model.compile( "rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"], jit_compile=jit_compile, ) return model def get_custom_objects(): return { "TransformerEncoder": TransformerEncoder, "TransformerDecoder": TransformerDecoder, "PositionalEmbedding": PositionalEmbedding, }
tf-keras/tf_keras/integration_test/models/translation.py/0
{ "file_path": "tf-keras/tf_keras/integration_test/models/translation.py", "repo_id": "tf-keras", "token_count": 3720 }
181
# Copyright 2018 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 TPUStrategy.""" import random import tempfile import tensorflow.compat.v2 as tf from absl import flags # isort: off from tensorflow.python.framework import ( test_util as tf_test_utils, ) FLAGS = flags.FLAGS flags.DEFINE_string("tpu", "", "Name of TPU to connect to.") flags.DEFINE_string("project", None, "Name of GCP project with TPU.") flags.DEFINE_string("zone", None, "Name of GCP zone with TPU.") # These vocabularies usually come from TFT or a Beam pipeline. FEATURE_VOCAB = [ "avenger", "ironman", "batman", "hulk", "spiderman", "kingkong", "wonder_woman", ] LABEL_VOCAB = ["yes", "no"] def get_tpu_cluster_resolver(): resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=FLAGS.tpu, zone=FLAGS.zone, project=FLAGS.project, ) return resolver def get_tpu_strategy(): resolver = get_tpu_cluster_resolver() tf.config.experimental_connect_to_cluster(resolver) tf.tpu.experimental.initialize_tpu_system(resolver) return tf.distribute.experimental.TPUStrategy(resolver) class TpuStrategyTest(tf.test.TestCase): def define_kpls_for_training(self, use_adapt): if use_adapt: feature_lookup_layer = tf.keras.layers.StringLookup( num_oov_indices=1 ) feature_lookup_layer.adapt(FEATURE_VOCAB) label_lookup_layer = tf.keras.layers.StringLookup( num_oov_indices=0, mask_token=None ) label_lookup_layer.adapt(LABEL_VOCAB) else: feature_lookup_layer = tf.keras.layers.StringLookup( vocabulary=FEATURE_VOCAB, num_oov_indices=1 ) label_lookup_layer = tf.keras.layers.StringLookup( vocabulary=LABEL_VOCAB, num_oov_indices=0, mask_token=None ) raw_feature_input = tf.keras.layers.Input( shape=(3,), dtype=tf.dtypes.string, name="feature", ragged=True ) feature_id_input = feature_lookup_layer(raw_feature_input) feature_mapper = tf.keras.Model( {"features": raw_feature_input}, feature_id_input ) raw_label_input = tf.keras.layers.Input( shape=(1,), dtype=tf.dtypes.string, name="label" ) label_id_input = label_lookup_layer(raw_label_input) label_mapper = tf.keras.Model( {"label": raw_label_input}, label_id_input ) return feature_mapper, label_mapper def define_inverse_lookup_layer(self): # Only needed for serving. label_inverse_lookup_layer = tf.keras.layers.StringLookup( num_oov_indices=0, mask_token=None, vocabulary=LABEL_VOCAB, invert=True, ) return label_inverse_lookup_layer def test_keras_metric_outside_strategy_scope_per_replica(self): if not tf.compat.v1.executing_eagerly(): self.skipTest( "connect_to_cluster() can only be called in eager mode" ) strategy = get_tpu_strategy() metric = tf.keras.metrics.Mean("test_metric", dtype=tf.float32) dataset = tf.data.Dataset.range( strategy.num_replicas_in_sync * 2 ).batch(2) dataset = strategy.experimental_distribute_dataset(dataset) @tf.function def step_fn(i): metric.update_state(i) with self.assertRaisesRegex( ValueError, "Trying to run metric.update_state in replica context", ): with strategy.scope(): for i in dataset: strategy.run(step_fn, args=(i,)) @tf_test_utils.disable_mlir_bridge( "TODO(b/168036682): Support dynamic padder" ) def test_train_and_serve(self): if not tf.compat.v1.executing_eagerly(): self.skipTest( "connect_to_cluster() can only be called in eager mode" ) strategy = get_tpu_strategy() use_adapt = False with strategy.scope(): feature_mapper, label_mapper = self.define_kpls_for_training( use_adapt ) def dataset_fn(_): def feature_and_label_gen(): # Generator of dataset. while True: features = random.sample(FEATURE_VOCAB, 3) label = ["yes"] if "avenger" in features else ["no"] yield {"features": features, "label": label} raw_dataset = ( tf.data.Dataset.from_generator( feature_and_label_gen, output_signature={ "features": tf.TensorSpec([3], tf.dtypes.string), "label": tf.TensorSpec([1], tf.dtypes.string), }, ) .shuffle(100) .batch(32) ) train_dataset = raw_dataset.map( lambda x: ( {"features": feature_mapper(x["features"])}, label_mapper(x["label"]), ) ) return train_dataset # Create the model. The input needs to be compatible with KPLs. model_input = tf.keras.layers.Input( shape=(3,), dtype=tf.dtypes.int64, name="model_input" ) # input_dim includes a mask token and an oov token. emb_output = tf.keras.layers.Embedding( input_dim=len(FEATURE_VOCAB) + 2, output_dim=20 )(model_input) emb_output = tf.math.reduce_mean(emb_output, axis=1) dense_output = tf.keras.layers.Dense(units=1, activation="sigmoid")( emb_output ) model = tf.keras.Model({"features": model_input}, dense_output) optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.1) accuracy = tf.keras.metrics.Accuracy() @tf.function def train_step(iterator): """The step function for one training step.""" def step_fn(inputs): """The computation to run on each TPU device.""" features, labels = inputs with tf.GradientTape() as tape: pred = model(features, training=True) loss = tf.keras.losses.binary_crossentropy(labels, pred) loss = tf.nn.compute_average_loss(loss) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients( list(zip(grads, model.trainable_variables)) ) actual_pred = tf.cast( tf.math.greater(pred, 0.5), tf.dtypes.int64 ) accuracy.update_state(labels, actual_pred) strategy.run(step_fn, args=(next(iterator),)) distributed_dataset = strategy.distribute_datasets_from_function( dataset_fn ) distributed_iterator = iter(distributed_dataset) num_epochs = 4 num_steps = 7 for _ in range(num_epochs): accuracy.reset_state() for _ in range(num_steps): train_step(distributed_iterator) self.assertGreater(accuracy.result().numpy(), 0.5) self.assertEqual( optimizer.iterations.numpy(), num_epochs * num_steps ) # Create a saved model. model.feature_mapper = feature_mapper model.label_mapper = label_mapper model.label_inverse_lookup_layer = ( self.define_inverse_lookup_layer() ) def create_serving_signature(model): @tf.function def serve_fn(raw_features): raw_features = tf.expand_dims(raw_features, axis=0) transformed_features = model.feature_mapper(raw_features) outputs = model(transformed_features) outputs = tf.squeeze(outputs, axis=0) outputs = tf.cast( tf.math.greater(outputs, 0.5), tf.dtypes.int64 ) decoded_outputs = model.label_inverse_lookup_layer(outputs) return tf.squeeze(decoded_outputs, axis=0) # Serving does NOT have batch dimension return serve_fn.get_concrete_function( tf.TensorSpec( shape=(3), dtype=tf.dtypes.string, name="example" ) ) serving_fn = create_serving_signature(model) saved_model_dir = tempfile.mkdtemp(dir=self.get_temp_dir()) model.save( saved_model_dir, save_format="tf", signatures={"serving_default": serving_fn}, ) # Test the saved_model. loaded_serving_fn = tf.keras.models.load_model( saved_model_dir ).signatures["serving_default"] # Check model calling with serving signature. prediction1 = loaded_serving_fn( tf.constant(["avenger", "ironman", "avenger"]) )["output_0"] self.assertIn(prediction1, ("yes", "no")) prediction2 = loaded_serving_fn( tf.constant(["ironman", "ironman", "unknown"]) )["output_0"] self.assertIn(prediction2, ("yes", "no")) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/integration_test/tpu_strategy_test.py/0
{ "file_path": "tf-keras/tf_keras/integration_test/tpu_strategy_test.py", "repo_id": "tf-keras", "token_count": 5316 }
182
# 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. # ============================================================================== """Parametric Rectified Linear Unit activation layer.""" from tf_keras import backend from tf_keras import constraints from tf_keras import initializers from tf_keras import regularizers from tf_keras.engine.base_layer import Layer from tf_keras.engine.input_spec import InputSpec from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.PReLU") class PReLU(Layer): """Parametric Rectified Linear Unit. It follows: ``` f(x) = alpha * x for x < 0 f(x) = x for x >= 0 ``` where `alpha` is a learned array with the same shape as x. Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Args: alpha_initializer: Initializer function for the weights. alpha_regularizer: Regularizer for the weights. alpha_constraint: Constraint for the weights. shared_axes: The axes along which to share learnable parameters for the activation function. For example, if the incoming feature maps are from a 2D convolution with output shape `(batch, height, width, channels)`, and you wish to share parameters across space so that each filter only has one set of parameters, set `shared_axes=[1, 2]`. """ def __init__( self, alpha_initializer="zeros", alpha_regularizer=None, alpha_constraint=None, shared_axes=None, **kwargs ): super().__init__(**kwargs) self.supports_masking = True self.alpha_initializer = initializers.get(alpha_initializer) self.alpha_regularizer = regularizers.get(alpha_regularizer) self.alpha_constraint = constraints.get(alpha_constraint) if shared_axes is None: self.shared_axes = None elif not isinstance(shared_axes, (list, tuple)): self.shared_axes = [shared_axes] else: self.shared_axes = list(shared_axes) @tf_utils.shape_type_conversion def build(self, input_shape): param_shape = list(input_shape[1:]) if self.shared_axes is not None: for i in self.shared_axes: param_shape[i - 1] = 1 self.alpha = self.add_weight( shape=param_shape, name="alpha", initializer=self.alpha_initializer, regularizer=self.alpha_regularizer, constraint=self.alpha_constraint, ) # Set input spec axes = {} if self.shared_axes: for i in range(1, len(input_shape)): if i not in self.shared_axes: axes[i] = input_shape[i] self.input_spec = InputSpec(ndim=len(input_shape), axes=axes) self.built = True def call(self, inputs): pos = backend.relu(inputs) neg = -self.alpha * backend.relu(-inputs) return pos + neg def get_config(self): config = { "alpha_initializer": initializers.serialize(self.alpha_initializer), "alpha_regularizer": regularizers.serialize(self.alpha_regularizer), "alpha_constraint": constraints.serialize(self.alpha_constraint), "shared_axes": self.shared_axes, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items())) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): return input_shape
tf-keras/tf_keras/layers/activation/prelu.py/0
{ "file_path": "tf-keras/tf_keras/layers/activation/prelu.py", "repo_id": "tf-keras", "token_count": 1763 }
183
# Copyright 2019 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. # ============================================================================== """Keras-based multi-head attention layer.""" import collections import math import string import numpy as np import tensorflow.compat.v2 as tf from tf_keras import constraints from tf_keras import initializers from tf_keras import regularizers from tf_keras.engine.base_layer import Layer from tf_keras.layers import activation from tf_keras.layers import core from tf_keras.layers import regularization from tf_keras.utils import tf_utils # isort: off from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export _CHR_IDX = string.ascii_lowercase def _build_attention_equation(rank, attn_axes): """Builds einsum equations for the attention computation. Query, key, value inputs after projection are expected to have the shape as: `(bs, <non-attention dims>, <attention dims>, num_heads, channels)`. `bs` and `<non-attention dims>` are treated as `<batch dims>`. The attention operations can be generalized: (1) Query-key dot product: `(<batch dims>, <query attention dims>, num_heads, channels), (<batch dims>, <key attention dims>, num_heads, channels) -> (<batch dims>, num_heads, <query attention dims>, <key attention dims>)` (2) Combination: `(<batch dims>, num_heads, <query attention dims>, <key attention dims>), (<batch dims>, <value attention dims>, num_heads, channels) -> (<batch dims>, <query attention dims>, num_heads, channels)` Args: rank: Rank of query, key, value tensors. attn_axes: List/tuple of axes, `[-1, rank)`, that attention will be applied to. Returns: Einsum equations. """ target_notation = _CHR_IDX[:rank] # `batch_dims` includes the head dim. batch_dims = tuple(np.delete(range(rank), attn_axes + (rank - 1,))) letter_offset = rank source_notation = "" for i in range(rank): if i in batch_dims or i == rank - 1: source_notation += target_notation[i] else: source_notation += _CHR_IDX[letter_offset] letter_offset += 1 product_notation = "".join( [target_notation[i] for i in batch_dims] + [target_notation[i] for i in attn_axes] + [source_notation[i] for i in attn_axes] ) dot_product_equation = "%s,%s->%s" % ( source_notation, target_notation, product_notation, ) attn_scores_rank = len(product_notation) combine_equation = "%s,%s->%s" % ( product_notation, source_notation, target_notation, ) return dot_product_equation, combine_equation, attn_scores_rank def _build_proj_equation(free_dims, bound_dims, output_dims): """Builds an einsum equation for projections inside multi-head attention.""" input_str = "" kernel_str = "" output_str = "" bias_axes = "" letter_offset = 0 for i in range(free_dims): char = _CHR_IDX[i + letter_offset] input_str += char output_str += char letter_offset += free_dims for i in range(bound_dims): char = _CHR_IDX[i + letter_offset] input_str += char kernel_str += char letter_offset += bound_dims for i in range(output_dims): char = _CHR_IDX[i + letter_offset] kernel_str += char output_str += char bias_axes += char equation = f"{input_str},{kernel_str}->{output_str}" return equation, bias_axes, len(output_str) def _get_output_shape(output_rank, known_last_dims): return [None] * (output_rank - len(known_last_dims)) + list(known_last_dims) @keras_export("keras.layers.MultiHeadAttention") class MultiHeadAttention(Layer): """MultiHeadAttention layer. This is an implementation of multi-headed attention as described in the paper "Attention is all you Need" (Vaswani et al., 2017). If `query`, `key,` `value` are the same, then this is self-attention. Each timestep in `query` attends to the corresponding sequence in `key`, and returns a fixed-width vector. This layer first projects `query`, `key` and `value`. These are (effectively) a list of tensors of length `num_attention_heads`, where the corresponding shapes are `(batch_size, <query dimensions>, key_dim)`, `(batch_size, <key/value dimensions>, key_dim)`, `(batch_size, <key/value dimensions>, value_dim)`. Then, the query and key tensors are dot-producted and scaled. These are softmaxed to obtain attention probabilities. The value tensors are then interpolated by these probabilities, then concatenated back to a single tensor. Finally, the result tensor with the last dimension as value_dim can take an linear projection and return. When using `MultiHeadAttention` inside a custom layer, the custom layer must implement its own `build()` method and call `MultiHeadAttention`'s `_build_from_signature()` there. This enables weights to be restored correctly when the model is loaded. Examples: Performs 1D cross-attention over two sequence inputs with an attention mask. Returns the additional attention weights over heads. >>> layer = MultiHeadAttention(num_heads=2, key_dim=2) >>> target = tf.keras.Input(shape=[8, 16]) >>> source = tf.keras.Input(shape=[4, 16]) >>> output_tensor, weights = layer(target, source, ... return_attention_scores=True) >>> print(output_tensor.shape) (None, 8, 16) >>> print(weights.shape) (None, 2, 8, 4) Performs 2D self-attention over a 5D input tensor on axes 2 and 3. >>> layer = MultiHeadAttention( ... num_heads=2, key_dim=2, attention_axes=(2, 3)) >>> input_tensor = tf.keras.Input(shape=[5, 3, 4, 16]) >>> output_tensor = layer(input_tensor, input_tensor) >>> print(output_tensor.shape) (None, 5, 3, 4, 16) Args: num_heads: Number of attention heads. key_dim: Size of each attention head for query and key. value_dim: Size of each attention head for value. dropout: Dropout probability. use_bias: Boolean, whether the dense layers use bias vectors/matrices. output_shape: The expected shape of an output tensor, besides the batch and sequence dims. If not specified, projects back to the query feature dim (the query input's last dimension). attention_axes: axes over which the attention is applied. `None` means attention over all axes, but batch, heads, and features. kernel_initializer: Initializer for dense layer kernels. bias_initializer: Initializer for dense layer biases. kernel_regularizer: Regularizer for dense layer kernels. bias_regularizer: Regularizer for dense layer biases. activity_regularizer: Regularizer for dense layer activity. kernel_constraint: Constraint for dense layer kernels. bias_constraint: Constraint for dense layer kernels. Call arguments: query: Query `Tensor` of shape `(B, T, dim)`. value: Value `Tensor` of shape `(B, S, dim)`. key: Optional key `Tensor` of shape `(B, S, dim)`. If not given, will use `value` for both `key` and `value`, which is the most common case. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. The boolean mask specifies which query elements can attend to which key elements, 1 indicates attention and 0 indicates no attention. Broadcasting can happen for the missing batch dimensions and the head dimension. return_attention_scores: A boolean to indicate whether the output should be `(attention_output, attention_scores)` if `True`, or `attention_output` if `False`. Defaults to `False`. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Will go with either using the training mode of the parent layer/model, or False (inference) if there is no parent layer. use_causal_mask: A boolean to indicate whether to apply a causal mask to prevent tokens from attending to future tokens (e.g., used in a decoder Transformer). Returns: attention_output: The result of the computation, of shape `(B, T, E)`, where `T` is for target sequence shapes and `E` is the query input last dimension if `output_shape` is `None`. Otherwise, the multi-head outputs are projected to the shape specified by `output_shape`. attention_scores: [Optional] multi-head attention coefficients over attention axes. """ def __init__( self, num_heads, key_dim, value_dim=None, dropout=0.0, use_bias=True, output_shape=None, attention_axes=None, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs, ): super().__init__(**kwargs) self.supports_masking = True self._num_heads = num_heads self._key_dim = key_dim self._value_dim = value_dim if value_dim else key_dim self._dropout = dropout self._use_bias = use_bias self._output_shape = output_shape self._kernel_initializer = initializers.get(kernel_initializer) self._bias_initializer = initializers.get(bias_initializer) self._kernel_regularizer = regularizers.get(kernel_regularizer) self._bias_regularizer = regularizers.get(bias_regularizer) self._activity_regularizer = regularizers.get(activity_regularizer) self._kernel_constraint = constraints.get(kernel_constraint) self._bias_constraint = constraints.get(bias_constraint) if attention_axes is not None and not isinstance( attention_axes, collections.abc.Sized ): self._attention_axes = (attention_axes,) else: self._attention_axes = attention_axes self._built_from_signature = False self._query_shape, self._key_shape, self._value_shape = None, None, None def get_config(self): config = { "num_heads": self._num_heads, "key_dim": self._key_dim, "value_dim": self._value_dim, "dropout": self._dropout, "use_bias": self._use_bias, "output_shape": self._output_shape, "attention_axes": self._attention_axes, "kernel_initializer": initializers.serialize( self._kernel_initializer ), "bias_initializer": initializers.serialize(self._bias_initializer), "kernel_regularizer": regularizers.serialize( self._kernel_regularizer ), "bias_regularizer": regularizers.serialize(self._bias_regularizer), "activity_regularizer": regularizers.serialize( self._activity_regularizer ), "kernel_constraint": constraints.serialize(self._kernel_constraint), "bias_constraint": constraints.serialize(self._bias_constraint), "query_shape": self._query_shape, "key_shape": self._key_shape, "value_shape": self._value_shape, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): # If the layer has a different build() function from the TF-Keras # default, we need to trigger the customized build to create weights. query_shape = config.pop("query_shape") key_shape = config.pop("key_shape") value_shape = config.pop("value_shape") layer = cls(**config) if None in [query_shape, key_shape, value_shape]: logging.warning( "One of dimensions of the input shape is missing. It " "should have been memorized when the layer was serialized. " "%s is created without weights.", str(cls), ) else: layer._build_from_signature(query_shape, value_shape, key_shape) return layer def _build_from_signature(self, query, value, key=None): """Builds layers and variables. Once the method is called, self._built_from_signature will be set to True. Args: query: Query tensor or TensorShape. value: Value tensor or TensorShape. key: Key tensor or TensorShape. """ self._built_from_signature = True if hasattr(query, "shape"): self._query_shape = tf.TensorShape(query.shape) else: self._query_shape = tf.TensorShape(query) if hasattr(value, "shape"): self._value_shape = tf.TensorShape(value.shape) else: self._value_shape = tf.TensorShape(value) if key is None: self._key_shape = self._value_shape elif hasattr(key, "shape"): self._key_shape = tf.TensorShape(key.shape) else: self._key_shape = tf.TensorShape(key) # Any setup work performed only once should happen in an `init_scope` # to avoid creating symbolic Tensors that will later pollute any eager # operations. with tf_utils.maybe_init_scope(self): free_dims = self._query_shape.rank - 1 einsum_equation, bias_axes, output_rank = _build_proj_equation( free_dims, bound_dims=1, output_dims=2 ) self._query_dense = core.EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._key_dim] ), bias_axes=bias_axes if self._use_bias else None, name="query", **self._get_common_kwargs_for_sublayer(), ) einsum_equation, bias_axes, output_rank = _build_proj_equation( self._key_shape.rank - 1, bound_dims=1, output_dims=2 ) self._key_dense = core.EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._key_dim] ), bias_axes=bias_axes if self._use_bias else None, name="key", **self._get_common_kwargs_for_sublayer(), ) einsum_equation, bias_axes, output_rank = _build_proj_equation( self._value_shape.rank - 1, bound_dims=1, output_dims=2 ) self._value_dense = core.EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._value_dim] ), bias_axes=bias_axes if self._use_bias else None, name="value", **self._get_common_kwargs_for_sublayer(), ) # Builds the attention computations for multi-head dot product # attention. These computations could be wrapped into the keras # attention layer once it supports mult-head einsum computations. self._build_attention(output_rank) self._output_dense = self._make_output_dense( free_dims, self._get_common_kwargs_for_sublayer(), "attention_output", ) def _get_common_kwargs_for_sublayer(self): common_kwargs = dict( kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint, dtype=self._dtype_policy, ) # Create new clone of kernel/bias initializer, so that we don't reuse # the initializer instance, which could lead to same init value since # initializer is stateless. kernel_initializer = self._kernel_initializer.__class__.from_config( self._kernel_initializer.get_config() ) bias_initializer = self._bias_initializer.__class__.from_config( self._bias_initializer.get_config() ) common_kwargs["kernel_initializer"] = kernel_initializer common_kwargs["bias_initializer"] = bias_initializer return common_kwargs def _make_output_dense(self, free_dims, common_kwargs, name=None): """Builds the output projection matrix. Args: free_dims: Number of free dimensions for einsum equation building. common_kwargs: Common keyword arguments for einsum layer. name: Name for the projection layer. Returns: Projection layer. """ if self._output_shape: if not isinstance(self._output_shape, collections.abc.Sized): output_shape = [self._output_shape] else: output_shape = self._output_shape else: output_shape = [self._query_shape[-1]] einsum_equation, bias_axes, output_rank = _build_proj_equation( free_dims, bound_dims=2, output_dims=len(output_shape) ) return core.EinsumDense( einsum_equation, output_shape=_get_output_shape(output_rank - 1, output_shape), bias_axes=bias_axes if self._use_bias else None, name=name, **common_kwargs, ) def _build_attention(self, rank): """Builds multi-head dot-product attention computations. This function builds attributes necessary for `_compute_attention` to customize attention computation to replace the default dot-product attention. Args: rank: the rank of query, key, value tensors. """ if self._attention_axes is None: self._attention_axes = tuple(range(1, rank - 2)) else: self._attention_axes = tuple(self._attention_axes) ( self._dot_product_equation, self._combine_equation, attn_scores_rank, ) = _build_attention_equation(rank, attn_axes=self._attention_axes) norm_axes = tuple( range( attn_scores_rank - len(self._attention_axes), attn_scores_rank ) ) self._softmax = activation.Softmax( axis=norm_axes, dtype=self._dtype_policy ) self._dropout_layer = regularization.Dropout( rate=self._dropout, dtype=self._dtype_policy ) def _masked_softmax(self, attention_scores, attention_mask=None): # Normalize the attention scores to probabilities. # `attention_scores` = [B, N, T, S] if attention_mask is not None: # The expand dim happens starting from the `num_heads` dimension, # (<batch_dims>, num_heads, <query_attention_dims, # key_attention_dims>) mask_expansion_axis = -len(self._attention_axes) * 2 - 1 for _ in range( len(attention_scores.shape) - len(attention_mask.shape) ): attention_mask = tf.expand_dims( attention_mask, axis=mask_expansion_axis ) return self._softmax(attention_scores, attention_mask) def _compute_attention( self, query, key, value, attention_mask=None, training=None ): """Applies Dot-product attention with query, key, value tensors. This function defines the computation inside `call` with projected multi-head Q, K, V inputs. Users can override this function for customized attention implementation. Args: query: Projected query `Tensor` of shape `(B, T, N, key_dim)`. key: Projected key `Tensor` of shape `(B, S, N, key_dim)`. value: Projected value `Tensor` of shape `(B, S, N, value_dim)`. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. It is generally not needed if the `query` and `value` (and/or `key`) are masked. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Returns: attention_output: Multi-headed outputs of attention computation. attention_scores: Multi-headed attention weights. """ # Note: Applying scalar multiply at the smaller end of einsum improves # XLA performance, but may introduce slight numeric differences in # the Transformer attention head. query = tf.multiply(query, 1.0 / math.sqrt(float(self._key_dim))) # Take the dot product between "query" and "key" to get the raw # attention scores. attention_scores = tf.einsum(self._dot_product_equation, key, query) attention_scores = self._masked_softmax( attention_scores, attention_mask ) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_scores_dropout = self._dropout_layer( attention_scores, training=training ) # `context_layer` = [B, T, N, H] attention_output = tf.einsum( self._combine_equation, attention_scores_dropout, value ) return attention_output, attention_scores def call( self, query, value, key=None, attention_mask=None, return_attention_scores=False, training=None, use_causal_mask=False, ): if not self._built_from_signature: self._build_from_signature(query=query, value=value, key=key) if key is None: key = value # Convert RaggedTensor to Tensor. query_is_ragged = isinstance(query, tf.RaggedTensor) if query_is_ragged: query_lengths = query.nested_row_lengths() query = query.to_tensor() key_is_ragged = isinstance(key, tf.RaggedTensor) value_is_ragged = isinstance(value, tf.RaggedTensor) if key_is_ragged and value_is_ragged: # Ensure they have the same shape. bounding_shape = tf.math.maximum( key.bounding_shape(), value.bounding_shape() ) key = key.to_tensor(shape=bounding_shape) value = value.to_tensor(shape=bounding_shape) elif key_is_ragged: key = key.to_tensor(shape=tf.shape(value)) elif value_is_ragged: value = value.to_tensor(shape=tf.shape(key)) attention_mask = self._compute_attention_mask( query, value, key=key, attention_mask=attention_mask, use_causal_mask=use_causal_mask, ) # N = `num_attention_heads` # H = `size_per_head` # `query` = [B, T, N ,H] query = self._query_dense(query) # `key` = [B, S, N, H] key = self._key_dense(key) # `value` = [B, S, N, H] value = self._value_dense(value) attention_output, attention_scores = self._compute_attention( query, key, value, attention_mask, training ) attention_output = self._output_dense(attention_output) if query_is_ragged: attention_output = tf.RaggedTensor.from_tensor( attention_output, lengths=query_lengths ) if return_attention_scores: return attention_output, attention_scores return attention_output def _compute_attention_mask( self, query, value, key=None, attention_mask=None, use_causal_mask=False ): """Computes the attention mask, using the TF-Keras masks of the inputs. * The `query`'s mask is reshaped from [B, T] to [B, T, 1]. * The `value`'s mask is reshaped from [B, S] to [B, 1, S]. * The `key`'s mask is reshaped from [B, S] to [B, 1, S]. The `key`'s mask is ignored if `key` is `None` or if `key is value`. * If `use_causal_mask=True`, then the causal mask is computed. Its shape is [1, T, S]. All defined masks are merged using a logical AND operation (`&`). In general, if the `query` and `value` are masked, then there is no need to define the `attention_mask`. Args: query: Projected query `Tensor` of shape `(B, T, N, key_dim)`. key: Projected key `Tensor` of shape `(B, T, N, key_dim)`. value: Projected value `Tensor` of shape `(B, T, N, value_dim)`. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. use_causal_mask: A boolean to indicate whether to apply a causal mask to prevent tokens from attending to future tokens (e.g., used in a decoder Transformer). Returns: attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions, based on the TF-Keras masks of the `query`, `key`, `value`, and `attention_mask` tensors, and the causal mask if `use_causal_mask=True`. """ query_mask = getattr(query, "_keras_mask", None) value_mask = getattr(value, "_keras_mask", None) key_mask = getattr(key, "_keras_mask", None) auto_mask = None if query_mask is not None: query_mask = tf.cast(query_mask, tf.bool) # defensive casting # B = batch size, T = max query length auto_mask = query_mask[:, :, tf.newaxis] # shape is [B, T, 1] if value_mask is not None: value_mask = tf.cast(value_mask, tf.bool) # defensive casting # B = batch size, S == max value length mask = value_mask[:, tf.newaxis, :] # shape is [B, 1, S] auto_mask = mask if auto_mask is None else auto_mask & mask if key_mask is not None: key_mask = tf.cast(key_mask, tf.bool) # defensive casting # B == batch size, S == max key length == max value length mask = key_mask[:, tf.newaxis, :] # shape is [B, 1, S] auto_mask = mask if auto_mask is None else auto_mask & mask if use_causal_mask: # the shape of the causal mask is [1, T, S] mask = self._compute_causal_mask(query, value) auto_mask = mask if auto_mask is None else auto_mask & mask if auto_mask is not None: # merge attention_mask & automatic mask, to shape [B, T, S] attention_mask = ( auto_mask if attention_mask is None else tf.cast(attention_mask, bool) & auto_mask ) return attention_mask def _compute_causal_mask(self, query, value=None): """Computes a causal mask (e.g., for masked self-attention layers). For example, if query and value both contain sequences of length 4, this function returns a boolean `Tensor` equal to: ``` [[[True, False, False, False], [True, True, False, False], [True, True, True, False], [True, True, True, True]]] ``` Args: query: query `Tensor` of shape `(B, T, ...)`. value: value `Tensor` of shape `(B, S, ...)` (optional, defaults to query). Returns: mask: a boolean `Tensor` of shape [1, T, S] containing a lower triangular matrix of shape [T, S]. """ q_seq_length = tf.shape(query)[1] v_seq_length = q_seq_length if value is None else tf.shape(value)[1] return tf.linalg.band_part( # creates a lower triangular matrix tf.ones((1, q_seq_length, v_seq_length), tf.bool), -1, 0 ) def compute_output_shape(self, query_shape, value_shape, key_shape=None): if key_shape is None: key_shape = value_shape query_shape = tf.TensorShape(query_shape) value_shape = tf.TensorShape(value_shape) key_shape = tf.TensorShape(key_shape) if query_shape[-1] != value_shape[-1]: raise ValueError( "The last dimension of `query_shape` and `value_shape` " f"must be equal, but are {query_shape[-1]}, {value_shape[-1]}. " "Received: query_shape={query_shape}, value_shape={value_shape}" ) if value_shape[1:-1] != key_shape[1:-1]: raise ValueError( "All dimensions of `value` and `key`, except the last one, " f"must be equal. Received {value_shape} and " f"{key_shape}" ) if self._output_shape: return query_shape[:-1].concatenate(self._output_shape) return query_shape
tf-keras/tf_keras/layers/attention/multi_head_attention.py/0
{ "file_path": "tf-keras/tf_keras/layers/attention/multi_head_attention.py", "repo_id": "tf-keras", "token_count": 13184 }
184
# 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. # ============================================================================== """Keras depthwise 2D convolution.""" from tf_keras import backend from tf_keras.layers.convolutional.base_depthwise_conv import DepthwiseConv from tf_keras.utils import conv_utils from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.DepthwiseConv2D") class DepthwiseConv2D(DepthwiseConv): """Depthwise 2D convolution. Depthwise convolution is a type of convolution in which each input channel is convolved with a different kernel (called a depthwise kernel). You can understand depthwise convolution as the first step in a depthwise separable convolution. It is implemented via the following steps: - Split the input into individual channels. - Convolve each channel with an individual depthwise kernel with `depth_multiplier` output channels. - Concatenate the convolved outputs along the channels axis. Unlike a regular 2D convolution, depthwise convolution does not mix information across different input channels. The `depth_multiplier` argument determines how many filter are applied to one input channel. As such, it controls the amount of output channels that are generated per input channel in the depthwise step. Args: kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Current implementation only supports equal length strides in row and column dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value !=1. padding: one of `'valid'` or `'same'` (case-insensitive). `"valid"` means no padding. `"same"` results in padding with zeros evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. When unspecified, uses `image_data_format` value found in your TF-Keras config file at `~/.keras/keras.json` (if exists) else 'channels_last'. Defaults to 'channels_last'. dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied (see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix (see `keras.initializers`). If None, the default initializer ('glorot_uniform') will be used. bias_initializer: Initializer for the bias vector (see `keras.initializers`). If None, the default initializer ('zeros') will be used. depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector (see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its 'activation') (see `keras.regularizers`). depthwise_constraint: Constraint function applied to the depthwise kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 4D tensor with shape: `[batch_size, channels, rows, cols]` if data_format='channels_first' or 4D tensor with shape: `[batch_size, rows, cols, channels]` if data_format='channels_last'. Output shape: 4D tensor with shape: `[batch_size, channels * depth_multiplier, new_rows, new_cols]` if `data_format='channels_first'` or 4D tensor with shape: `[batch_size, new_rows, new_cols, channels * depth_multiplier]` if `data_format='channels_last'`. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4 representing `activation(depthwiseconv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__( self, kernel_size, strides=(1, 1), padding="valid", depth_multiplier=1, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, depthwise_initializer="glorot_uniform", bias_initializer="zeros", depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs ): super().__init__( 2, kernel_size=kernel_size, strides=strides, padding=padding, depth_multiplier=depth_multiplier, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, depthwise_initializer=depthwise_initializer, bias_initializer=bias_initializer, depthwise_regularizer=depthwise_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, depthwise_constraint=depthwise_constraint, bias_constraint=bias_constraint, **kwargs ) def call(self, inputs): outputs = backend.depthwise_conv2d( inputs, self.depthwise_kernel, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate, data_format=self.data_format, ) if self.use_bias: outputs = backend.bias_add( outputs, self.bias, data_format=self.data_format ) if self.activation is not None: return self.activation(outputs) return outputs @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.data_format == "channels_first": rows = input_shape[2] cols = input_shape[3] out_filters = input_shape[1] * self.depth_multiplier elif self.data_format == "channels_last": rows = input_shape[1] cols = input_shape[2] out_filters = input_shape[3] * self.depth_multiplier rows = conv_utils.conv_output_length( rows, self.kernel_size[0], self.padding, self.strides[0], self.dilation_rate[0], ) cols = conv_utils.conv_output_length( cols, self.kernel_size[1], self.padding, self.strides[1], self.dilation_rate[1], ) if self.data_format == "channels_first": return (input_shape[0], out_filters, rows, cols) elif self.data_format == "channels_last": return (input_shape[0], rows, cols, out_filters)
tf-keras/tf_keras/layers/convolutional/depthwise_conv2d.py/0
{ "file_path": "tf-keras/tf_keras/layers/convolutional/depthwise_conv2d.py", "repo_id": "tf-keras", "token_count": 3388 }
185
# 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. # ============================================================================== """Contains the Masking layer.""" import tensorflow.compat.v2 as tf from tf_keras.engine.base_layer import Layer # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.Masking") class Masking(Layer): """Masks a sequence by using a mask value to skip timesteps. For each timestep in the input tensor (dimension #1 in the tensor), if all values in the input tensor at that timestep are equal to `mask_value`, then the timestep will be masked (skipped) in all downstream layers (as long as they support masking). If any downstream layer does not support masking yet receives such an input mask, an exception will be raised. Example: Consider a Numpy data array `x` of shape `(samples, timesteps, features)`, to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you lack data for these timesteps. You can: - Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.` - Insert a `Masking` layer with `mask_value=0.` before the LSTM layer: ```python samples, timesteps, features = 32, 10, 8 inputs = np.random.random([samples, timesteps, features]).astype(np.float32) inputs[:, 3, :] = 0. inputs[:, 5, :] = 0. model = tf.keras.models.Sequential() model.add(tf.keras.layers.Masking(mask_value=0., input_shape=(timesteps, features))) model.add(tf.keras.layers.LSTM(32)) output = model(inputs) # The time step 3 and 5 will be skipped from LSTM calculation. ``` See [the masking and padding guide]( https://www.tensorflow.org/guide/keras/masking_and_padding) for more details. """ def __init__(self, mask_value=0.0, **kwargs): super().__init__(**kwargs) self.supports_masking = True self.mask_value = mask_value self._compute_output_and_mask_jointly = True def compute_mask(self, inputs, mask=None): return tf.reduce_any(tf.not_equal(inputs, self.mask_value), axis=-1) def call(self, inputs): boolean_mask = tf.reduce_any( tf.not_equal(inputs, self.mask_value), axis=-1, keepdims=True ) outputs = inputs * tf.cast(boolean_mask, inputs.dtype) # Compute the mask and outputs simultaneously. outputs._keras_mask = tf.squeeze(boolean_mask, axis=-1) return outputs def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = {"mask_value": self.mask_value} base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
tf-keras/tf_keras/layers/core/masking.py/0
{ "file_path": "tf-keras/tf_keras/layers/core/masking.py", "repo_id": "tf-keras", "token_count": 1213 }
186
# 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. # ============================================================================== """Locally-connected layer for 2D input.""" from tf_keras import activations from tf_keras import backend from tf_keras import constraints from tf_keras import initializers from tf_keras import regularizers from tf_keras.engine.base_layer import Layer from tf_keras.engine.input_spec import InputSpec from tf_keras.layers.locally_connected import locally_connected_utils from tf_keras.utils import conv_utils from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.LocallyConnected2D") class LocallyConnected2D(Layer): """Locally-connected layer for 2D inputs. The `LocallyConnected2D` layer works similarly to the `Conv2D` layer, except that weights are unshared, that is, a different set of filters is applied at each different patch of the input. Note: layer attributes cannot be modified after the layer has been called once (except the `trainable` attribute). Examples: ```python # apply a 3x3 unshared weights convolution with 64 output filters on a 32x32 image # with `data_format="channels_last"`: model = Sequential() model.add(LocallyConnected2D(64, (3, 3), input_shape=(32, 32, 3))) # now model.output_shape == (None, 30, 30, 64) # notice that this layer will consume (30*30)*(3*3*3*64) + (30*30)*64 parameters # add a 3x3 unshared weights convolution on top, with 32 output filters: model.add(LocallyConnected2D(32, (3, 3))) # now model.output_shape == (None, 28, 28, 32) ``` Args: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. padding: Currently only support `"valid"` (case-insensitive). `"same"` will be supported in future. `"valid"` means no padding. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. When unspecified, uses `image_data_format` value found in your TF-Keras config file at `~/.keras/keras.json` (if exists) else 'channels_last'. Defaults to 'channels_last'. activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). kernel_constraint: Constraint function applied to the kernel matrix. bias_constraint: Constraint function applied to the bias vector. implementation: implementation mode, either `1`, `2`, or `3`. `1` loops over input spatial locations to perform the forward pass. It is memory-efficient but performs a lot of (small) ops. `2` stores layer weights in a dense but sparsely-populated 2D matrix and implements the forward pass as a single matrix-multiply. It uses a lot of RAM but performs few (large) ops. `3` stores layer weights in a sparse tensor and implements the forward pass as a single sparse matrix-multiply. How to choose: `1`: large, dense models, `2`: small models, `3`: large, sparse models, where "large" stands for large input/output activations (i.e. many `filters`, `input_filters`, large `np.prod(input_size)`, `np.prod(output_size)`), and "sparse" stands for few connections between inputs and outputs, i.e. small ratio `filters * input_filters * np.prod(kernel_size) / (np.prod(input_size) * np.prod(strides))`, where inputs to and outputs of the layer are assumed to have shapes `input_size + (input_filters,)`, `output_size + (filters,)` respectively. It is recommended to benchmark each in the setting of interest to pick the most efficient one (in terms of speed and memory usage). Correct choice of implementation can lead to dramatic speed improvements (e.g. 50X), potentially at the expense of RAM. Also, only `padding="valid"` is supported by `implementation=1`. Input shape: 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. """ def __init__( self, filters, kernel_size, strides=(1, 1), padding="valid", data_format=None, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, implementation=1, **kwargs, ): super().__init__(**kwargs) self.filters = filters self.kernel_size = conv_utils.normalize_tuple( kernel_size, 2, "kernel_size" ) self.strides = conv_utils.normalize_tuple( strides, 2, "strides", allow_zero=True ) self.padding = conv_utils.normalize_padding(padding) if self.padding != "valid" and implementation == 1: raise ValueError( "Invalid border mode for LocallyConnected2D " '(only "valid" is supported if implementation is 1): ' + padding ) self.data_format = conv_utils.normalize_data_format(data_format) self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.implementation = implementation self.input_spec = InputSpec(ndim=4) @property def _use_input_spec_as_call_signature(self): return False @tf_utils.shape_type_conversion def build(self, input_shape): if self.data_format == "channels_last": input_row, input_col = input_shape[1:-1] input_filter = input_shape[3] else: input_row, input_col = input_shape[2:] input_filter = input_shape[1] if input_row is None or input_col is None: raise ValueError( "The spatial dimensions of the inputs to " " a LocallyConnected2D layer " "should be fully-defined, but layer received " "the inputs shape " + str(input_shape) ) output_row = conv_utils.conv_output_length( input_row, self.kernel_size[0], self.padding, self.strides[0] ) output_col = conv_utils.conv_output_length( input_col, self.kernel_size[1], self.padding, self.strides[1] ) self.output_row = output_row self.output_col = output_col if self.output_row <= 0 or self.output_col <= 0: raise ValueError( "One of the dimensions in the output is <= 0 " f"due to downsampling in {self.name}. Consider " "increasing the input size. " f"Received input shape {input_shape} which would produce " "output shape with a zero or negative value in a " "dimension." ) if self.implementation == 1: self.kernel_shape = ( output_row * output_col, self.kernel_size[0] * self.kernel_size[1] * input_filter, self.filters, ) self.kernel = self.add_weight( shape=self.kernel_shape, initializer=self.kernel_initializer, name="kernel", regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, ) elif self.implementation == 2: if self.data_format == "channels_first": self.kernel_shape = ( input_filter, input_row, input_col, self.filters, self.output_row, self.output_col, ) else: self.kernel_shape = ( input_row, input_col, input_filter, self.output_row, self.output_col, self.filters, ) self.kernel = self.add_weight( shape=self.kernel_shape, initializer=self.kernel_initializer, name="kernel", regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, ) self.kernel_mask = ( locally_connected_utils.get_locallyconnected_mask( input_shape=(input_row, input_col), kernel_shape=self.kernel_size, strides=self.strides, padding=self.padding, data_format=self.data_format, ) ) elif self.implementation == 3: self.kernel_shape = ( self.output_row * self.output_col * self.filters, input_row * input_col * input_filter, ) self.kernel_idxs = sorted( conv_utils.conv_kernel_idxs( input_shape=(input_row, input_col), kernel_shape=self.kernel_size, strides=self.strides, padding=self.padding, filters_in=input_filter, filters_out=self.filters, data_format=self.data_format, ) ) self.kernel = self.add_weight( shape=(len(self.kernel_idxs),), initializer=self.kernel_initializer, name="kernel", regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, ) else: raise ValueError( "Unrecognized implementation mode: %d." % self.implementation ) if self.use_bias: self.bias = self.add_weight( shape=(output_row, output_col, self.filters), initializer=self.bias_initializer, name="bias", regularizer=self.bias_regularizer, constraint=self.bias_constraint, ) else: self.bias = None if self.data_format == "channels_first": self.input_spec = InputSpec(ndim=4, axes={1: input_filter}) else: self.input_spec = InputSpec(ndim=4, axes={-1: input_filter}) self.built = True @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.data_format == "channels_first": rows = input_shape[2] cols = input_shape[3] elif self.data_format == "channels_last": rows = input_shape[1] cols = input_shape[2] rows = conv_utils.conv_output_length( rows, self.kernel_size[0], self.padding, self.strides[0] ) cols = conv_utils.conv_output_length( cols, self.kernel_size[1], self.padding, self.strides[1] ) if self.data_format == "channels_first": return (input_shape[0], self.filters, rows, cols) elif self.data_format == "channels_last": return (input_shape[0], rows, cols, self.filters) def call(self, inputs): if self.implementation == 1: output = backend.local_conv( inputs, self.kernel, self.kernel_size, self.strides, (self.output_row, self.output_col), self.data_format, ) elif self.implementation == 2: output = locally_connected_utils.local_conv_matmul( inputs, self.kernel, self.kernel_mask, self.compute_output_shape(inputs.shape), ) elif self.implementation == 3: output = locally_connected_utils.local_conv_sparse_matmul( inputs, self.kernel, self.kernel_idxs, self.kernel_shape, self.compute_output_shape(inputs.shape), ) else: raise ValueError( "Unrecognized implementation mode: %d." % self.implementation ) if self.use_bias: output = backend.bias_add( output, self.bias, data_format=self.data_format ) output = self.activation(output) return output def get_config(self): config = { "filters": self.filters, "kernel_size": self.kernel_size, "strides": self.strides, "padding": self.padding, "data_format": self.data_format, "activation": activations.serialize(self.activation), "use_bias": self.use_bias, "kernel_initializer": initializers.serialize( self.kernel_initializer ), "bias_initializer": initializers.serialize(self.bias_initializer), "kernel_regularizer": regularizers.serialize( self.kernel_regularizer ), "bias_regularizer": regularizers.serialize(self.bias_regularizer), "activity_regularizer": regularizers.serialize( self.activity_regularizer ), "kernel_constraint": constraints.serialize(self.kernel_constraint), "bias_constraint": constraints.serialize(self.bias_constraint), "implementation": self.implementation, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
tf-keras/tf_keras/layers/locally_connected/locally_connected2d.py/0
{ "file_path": "tf-keras/tf_keras/layers/locally_connected/locally_connected2d.py", "repo_id": "tf-keras", "token_count": 7595 }
187
# Description: # Contains the TF-Keras normalization layers (internal TensorFlow version). # Placeholder: load unaliased py_library # buildifier: disable=same-origin-load load("@org_keras//tf_keras:tf_keras.bzl", "cuda_py_test") # buildifier: disable=same-origin-load load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test") package( # copybara:uncomment default_applicable_licenses = ["//tf_keras:license"], # TODO(scottzhu): Remove non-keras deps from TF. default_visibility = ["//tf_keras:friends"], licenses = ["notice"], ) py_library( name = "normalization", srcs = [ "__init__.py", ], srcs_version = "PY3", deps = [ ":batch_normalization", ":batch_normalization_v1", ":group_normalization", ":layer_normalization", ":spectral_normalization", ":unit_normalization", ], ) py_library( name = "batch_normalization", srcs = ["batch_normalization.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras:constraints", "//tf_keras:regularizers", "//tf_keras/dtensor:utils", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/initializers", "//tf_keras/utils:control_flow_util", ], ) py_library( name = "batch_normalization_v1", srcs = ["batch_normalization_v1.py"], srcs_version = "PY3", deps = [ ":batch_normalization", "//:expect_tensorflow_installed", ], ) py_library( name = "group_normalization", srcs = ["group_normalization.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:constraints", "//tf_keras:regularizers", "//tf_keras/dtensor:utils", "//tf_keras/engine:base_layer", "//tf_keras/initializers", ], ) py_library( name = "layer_normalization", srcs = ["layer_normalization.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:constraints", "//tf_keras:regularizers", "//tf_keras/dtensor:utils", "//tf_keras/engine:base_layer", "//tf_keras/initializers", ], ) py_library( name = "unit_normalization", srcs = ["unit_normalization.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", ], ) py_library( name = "spectral_normalization", srcs = ["spectral_normalization.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", ], ) cuda_py_test( name = "group_normalization_test", size = "medium", srcs = ["group_normalization_test.py"], python_version = "PY3", shard_count = 4, tags = [ "notsan", ], xla_tags = [ "no_cuda_asan", # times out ], deps = [ ":group_normalization", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/layers", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) cuda_py_test( name = "batch_normalization_test", size = "medium", srcs = ["batch_normalization_test.py"], python_version = "PY3", shard_count = 4, tags = [ "notsan", ], deps = [ ":batch_normalization", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/layers", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "batch_normalization_dtensor_test", srcs = ["batch_normalization_dtensor_test.py"], shard_count = 2, tags = ["no_oss"], deps = [ ":batch_normalization", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/dtensor:test_util", "//tf_keras/testing_infra:test_utils", "//third_party/tensorflow/python/distribute/experimental:mirrored_strategy", ], ) cuda_py_test( name = "layer_normalization_test", size = "medium", srcs = ["layer_normalization_test.py"], python_version = "PY3", shard_count = 4, tags = [ "notsan", ], deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) cuda_py_test( name = "unit_normalization_test", size = "small", srcs = ["unit_normalization_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) cuda_py_test( name = "spectral_normalization_test", size = "small", srcs = ["spectral_normalization_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], )
tf-keras/tf_keras/layers/normalization/BUILD/0
{ "file_path": "tf-keras/tf_keras/layers/normalization/BUILD", "repo_id": "tf-keras", "token_count": 2692 }
188
# 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. # ============================================================================== """Average pooling 1D layer.""" import functools from tf_keras import backend from tf_keras.layers.pooling.base_pooling1d import Pooling1D # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.AveragePooling1D", "keras.layers.AvgPool1D") class AveragePooling1D(Pooling1D): """Average pooling for temporal data. Downsamples the input representation by taking the average value over the window defined by `pool_size`. The window is shifted by `strides`. The resulting output when using "valid" padding option has a shape of: `output_shape = (input_shape - pool_size + 1) / strides)` The resulting output shape when using the "same" padding option is: `output_shape = input_shape / strides` For example, for strides=1 and padding="valid": >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> x <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[1.], [2.], [3.], [4.], [5.]], dtype=float32)> >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding='valid') >>> avg_pool_1d(x) <tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy= array([[[1.5], [2.5], [3.5], [4.5]]], dtype=float32)> For example, for strides=2 and padding="valid": >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> x <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[1.], [2.], [3.], [4.], [5.]], dtype=float32)> >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, ... strides=2, padding='valid') >>> avg_pool_1d(x) <tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy= array([[[1.5], [3.5]]], dtype=float32)> For example, for strides=1 and padding="same": >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> x <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[1.], [2.], [3.], [4.], [5.]], dtype=float32)> >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, ... strides=1, padding='same') >>> avg_pool_1d(x) <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[1.5], [2.5], [3.5], [4.5], [5.]]], dtype=float32)> Args: pool_size: Integer, size of the average pooling windows. strides: Integer, or None. Factor by which to downscale. E.g. 2 will halve the input. If None, it will default to `pool_size`. padding: One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, steps, features)` while `channels_first` corresponds to inputs with shape `(batch, features, steps)`. Input shape: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, steps, features)`. - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, steps)`. Output shape: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, downsampled_steps, features)`. - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, downsampled_steps)`. """ def __init__( self, pool_size=2, strides=None, padding="valid", data_format="channels_last", **kwargs ): super().__init__( functools.partial(backend.pool2d, pool_mode="avg"), pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs ) # Alias AvgPool1D = AveragePooling1D
tf-keras/tf_keras/layers/pooling/average_pooling1d.py/0
{ "file_path": "tf-keras/tf_keras/layers/pooling/average_pooling1d.py", "repo_id": "tf-keras", "token_count": 2184 }
189
# Copyright 2019 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. # ============================================================================== """Distribution tests for keras.layers.preprocessing.category_encoding.""" import numpy as np import tensorflow.compat.v2 as tf import tf_keras as keras from tf_keras import backend from tf_keras.distribute import strategy_combinations from tf_keras.layers.preprocessing import category_encoding from tf_keras.layers.preprocessing import preprocessing_test_utils from tf_keras.testing_infra import test_combinations from tf_keras.testing_infra import test_utils # isort: off from tensorflow.python.framework import ( test_util as tf_test_utils, ) def batch_wrapper(dataset, batch_size, strategy, repeat=None): if repeat: dataset = dataset.repeat(repeat) # TPUs currently require fully defined input shapes, drop_remainder ensures # the input will have fully defined shapes. if backend.is_tpu_strategy(strategy): return dataset.batch(batch_size, drop_remainder=True) else: return dataset.batch(batch_size) @test_utils.run_v2_only @tf.__internal__.distribute.combinations.generate( tf.__internal__.test.combinations.combine( strategy=strategy_combinations.all_strategies + strategy_combinations.multi_worker_mirrored_strategies + strategy_combinations.parameter_server_strategies_single_worker + strategy_combinations.parameter_server_strategies_multi_worker, mode=["eager"], ) ) class CategoryEncodingDistributionTest( test_combinations.TestCase, preprocessing_test_utils.PreprocessingLayerTest ): def test_strategy(self, strategy): if ( backend.is_tpu_strategy(strategy) and not tf_test_utils.is_mlir_bridge_enabled() ): self.skipTest("TPU tests require MLIR bridge") input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]]) inp_dataset = tf.data.Dataset.from_tensor_slices(input_array) inp_dataset = batch_wrapper(inp_dataset, 2, strategy) # pyformat: disable expected_output = [[0, 1, 1, 1, 0, 0], [1, 1, 0, 1, 0, 0]] # pyformat: enable num_tokens = 6 tf.config.set_soft_device_placement(True) with strategy.scope(): input_data = keras.Input(shape=(4,), dtype=tf.int32) layer = category_encoding.CategoryEncoding( num_tokens=num_tokens, output_mode=category_encoding.MULTI_HOT ) int_data = layer(input_data) model = keras.Model(inputs=input_data, outputs=int_data) output_dataset = model.predict(inp_dataset) self.assertAllEqual(expected_output, output_dataset) if __name__ == "__main__": tf.__internal__.distribute.multi_process_runner.test_main()
tf-keras/tf_keras/layers/preprocessing/category_encoding_distribution_test.py/0
{ "file_path": "tf-keras/tf_keras/layers/preprocessing/category_encoding_distribution_test.py", "repo_id": "tf-keras", "token_count": 1261 }
190
# Copyright 2020 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. # ============================================================================== """Keras string lookup preprocessing layer.""" import numpy as np import tensorflow.compat.v2 as tf from tf_keras.layers.preprocessing import index_lookup # isort: off from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export @keras_export( "keras.layers.IntegerLookup", "keras.layers.experimental.preprocessing.IntegerLookup", v1=[], ) class IntegerLookup(index_lookup.IndexLookup): """A preprocessing layer which maps integer features to contiguous ranges. This layer maps a set of arbitrary integer input tokens into indexed integer output via a table-based vocabulary lookup. The layer's output indices will be contiguously arranged up to the maximum vocab size, even if the input tokens are non-continguous or unbounded. The layer supports multiple options for encoding the output via `output_mode`, and has optional support for out-of-vocabulary (OOV) tokens and masking. The vocabulary for the layer must be either supplied on construction or learned via `adapt()`. During `adapt()`, the layer will analyze a data set, determine the frequency of individual integer tokens, and create a vocabulary from them. If the vocabulary is capped in size, the most frequent tokens will be used to create the vocabulary and all others will be treated as OOV. There are two possible output modes for the layer. When `output_mode` is `"int"`, input integers are converted to their index in the vocabulary (an integer). When `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"`, input integers are encoded into an array where each dimension corresponds to an element in the vocabulary. The vocabulary can optionally contain a mask token as well as an OOV token (which can optionally occupy multiple indices in the vocabulary, as set by `num_oov_indices`). The position of these tokens in the vocabulary is fixed. When `output_mode` is `"int"`, the vocabulary will begin with the mask token at index 0, followed by OOV indices, followed by the rest of the vocabulary. When `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"` the vocabulary will begin with OOV indices and instances of the mask token will be dropped. For an overview and full list of preprocessing layers, see the preprocessing [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers). Args: max_tokens: Maximum size of the vocabulary for this layer. This should only be specified when adapting the vocabulary or when setting `pad_to_max_tokens=True`. If None, there is no cap on the size of the vocabulary. Note that this size includes the OOV and mask tokens. Defaults to `None`. num_oov_indices: The number of out-of-vocabulary tokens to use. If this value is more than 1, OOV inputs are modulated to determine their OOV value. If this value is 0, OOV inputs will cause an error when calling the layer. Defaults to `1`. mask_token: An integer token that represents masked inputs. When `output_mode` is `"int"`, the token is included in vocabulary and mapped to index 0. In other output modes, the token will not appear in the vocabulary and instances of the mask token in the input will be dropped. If set to None, no mask term will be added. Defaults to `None`. oov_token: Only used when `invert` is True. The token to return for OOV indices. Defaults to `-1`. vocabulary: Optional. Either an array of integers or a string path to a text file. If passing an array, can pass a tuple, list, 1D numpy array, or 1D tensor containing the integer vocbulary terms. If passing a file path, the file should contain one line per term in the vocabulary. If this argument is set, there is no need to `adapt()` the layer. vocabulary_dtype: The dtype of the vocabulary terms, for example `"int64"` or `"int32"`. Defaults to `"int64"`. idf_weights: Only valid when `output_mode` is `"tf_idf"`. A tuple, list, 1D numpy array, or 1D tensor or the same length as the vocabulary, containing the floating point inverse document frequency weights, which will be multiplied by per sample term counts for the final `tf_idf` weight. If the `vocabulary` argument is set, and `output_mode` is `"tf_idf"`, this argument must be supplied. invert: Only valid when `output_mode` is `"int"`. If True, this layer will map indices to vocabulary items instead of mapping vocabulary items to indices. Defaults to `False`. output_mode: Specification for the output of the layer. Values can be `"int"`, `"one_hot"`, `"multi_hot"`, `"count"`, or `"tf_idf"` configuring the layer as follows: - `"int"`: Return the vocabulary indices of the input tokens. - `"one_hot"`: Encodes each individual element in the input into an array the same size as the vocabulary, containing a 1 at the element index. If the last dimension is size 1, will encode on that dimension. If the last dimension is not size 1, will append a new dimension for the encoded output. - `"multi_hot"`: Encodes each sample in the input into a single array the same size as the vocabulary, containing a 1 for each vocabulary term present in the sample. Treats the last dimension as the sample dimension, if input shape is (..., sample_length), output shape will be (..., num_tokens). - `"count"`: As `"multi_hot"`, but the int array contains a count of the number of times the token at that index appeared in the sample. - `"tf_idf"`: As `"multi_hot"`, but the TF-IDF algorithm is applied to find the value in each token slot. For `"int"` output, any shape of input and output is supported. For all other output modes, currently only output up to rank 2 is supported. Defaults to `"int"`. pad_to_max_tokens: Only applicable when `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"`. If True, the output will have its feature axis padded to `max_tokens` even if the number of unique tokens in the vocabulary is less than max_tokens, resulting in a tensor of shape [batch_size, max_tokens] regardless of vocabulary size. Defaults to False. sparse: Boolean. Only applicable when `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"`. If True, returns a `SparseTensor` instead of a dense `Tensor`. Defaults to `False`. Examples: **Creating a lookup layer with a known vocabulary** This example creates a lookup layer with a pre-existing vocabulary. >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup(vocabulary=vocab) >>> layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[1, 3, 4], [4, 0, 2]])> **Creating a lookup layer with an adapted vocabulary** This example creates a lookup layer and generates the vocabulary by analyzing the dataset. >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) >>> layer = tf.keras.layers.IntegerLookup() >>> layer.adapt(data) >>> layer.get_vocabulary() [-1, 42, 1138, 1000, 36, 12] Note that the OOV token -1 have been added to the vocabulary. The remaining tokens are sorted by frequency (42, which has 2 occurrences, is first) then by inverse sort order. >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) >>> layer = tf.keras.layers.IntegerLookup() >>> layer.adapt(data) >>> layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[5, 2, 1], [1, 3, 4]])> **Lookups with multiple OOV indices** This example demonstrates how to use a lookup layer with multiple OOV indices. When a layer is created with more than one OOV index, any OOV tokens are hashed into the number of OOV buckets, distributing OOV tokens in a deterministic fashion across the set. >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[12, 1138, 42], [37, 1000, 36]]) >>> layer = tf.keras.layers.IntegerLookup( ... vocabulary=vocab, num_oov_indices=2) >>> layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[2, 4, 5], [1, 0, 3]])> Note that the output for OOV token 37 is 1, while the output for OOV token 1000 is 0. The in-vocab terms have their output index increased by 1 from earlier examples (12 maps to 2, etc) in order to make space for the extra OOV token. **One-hot output** Configure the layer with `output_mode='one_hot'`. Note that the first `num_oov_indices` dimensions in the one_hot encoding represent OOV values. >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([12, 36, 1138, 42, 7]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup( ... vocabulary=vocab, output_mode='one_hot') >>> layer(data) <tf.Tensor: shape=(5, 5), dtype=float32, numpy= array([[0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0., 0.]], dtype=float32)> **Multi-hot output** Configure the layer with `output_mode='multi_hot'`. Note that the first `num_oov_indices` dimensions in the multi_hot encoding represent OOV tokens >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[12, 1138, 42, 42], ... [42, 7, 36, 7]]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup( ... vocabulary=vocab, output_mode='multi_hot') >>> layer(data) <tf.Tensor: shape=(2, 5), dtype=float32, numpy= array([[0., 1., 0., 1., 1.], [1., 0., 1., 0., 1.]], dtype=float32)> **Token count output** Configure the layer with `output_mode='count'`. As with multi_hot output, the first `num_oov_indices` dimensions in the output represent OOV tokens. >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[12, 1138, 42, 42], ... [42, 7, 36, 7]]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup( ... vocabulary=vocab, output_mode='count') >>> layer(data) <tf.Tensor: shape=(2, 5), dtype=float32, numpy= array([[0., 1., 0., 1., 2.], [2., 0., 1., 0., 1.]], dtype=float32)> **TF-IDF output** Configure the layer with `output_mode='tf_idf'`. As with multi_hot output, the first `num_oov_indices` dimensions in the output represent OOV tokens. Each token bin will output `token_count * idf_weight`, where the idf weights are the inverse document frequency weights per token. These should be provided along with the vocabulary. Note that the `idf_weight` for OOV tokens will default to the average of all idf weights passed in. >>> vocab = [12, 36, 1138, 42] >>> idf_weights = [0.25, 0.75, 0.6, 0.4] >>> data = tf.constant([[12, 1138, 42, 42], ... [42, 7, 36, 7]]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup( ... output_mode='tf_idf', vocabulary=vocab, idf_weights=idf_weights) >>> layer(data) <tf.Tensor: shape=(2, 5), dtype=float32, numpy= array([[0. , 0.25, 0. , 0.6 , 0.8 ], [1.0 , 0. , 0.75, 0. , 0.4 ]], dtype=float32)> To specify the idf weights for oov tokens, you will need to pass the entire vocabularly including the leading oov token. >>> vocab = [-1, 12, 36, 1138, 42] >>> idf_weights = [0.9, 0.25, 0.75, 0.6, 0.4] >>> data = tf.constant([[12, 1138, 42, 42], ... [42, 7, 36, 7]]) # Note OOV tokens >>> layer = tf.keras.layers.IntegerLookup( ... output_mode='tf_idf', vocabulary=vocab, idf_weights=idf_weights) >>> layer(data) <tf.Tensor: shape=(2, 5), dtype=float32, numpy= array([[0. , 0.25, 0. , 0.6 , 0.8 ], [1.8 , 0. , 0.75, 0. , 0.4 ]], dtype=float32)> When adapting the layer in tf_idf mode, each input sample will be considered a document, and idf weight per token will be calculated as `log(1 + num_documents / (1 + token_document_count))`. **Inverse lookup** This example demonstrates how to map indices to tokens using this layer. (You can also use `adapt()` with `inverse=True`, but for simplicity we'll pass the vocab in this example.) >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[1, 3, 4], [4, 0, 2]]) >>> layer = tf.keras.layers.IntegerLookup(vocabulary=vocab, invert=True) >>> layer(data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[ 12, 1138, 42], [ 42, -1, 36]])> Note that the first index correspond to the oov token by default. **Forward and inverse lookup pairs** This example demonstrates how to use the vocabulary of a standard lookup layer to create an inverse lookup layer. >>> vocab = [12, 36, 1138, 42] >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) >>> layer = tf.keras.layers.IntegerLookup(vocabulary=vocab) >>> i_layer = tf.keras.layers.IntegerLookup( ... vocabulary=layer.get_vocabulary(), invert=True) >>> int_data = layer(data) >>> i_layer(int_data) <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[ 12, 1138, 42], [ 42, -1, 36]])> In this example, the input token 1000 resulted in an output of -1, since 1000 was not in the vocabulary - it got represented as an OOV, and all OOV tokens are returned as -1 in the inverse layer. Also, note that for the inverse to work, you must have already set the forward layer vocabulary either directly or via `adapt()` before calling `get_vocabulary()`. """ def __init__( self, max_tokens=None, num_oov_indices=1, mask_token=None, oov_token=-1, vocabulary=None, vocabulary_dtype="int64", idf_weights=None, invert=False, output_mode="int", sparse=False, pad_to_max_tokens=False, **kwargs, ): if not tf.dtypes.as_dtype(vocabulary_dtype).is_integer: raise ValueError( "`vocabulary_dtype` must be an integer dtype. " f"Received: {vocabulary_dtype}" ) # Legacy versions of the IntegerLookup layer set layer dtype to int64, # instead of the output type. If we see this and output mode is not # "int", clear the setting so we don't switch types for old SavedModels. if ( output_mode != "int" and "dtype" in kwargs and (kwargs["dtype"] == tf.int64 or kwargs["dtype"] == "int64") ): del kwargs["dtype"] # Support deprecated args for this layer. if "max_values" in kwargs: logging.log_first_n( logging.WARN, "max_values is deprecated, use max_tokens instead.", 1, ) max_tokens = kwargs["max_values"] del kwargs["max_values"] if "mask_value" in kwargs: logging.log_first_n( logging.WARN, "mask_value is deprecated, use mask_token instead.", 1, ) mask_token = kwargs["mask_value"] del kwargs["mask_value"] if "oov_value" in kwargs: logging.log_first_n( logging.WARN, "oov_value is deprecated, use oov_token instead.", 1, ) oov_token = kwargs["oov_value"] del kwargs["oov_value"] # If max_tokens is set, the token must be greater than 1 - otherwise we # are creating a 0-element vocab, which doesn't make sense. if max_tokens is not None and max_tokens <= 1: raise ValueError( "If `max_tokens` is set for `IntegerLookup`, it must be " f"greater than 1. Received: max_tokens={max_tokens}." ) if num_oov_indices < 0: raise ValueError( "The value of `num_oov_indices` argument for `IntegerLookup` " "must >= 0. Received num_oov_indices=" f"{num_oov_indices}." ) # Make sure mask and oov are of the dtype we want. mask_token = None if mask_token is None else np.int64(mask_token) oov_token = None if oov_token is None else np.int64(oov_token) super().__init__( max_tokens=max_tokens, num_oov_indices=num_oov_indices, mask_token=mask_token, oov_token=oov_token, vocabulary=vocabulary, vocabulary_dtype=vocabulary_dtype, idf_weights=idf_weights, invert=invert, output_mode=output_mode, sparse=sparse, pad_to_max_tokens=pad_to_max_tokens, **kwargs, ) # We override this method solely to generate a docstring. def adapt(self, data, batch_size=None, steps=None): """Computes a vocabulary of interger terms from tokens in a dataset. Calling `adapt()` on an `IntegerLookup` layer is an alternative to passing in a precomputed vocabulary on construction via the `vocabulary` argument. An `IntegerLookup` layer should always be either adapted over a dataset or supplied with a vocabulary. During `adapt()`, the layer will build a vocabulary of all integer tokens seen in the dataset, sorted by occurrence count, with ties broken by sort order of the tokens (high to low). At the end of `adapt()`, if `max_tokens` is set, the vocabulary wil be truncated to `max_tokens` size. For example, adapting a layer with `max_tokens=1000` will compute the 1000 most frequent tokens occurring in the input dataset. If `output_mode='tf-idf'`, `adapt()` will also learn the document frequencies of each token in the input dataset. In order to make `StringLookup` efficient in any distribution context, the vocabulary is kept static with respect to any compiled `tf.Graph`s that call the layer. As a consequence, if the layer is adapted a second time, any models using the layer should be re-compiled. For more information see `tf.keras.layers.experimental.preprocessing.PreprocessingLayer.adapt`. `adapt()` is meant only as a single machine utility to compute layer state. To analyze a dataset that cannot fit on a single machine, see [Tensorflow Transform]( https://www.tensorflow.org/tfx/transform/get_started) for a multi-machine, map-reduce solution. Arguments: data: The data to train on. It can be passed either as a `tf.data.Dataset`, or as a numpy array. batch_size: Integer or `None`. Number of samples per state update. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of datasets, generators, or `keras.utils.Sequence` instances (since they generate batches). steps: Integer or `None`. Total number of steps (batches of samples) When training with input tensors such as TensorFlow data tensors, the default `None` is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a `tf.data` dataset, and 'steps' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the `steps` argument. This argument is not supported with array inputs. """ super().adapt(data, batch_size=batch_size, steps=steps)
tf-keras/tf_keras/layers/preprocessing/integer_lookup.py/0
{ "file_path": "tf-keras/tf_keras/layers/preprocessing/integer_lookup.py", "repo_id": "tf-keras", "token_count": 8219 }
191
# Description: # Contains the TF-Keras regularization layers. # Placeholder: load unaliased py_library load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test") package( # copybara:uncomment default_applicable_licenses = ["//tf_keras:license"], default_visibility = [ "//tf_keras:friends", "//third_party/py/tensorflow_gnn:__subpackages__", "//third_party/tensorflow/python/distribute:__pkg__", "//third_party/tensorflow/python/feature_column:__pkg__", "//third_party/tensorflow/python/trackable:__pkg__", "//third_party/tensorflow/tools/pip_package:__pkg__", "//third_party/tensorflow_models/official/projects/residual_mobilenet/modeling/backbones:__pkg__", ], licenses = ["notice"], ) py_library( name = "regularization", srcs = ["__init__.py"], srcs_version = "PY3", deps = [ ":activity_regularization", ":alpha_dropout", ":dropout", ":gaussian_dropout", ":gaussian_noise", ":spatial_dropout1d", ":spatial_dropout2d", ":spatial_dropout3d", ], ) py_library( name = "dropout", srcs = ["dropout.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/utils:control_flow_util", ], ) py_library( name = "spatial_dropout1d", srcs = ["spatial_dropout1d.py"], srcs_version = "PY3", deps = [ ":dropout", "//:expect_tensorflow_installed", "//tf_keras/engine:input_spec", ], ) py_library( name = "spatial_dropout2d", srcs = ["spatial_dropout2d.py"], srcs_version = "PY3", deps = [ ":dropout", "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:input_spec", ], ) py_library( name = "spatial_dropout3d", srcs = ["spatial_dropout3d.py"], srcs_version = "PY3", deps = [ ":dropout", "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:input_spec", ], ) py_library( name = "gaussian_dropout", srcs = ["gaussian_dropout.py"], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/utils:tf_utils", ], ) py_library( name = "gaussian_noise", srcs = ["gaussian_noise.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/utils:tf_utils", ], ) py_library( name = "activity_regularization", srcs = ["activity_regularization.py"], srcs_version = "PY3", deps = [ "//tf_keras:regularizers", "//tf_keras/engine:base_layer", ], ) py_library( name = "alpha_dropout", srcs = ["alpha_dropout.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/utils:tf_utils", ], ) tf_py_test( name = "dropout_test", size = "medium", srcs = ["dropout_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "spatial_dropout_test", size = "medium", srcs = ["spatial_dropout_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "gaussian_dropout_test", size = "medium", srcs = ["gaussian_dropout_test.py"], python_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "gaussian_noise_test", size = "medium", srcs = ["gaussian_noise_test.py"], python_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "activity_regularization_test", size = "medium", srcs = ["activity_regularization_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "alpha_dropout_test", size = "medium", srcs = ["alpha_dropout_test.py"], python_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], )
tf-keras/tf_keras/layers/regularization/BUILD/0
{ "file_path": "tf-keras/tf_keras/layers/regularization/BUILD", "repo_id": "tf-keras", "token_count": 2663 }
192
# Description: # Contains the TF-Keras reshaping layers. # Placeholder: load unaliased py_library load("@org_keras//tf_keras:tf_keras.bzl", "cuda_py_test") # buildifier: disable=same-origin-load load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test") package( # copybara:uncomment default_applicable_licenses = ["//tf_keras:license"], default_visibility = [ "//tf_keras:__subpackages__", "//third_party/tensorflow/python/distribute:__pkg__", "//third_party/tensorflow/python/feature_column:__pkg__", "//third_party/tensorflow/python/trackable:__pkg__", "//third_party/tensorflow/tools/pip_package:__pkg__", "//third_party/tensorflow_models/official/projects/residual_mobilenet/modeling/backbones:__pkg__", ], licenses = ["notice"], ) py_library( name = "reshaping", srcs = [ "__init__.py", ], srcs_version = "PY3", deps = [ ":cropping1d", ":cropping2d", ":cropping3d", ":flatten", ":permute", ":repeat_vector", ":reshape", ":up_sampling1d", ":up_sampling2d", ":up_sampling3d", ":zero_padding1d", ":zero_padding2d", ":zero_padding3d", ], ) py_library( name = "cropping1d", srcs = ["cropping1d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "cropping2d", srcs = ["cropping2d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "cropping3d", srcs = ["cropping3d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "flatten", srcs = ["flatten.py"], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "permute", srcs = ["permute.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", ], ) py_library( name = "repeat_vector", srcs = ["repeat_vector.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", ], ) py_library( name = "reshape", srcs = ["reshape.py"], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/engine:base_layer", ], ) py_library( name = "up_sampling1d", srcs = ["up_sampling1d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", ], ) py_library( name = "up_sampling2d", srcs = ["up_sampling2d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "up_sampling3d", srcs = ["up_sampling3d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "zero_padding1d", srcs = ["zero_padding1d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "zero_padding2d", srcs = ["zero_padding2d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) py_library( name = "zero_padding3d", srcs = ["zero_padding3d.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/engine:base_layer", "//tf_keras/engine:input_spec", "//tf_keras/utils:engine_utils", ], ) cuda_py_test( name = "cropping_test", size = "medium", srcs = ["cropping_test.py"], python_version = "PY3", shard_count = 8, deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "flatten_test", size = "medium", srcs = ["flatten_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "permute_test", size = "medium", srcs = ["permute_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "repeat_vector_test", size = "medium", srcs = ["repeat_vector_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "reshape_test", size = "medium", srcs = ["reshape_test.py"], python_version = "PY3", shard_count = 3, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) cuda_py_test( name = "up_sampling_test", size = "medium", srcs = ["up_sampling_test.py"], python_version = "PY3", shard_count = 8, deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) cuda_py_test( name = "zero_padding_test", size = "medium", srcs = ["zero_padding_test.py"], python_version = "PY3", shard_count = 8, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], )
tf-keras/tf_keras/layers/reshaping/BUILD/0
{ "file_path": "tf-keras/tf_keras/layers/reshaping/BUILD", "repo_id": "tf-keras", "token_count": 3915 }
193
# 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. # ============================================================================== """Keras upsampling layer for 3D inputs.""" import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras.engine.base_layer import Layer from tf_keras.engine.input_spec import InputSpec from tf_keras.utils import conv_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.UpSampling3D") class UpSampling3D(Layer): """Upsampling layer for 3D inputs. Repeats the 1st, 2nd and 3rd dimensions of the data by `size[0]`, `size[1]` and `size[2]` respectively. Examples: >>> input_shape = (2, 1, 2, 1, 3) >>> x = tf.constant(1, shape=input_shape) >>> y = tf.keras.layers.UpSampling3D(size=2)(x) >>> print(y.shape) (2, 2, 4, 2, 3) Args: size: Int, or tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. When unspecified, uses `image_data_format` value found in your TF-Keras config file at `~/.keras/keras.json` (if exists) else 'channels_last'. Defaults to 'channels_last'. Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, dim1, dim2, dim3, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, dim1, dim2, dim3)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` """ def __init__(self, size=(2, 2, 2), data_format=None, **kwargs): self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 3, "size") self.input_spec = InputSpec(ndim=5) super().__init__(**kwargs) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == "channels_first": dim1 = ( self.size[0] * input_shape[2] if input_shape[2] is not None else None ) dim2 = ( self.size[1] * input_shape[3] if input_shape[3] is not None else None ) dim3 = ( self.size[2] * input_shape[4] if input_shape[4] is not None else None ) return tf.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3] ) else: dim1 = ( self.size[0] * input_shape[1] if input_shape[1] is not None else None ) dim2 = ( self.size[1] * input_shape[2] if input_shape[2] is not None else None ) dim3 = ( self.size[2] * input_shape[3] if input_shape[3] is not None else None ) return tf.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]] ) def call(self, inputs): return backend.resize_volumes( inputs, self.size[0], self.size[1], self.size[2], self.data_format ) def get_config(self): config = {"size": self.size, "data_format": self.data_format} base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
tf-keras/tf_keras/layers/reshaping/up_sampling3d.py/0
{ "file_path": "tf-keras/tf_keras/layers/reshaping/up_sampling3d.py", "repo_id": "tf-keras", "token_count": 2150 }
194
# 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. # ============================================================================== """Bidirectional wrapper for RNNs.""" import copy import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras.engine.base_layer import Layer from tf_keras.engine.input_spec import InputSpec from tf_keras.layers.rnn import rnn_utils from tf_keras.layers.rnn.base_wrapper import Wrapper from tf_keras.saving import serialization_lib from tf_keras.utils import generic_utils from tf_keras.utils import tf_inspect from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.layers.Bidirectional") class Bidirectional(Wrapper): """Bidirectional wrapper for RNNs. Args: layer: `keras.layers.RNN` instance, such as `keras.layers.LSTM` or `keras.layers.GRU`. It could also be a `keras.layers.Layer` instance that meets the following criteria: 1. Be a sequence-processing layer (accepts 3D+ inputs). 2. Have a `go_backwards`, `return_sequences` and `return_state` attribute (with the same semantics as for the `RNN` class). 3. Have an `input_spec` attribute. 4. Implement serialization via `get_config()` and `from_config()`. Note that the recommended way to create new RNN layers is to write a custom RNN cell and use it with `keras.layers.RNN`, instead of subclassing `keras.layers.Layer` directly. - When the `returns_sequences` is true, the output of the masked timestep will be zero regardless of the layer's original `zero_output_for_mask` value. merge_mode: Mode by which outputs of the forward and backward RNNs will be combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the outputs will not be combined, they will be returned as a list. Default value is 'concat'. backward_layer: Optional `keras.layers.RNN`, or `keras.layers.Layer` instance to be used to handle backwards input processing. If `backward_layer` is not provided, the layer instance passed as the `layer` argument will be used to generate the backward layer automatically. Note that the provided `backward_layer` layer should have properties matching those of the `layer` argument, in particular it should have the same values for `stateful`, `return_states`, `return_sequences`, etc. In addition, `backward_layer` and `layer` should have different `go_backwards` argument values. A `ValueError` will be raised if these requirements are not met. Call arguments: The call arguments for this layer are the same as those of the wrapped RNN layer. Beware that when passing the `initial_state` argument during the call of this layer, the first half in the list of elements in the `initial_state` list will be passed to the forward RNN call and the last half in the list of elements will be passed to the backward RNN call. Raises: ValueError: 1. If `layer` or `backward_layer` is not a `Layer` instance. 2. In case of invalid `merge_mode` argument. 3. If `backward_layer` has mismatched properties compared to `layer`. Examples: ```python model = Sequential() model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10))) model.add(Bidirectional(LSTM(10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') # With custom backward layer model = Sequential() forward_layer = LSTM(10, return_sequences=True) backward_layer = LSTM(10, activation='relu', return_sequences=True, go_backwards=True) model.add(Bidirectional(forward_layer, backward_layer=backward_layer, input_shape=(5, 10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') ``` """ def __init__( self, layer, merge_mode="concat", weights=None, backward_layer=None, **kwargs, ): if not isinstance(layer, Layer): raise ValueError( "Please initialize `Bidirectional` layer with a " f"`tf.keras.layers.Layer` instance. Received: {layer}" ) if backward_layer is not None and not isinstance(backward_layer, Layer): raise ValueError( "`backward_layer` need to be a `tf.keras.layers.Layer` " f"instance. Received: {backward_layer}" ) if merge_mode not in ["sum", "mul", "ave", "concat", None]: raise ValueError( f"Invalid merge mode. Received: {merge_mode}. " "Merge mode should be one of " '{"sum", "mul", "ave", "concat", None}' ) # We don't want to track `layer` since we're already tracking the two # copies of it we actually run. self._setattr_tracking = False super().__init__(layer, **kwargs) self._setattr_tracking = True # Recreate the forward layer from the original layer config, so that it # will not carry over any state from the layer. self.forward_layer = self._recreate_layer_from_config(layer) if backward_layer is None: self.backward_layer = self._recreate_layer_from_config( layer, go_backwards=True ) else: self.backward_layer = backward_layer # Keep the custom backward layer config, so that we can save it # later. The layer's name might be updated below with prefix # 'backward_', and we want to preserve the original config. self._backward_layer_config = ( serialization_lib.serialize_keras_object(backward_layer) ) self.forward_layer._name = "forward_" + self.forward_layer.name self.backward_layer._name = "backward_" + self.backward_layer.name self._verify_layer_config() def force_zero_output_for_mask(layer): # Force the zero_output_for_mask to be True if returning sequences. if getattr(layer, "zero_output_for_mask", None) is not None: layer.zero_output_for_mask = layer.return_sequences force_zero_output_for_mask(self.forward_layer) force_zero_output_for_mask(self.backward_layer) self.merge_mode = merge_mode if weights: nw = len(weights) self.forward_layer.initial_weights = weights[: nw // 2] self.backward_layer.initial_weights = weights[nw // 2 :] self.stateful = layer.stateful self.return_sequences = layer.return_sequences self.return_state = layer.return_state self.supports_masking = True self._trainable = kwargs.get("trainable", layer.trainable) self._num_constants = 0 self.input_spec = layer.input_spec @property def _use_input_spec_as_call_signature(self): return self.layer._use_input_spec_as_call_signature def _verify_layer_config(self): """Ensure the forward and backward layers have valid common property.""" if self.forward_layer.go_backwards == self.backward_layer.go_backwards: raise ValueError( "Forward layer and backward layer should have different " "`go_backwards` value." "forward_layer.go_backwards = " f"{self.forward_layer.go_backwards}," "backward_layer.go_backwards = " f"{self.backward_layer.go_backwards}" ) common_attributes = ("stateful", "return_sequences", "return_state") for a in common_attributes: forward_value = getattr(self.forward_layer, a) backward_value = getattr(self.backward_layer, a) if forward_value != backward_value: raise ValueError( "Forward layer and backward layer are expected to have " f'the same value for attribute "{a}", got ' f'"{forward_value}" for forward layer and ' f'"{backward_value}" for backward layer' ) def _recreate_layer_from_config(self, layer, go_backwards=False): # When recreating the layer from its config, it is possible that the # layer is a RNN layer that contains custom cells. In this case we # inspect the layer and pass the custom cell class as part of the # `custom_objects` argument when calling `from_config`. See # https://github.com/tensorflow/tensorflow/issues/26581 for more detail. config = layer.get_config() if go_backwards: config["go_backwards"] = not config["go_backwards"] if ( "custom_objects" in tf_inspect.getfullargspec(layer.__class__.from_config).args ): custom_objects = {} cell = getattr(layer, "cell", None) if cell is not None: custom_objects[cell.__class__.__name__] = cell.__class__ # For StackedRNNCells stacked_cells = getattr(cell, "cells", []) for c in stacked_cells: custom_objects[c.__class__.__name__] = c.__class__ return layer.__class__.from_config( config, custom_objects=custom_objects ) else: return layer.__class__.from_config(config) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): output_shape = self.forward_layer.compute_output_shape(input_shape) if self.return_state: state_shape = tf_utils.convert_shapes( output_shape[1:], to_tuples=False ) output_shape = tf_utils.convert_shapes( output_shape[0], to_tuples=False ) else: output_shape = tf_utils.convert_shapes( output_shape, to_tuples=False ) if self.merge_mode == "concat": output_shape = output_shape.as_list() output_shape[-1] *= 2 output_shape = tf.TensorShape(output_shape) elif self.merge_mode is None: output_shape = [output_shape, copy.copy(output_shape)] if self.return_state: if self.merge_mode is None: return output_shape + state_shape + copy.copy(state_shape) return [output_shape] + state_shape + copy.copy(state_shape) return output_shape def __call__(self, inputs, initial_state=None, constants=None, **kwargs): """`Bidirectional.__call__` implements the same API as the wrapped `RNN`.""" inputs, initial_state, constants = rnn_utils.standardize_args( inputs, initial_state, constants, self._num_constants ) if isinstance(inputs, list): if len(inputs) > 1: initial_state = inputs[1:] inputs = inputs[0] if initial_state is None and constants is None: return super().__call__(inputs, **kwargs) # Applies the same workaround as in `RNN.__call__` additional_inputs = [] additional_specs = [] if initial_state is not None: # Check if `initial_state` can be split into half num_states = len(initial_state) if num_states % 2 > 0: raise ValueError( "When passing `initial_state` to a Bidirectional RNN, " "the state should be a list containing the states of " "the underlying RNNs. " f"Received: {initial_state}" ) kwargs["initial_state"] = initial_state additional_inputs += initial_state state_specs = tf.nest.map_structure( lambda state: InputSpec(shape=backend.int_shape(state)), initial_state, ) self.forward_layer.state_spec = state_specs[: num_states // 2] self.backward_layer.state_spec = state_specs[num_states // 2 :] additional_specs += state_specs if constants is not None: kwargs["constants"] = constants additional_inputs += constants constants_spec = [ InputSpec(shape=backend.int_shape(constant)) for constant in constants ] self.forward_layer.constants_spec = constants_spec self.backward_layer.constants_spec = constants_spec additional_specs += constants_spec self._num_constants = len(constants) self.forward_layer._num_constants = self._num_constants self.backward_layer._num_constants = self._num_constants is_keras_tensor = backend.is_keras_tensor( tf.nest.flatten(additional_inputs)[0] ) for tensor in tf.nest.flatten(additional_inputs): if backend.is_keras_tensor(tensor) != is_keras_tensor: raise ValueError( "The initial state of a Bidirectional" " layer cannot be specified with a mix of" " TF-Keras tensors and non-Keras tensors" ' (a "Keras tensor" is a tensor that was' " returned by a TF-Keras layer, or by `Input`)" ) if is_keras_tensor: # Compute the full input spec, including state full_input = [inputs] + additional_inputs # The original input_spec is None since there could be a nested # tensor input. Update the input_spec to match the inputs. full_input_spec = [ None for _ in range(len(tf.nest.flatten(inputs))) ] + additional_specs # Removing kwargs since the value are passed with input list. kwargs["initial_state"] = None kwargs["constants"] = None # Perform the call with temporarily replaced input_spec original_input_spec = self.input_spec self.input_spec = full_input_spec output = super().__call__(full_input, **kwargs) self.input_spec = original_input_spec return output else: return super().__call__(inputs, **kwargs) def call( self, inputs, training=None, mask=None, initial_state=None, constants=None, ): """`Bidirectional.call` implements the same API as the wrapped `RNN`.""" kwargs = {} if generic_utils.has_arg(self.layer.call, "training"): kwargs["training"] = training if generic_utils.has_arg(self.layer.call, "mask"): kwargs["mask"] = mask if generic_utils.has_arg(self.layer.call, "constants"): kwargs["constants"] = constants if generic_utils.has_arg(self.layer.call, "initial_state"): if isinstance(inputs, list) and len(inputs) > 1: # initial_states are keras tensors, which means they are passed # in together with inputs as list. The initial_states need to be # split into forward and backward section, and be feed to layers # accordingly. forward_inputs = [inputs[0]] backward_inputs = [inputs[0]] pivot = (len(inputs) - self._num_constants) // 2 + 1 # add forward initial state forward_inputs += inputs[1:pivot] if not self._num_constants: # add backward initial state backward_inputs += inputs[pivot:] else: # add backward initial state backward_inputs += inputs[pivot : -self._num_constants] # add constants for forward and backward layers forward_inputs += inputs[-self._num_constants :] backward_inputs += inputs[-self._num_constants :] forward_state, backward_state = None, None if "constants" in kwargs: kwargs["constants"] = None elif initial_state is not None: # initial_states are not keras tensors, eg eager tensor from np # array. They are only passed in from kwarg initial_state, and # should be passed to forward/backward layer via kwarg # initial_state as well. forward_inputs, backward_inputs = inputs, inputs half = len(initial_state) // 2 forward_state = initial_state[:half] backward_state = initial_state[half:] else: forward_inputs, backward_inputs = inputs, inputs forward_state, backward_state = None, None y = self.forward_layer( forward_inputs, initial_state=forward_state, **kwargs ) y_rev = self.backward_layer( backward_inputs, initial_state=backward_state, **kwargs ) else: y = self.forward_layer(inputs, **kwargs) y_rev = self.backward_layer(inputs, **kwargs) if self.return_state: states = y[1:] + y_rev[1:] y = y[0] y_rev = y_rev[0] if self.return_sequences: time_dim = ( 0 if getattr(self.forward_layer, "time_major", False) else 1 ) y_rev = backend.reverse(y_rev, time_dim) if self.merge_mode == "concat": output = backend.concatenate([y, y_rev]) elif self.merge_mode == "sum": output = y + y_rev elif self.merge_mode == "ave": output = (y + y_rev) / 2 elif self.merge_mode == "mul": output = y * y_rev elif self.merge_mode is None: output = [y, y_rev] else: raise ValueError( "Unrecognized value for `merge_mode`. " f"Received: {self.merge_mode}" 'Expected values are ["concat", "sum", "ave", "mul"]' ) if self.return_state: if self.merge_mode is None: return output + states return [output] + states return output def reset_states(self, states=None): if not self.stateful: raise AttributeError("Layer must be stateful.") if states is None: self.forward_layer.reset_states() self.backward_layer.reset_states() else: if not isinstance(states, (list, tuple)): raise ValueError( "Unrecognized value for `states`. " "Expected `states` to be list or tuple. " f"Received: {states}" ) half = len(states) // 2 self.forward_layer.reset_states(states[:half]) self.backward_layer.reset_states(states[half:]) def build(self, input_shape): with backend.name_scope(self.forward_layer.name): self.forward_layer.build(input_shape) with backend.name_scope(self.backward_layer.name): self.backward_layer.build(input_shape) self.built = True def compute_mask(self, inputs, mask): if isinstance(mask, list): mask = mask[0] if self.return_sequences: if not self.merge_mode: output_mask = [mask, mask] else: output_mask = mask else: output_mask = [None, None] if not self.merge_mode else None if self.return_state: states = self.forward_layer.states state_mask = [None for _ in states] if isinstance(output_mask, list): return output_mask + state_mask * 2 return [output_mask] + state_mask * 2 return output_mask @property def constraints(self): constraints = {} if hasattr(self.forward_layer, "constraints"): constraints.update(self.forward_layer.constraints) constraints.update(self.backward_layer.constraints) return constraints def get_config(self): config = {"merge_mode": self.merge_mode} if self._num_constants: config["num_constants"] = self._num_constants if hasattr(self, "_backward_layer_config"): config["backward_layer"] = self._backward_layer_config base_config = super().get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): # Instead of updating the input, create a copy and use that. config = copy.deepcopy(config) num_constants = config.pop("num_constants", 0) # Handle forward layer instantiation (as would parent class). from tf_keras.layers import deserialize as deserialize_layer config["layer"] = deserialize_layer( config["layer"], custom_objects=custom_objects ) # Handle (optional) backward layer instantiation. backward_layer_config = config.pop("backward_layer", None) if backward_layer_config is not None: backward_layer = deserialize_layer( backward_layer_config, custom_objects=custom_objects ) config["backward_layer"] = backward_layer # Instantiate the wrapper, adjust it and return it. layer = cls(**config) layer._num_constants = num_constants return layer
tf-keras/tf_keras/layers/rnn/bidirectional.py/0
{ "file_path": "tf-keras/tf_keras/layers/rnn/bidirectional.py", "repo_id": "tf-keras", "token_count": 10150 }
195
# Copyright 2016 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 layer serialization utils.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import tf_keras as keras from tf_keras.layers.normalization import batch_normalization as batchnorm_v2 from tf_keras.layers.normalization import batch_normalization_v1 as batchnorm_v1 from tf_keras.layers.rnn import gru from tf_keras.layers.rnn import gru_v1 from tf_keras.layers.rnn import lstm from tf_keras.layers.rnn import lstm_v1 from tf_keras.metrics import Mean from tf_keras.testing_infra import test_combinations class SerializableInt(int): def __new__(cls, value): return int.__new__(cls, value) def get_config(self): return {"value": int(self)} @classmethod def from_config(cls, config): return cls(**config) @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class LayerSerializationTest(parameterized.TestCase, tf.test.TestCase): def test_serialize_deserialize(self): layer = keras.layers.Dense( 3, activation="relu", kernel_initializer="ones", bias_regularizer="l2", ) config = keras.layers.serialize(layer) new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.activation, keras.activations.relu) self.assertEqual( new_layer.bias_regularizer.__class__, keras.regularizers.L2 ) if tf.__internal__.tf2.enabled(): self.assertEqual( new_layer.kernel_initializer.__class__, keras.initializers.OnesV2, ) else: self.assertEqual( new_layer.kernel_initializer.__class__, keras.initializers.Ones ) self.assertEqual(new_layer.units, 3) def test_implicit_serialize_deserialize_fails_without_object(self): # After discussion (rchao, nkovela) decided to exclude from new saving if tf.__internal__.tf2.enabled(): self.skipTest("Test excluded from new saving format.") layer = keras.layers.Dense( SerializableInt(3), activation="relu", kernel_initializer="ones", bias_regularizer="l2", ) config = keras.layers.serialize(layer) # Because we're passing an unknown class here, deserialization should # fail unless we add SerializableInt to the custom object dict. with self.assertRaisesRegex( ValueError, "Unknown config_item: 'SerializableInt.*" ): _ = keras.layers.deserialize(config) def test_implicit_serialize_deserialize_succeeds_with_object(self): layer = keras.layers.Dense( SerializableInt(3), activation="relu", kernel_initializer="ones", bias_regularizer="l2", ) config = keras.layers.serialize(layer) # Because we're passing an unknown class here, deserialization should # fail unless we add SerializableInt to the custom object dict. new_layer = keras.layers.deserialize( config, custom_objects={"SerializableInt": SerializableInt} ) self.assertEqual(new_layer.activation, keras.activations.relu) self.assertEqual( new_layer.bias_regularizer.__class__, keras.regularizers.L2 ) if tf.__internal__.tf2.enabled(): self.assertEqual( new_layer.kernel_initializer.__class__, keras.initializers.OnesV2, ) else: self.assertEqual( new_layer.kernel_initializer.__class__, keras.initializers.Ones ) self.assertEqual(new_layer.units.__class__, SerializableInt) self.assertEqual(new_layer.units, 3) @parameterized.parameters( [batchnorm_v1.BatchNormalization, batchnorm_v2.BatchNormalization] ) def test_serialize_deserialize_batchnorm(self, batchnorm_layer): layer = batchnorm_layer( momentum=0.9, beta_initializer="zeros", gamma_regularizer="l2" ) config = keras.layers.serialize(layer) self.assertEqual(config["class_name"], "BatchNormalization") new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.momentum, 0.9) if tf.__internal__.tf2.enabled(): self.assertIsInstance(new_layer, batchnorm_v2.BatchNormalization) self.assertEqual( new_layer.beta_initializer.__class__, keras.initializers.ZerosV2 ) else: self.assertIsInstance(new_layer, batchnorm_v1.BatchNormalization) self.assertEqual( new_layer.beta_initializer.__class__, keras.initializers.Zeros ) self.assertEqual( new_layer.gamma_regularizer.__class__, keras.regularizers.L2 ) @parameterized.parameters( [batchnorm_v1.BatchNormalization, batchnorm_v2.BatchNormalization] ) def test_deserialize_batchnorm_backwards_compatibility( self, batchnorm_layer ): layer = batchnorm_layer( momentum=0.9, beta_initializer="zeros", gamma_regularizer="l2" ) config = keras.layers.serialize(layer) new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.momentum, 0.9) if tf.__internal__.tf2.enabled(): self.assertIsInstance(new_layer, batchnorm_v2.BatchNormalization) self.assertEqual( new_layer.beta_initializer.__class__, keras.initializers.ZerosV2 ) else: self.assertIsInstance(new_layer, batchnorm_v1.BatchNormalization) self.assertEqual( new_layer.beta_initializer.__class__, keras.initializers.Zeros ) self.assertEqual( new_layer.gamma_regularizer.__class__, keras.regularizers.L2 ) @parameterized.parameters([lstm_v1.LSTM, lstm.LSTM]) def test_serialize_deserialize_lstm(self, layer): lstm_layer = layer(5, return_sequences=True) config = keras.layers.serialize(lstm_layer) self.assertEqual(config["class_name"], "LSTM") new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.units, 5) self.assertEqual(new_layer.return_sequences, True) if tf.__internal__.tf2.enabled(): self.assertIsInstance(new_layer, lstm.LSTM) else: self.assertIsInstance(new_layer, lstm_v1.LSTM) self.assertNotIsInstance(new_layer, lstm.LSTM) @parameterized.parameters([gru_v1.GRU, gru.GRU]) def test_serialize_deserialize_gru(self, layer): gru_layer = layer(5, return_sequences=True) config = keras.layers.serialize(gru_layer) self.assertEqual(config["class_name"], "GRU") new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.units, 5) self.assertEqual(new_layer.return_sequences, True) if tf.__internal__.tf2.enabled(): self.assertIsInstance(new_layer, gru.GRU) else: self.assertIsInstance(new_layer, gru_v1.GRU) self.assertNotIsInstance(new_layer, gru.GRU) def test_serialize_metric_throws_error(self): metric = Mean() with self.assertRaisesRegex(ValueError, "since it is a metric."): _ = keras.layers.serialize(metric) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/layers/serialization_test.py/0
{ "file_path": "tf-keras/tf_keras/layers/serialization_test.py", "repo_id": "tf-keras", "token_count": 3630 }
196
# 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 tf.layers.pooling.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tf_keras.legacy_tf_layers import pooling as pooling_layers # isort: off from tensorflow.python.framework import ( test_util as tf_test_utils, ) class PoolingTest(tf.test.TestCase): def testInvalidDataFormat(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 3), seed=1) with self.assertRaisesRegex(ValueError, "data_format"): pooling_layers.max_pooling2d( images, 3, strides=2, data_format="invalid" ) def testInvalidStrides(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 3), seed=1) with self.assertRaisesRegex(ValueError, "strides"): pooling_layers.max_pooling2d(images, 3, strides=(1, 2, 3)) with self.assertRaisesRegex(ValueError, "strides"): pooling_layers.max_pooling2d(images, 3, strides=None) def testInvalidPoolSize(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 3), seed=1) with self.assertRaisesRegex(ValueError, "pool_size"): pooling_layers.max_pooling2d(images, (1, 2, 3), strides=2) with self.assertRaisesRegex(ValueError, "pool_size"): pooling_layers.max_pooling2d(images, None, strides=2) def testCreateMaxPooling2D(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 4)) layer = pooling_layers.MaxPooling2D([2, 2], strides=2) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 3, 4, 4]) def testCreateAveragePooling2D(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 4)) layer = pooling_layers.AveragePooling2D([2, 2], strides=2) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 3, 4, 4]) @tf_test_utils.run_deprecated_v1 def testCreateMaxPooling2DChannelsFirst(self): height, width = 7, 9 images = tf.random.uniform((5, 2, height, width)) layer = pooling_layers.MaxPooling2D( [2, 2], strides=1, data_format="channels_first" ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 2, 6, 8]) @tf_test_utils.run_deprecated_v1 def testCreateAveragePooling2DChannelsFirst(self): height, width = 5, 6 images = tf.random.uniform((3, 4, height, width)) layer = pooling_layers.AveragePooling2D( (2, 2), strides=(1, 1), padding="valid", data_format="channels_first", ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [3, 4, 4, 5]) @tf_test_utils.run_deprecated_v1 def testCreateAveragePooling2DChannelsFirstWithNoneBatch(self): height, width = 5, 6 images = tf.compat.v1.placeholder( dtype="float32", shape=(None, 4, height, width) ) layer = pooling_layers.AveragePooling2D( (2, 2), strides=(1, 1), padding="valid", data_format="channels_first", ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [None, 4, 4, 5]) def testCreateMaxPooling1D(self): width = 7 channels = 3 images = tf.random.uniform((5, width, channels)) layer = pooling_layers.MaxPooling1D(2, strides=2) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, width // 2, channels] ) def testCreateAveragePooling1D(self): width = 7 channels = 3 images = tf.random.uniform((5, width, channels)) layer = pooling_layers.AveragePooling1D(2, strides=2) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, width // 2, channels] ) def testCreateMaxPooling1DChannelsFirst(self): width = 7 channels = 3 images = tf.random.uniform((5, channels, width)) layer = pooling_layers.MaxPooling1D( 2, strides=2, data_format="channels_first" ) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, channels, width // 2] ) def testCreateAveragePooling1DChannelsFirst(self): width = 7 channels = 3 images = tf.random.uniform((5, channels, width)) layer = pooling_layers.AveragePooling1D( 2, strides=2, data_format="channels_first" ) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, channels, width // 2] ) def testCreateMaxPooling3D(self): depth, height, width = 6, 7, 9 images = tf.random.uniform((5, depth, height, width, 4)) layer = pooling_layers.MaxPooling3D([2, 2, 2], strides=2) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 3, 3, 4, 4]) def testCreateAveragePooling3D(self): depth, height, width = 6, 7, 9 images = tf.random.uniform((5, depth, height, width, 4)) layer = pooling_layers.AveragePooling3D([2, 2, 2], strides=2) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 3, 3, 4, 4]) def testMaxPooling3DChannelsFirst(self): depth, height, width = 6, 7, 9 images = tf.random.uniform((5, 2, depth, height, width)) layer = pooling_layers.MaxPooling3D( [2, 2, 2], strides=2, data_format="channels_first" ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 2, 3, 3, 4]) def testAveragePooling3DChannelsFirst(self): depth, height, width = 6, 7, 9 images = tf.random.uniform((5, 2, depth, height, width)) layer = pooling_layers.AveragePooling3D( [2, 2, 2], strides=2, data_format="channels_first" ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 2, 3, 3, 4]) def testCreateMaxPooling2DIntegerPoolSize(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 4)) layer = pooling_layers.MaxPooling2D(2, strides=2) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 3, 4, 4]) def testMaxPooling2DPaddingSame(self): height, width = 7, 9 images = tf.random.uniform((5, height, width, 4), seed=1) layer = pooling_layers.MaxPooling2D( images.get_shape()[1:3], strides=2, padding="same" ) output = layer(images) self.assertListEqual(output.get_shape().as_list(), [5, 4, 5, 4]) def testCreatePooling2DWithStrides(self): height, width = 6, 8 # Test strides tuple images = tf.random.uniform((5, height, width, 3), seed=1) layer = pooling_layers.MaxPooling2D( [2, 2], strides=(2, 2), padding="same" ) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, height / 2, width / 2, 3] ) # Test strides integer layer = pooling_layers.MaxPooling2D([2, 2], strides=2, padding="same") output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, height / 2, width / 2, 3] ) # Test unequal strides layer = pooling_layers.MaxPooling2D( [2, 2], strides=(2, 1), padding="same" ) output = layer(images) self.assertListEqual( output.get_shape().as_list(), [5, height / 2, width, 3] ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/legacy_tf_layers/pooling_test.py/0
{ "file_path": "tf-keras/tf_keras/legacy_tf_layers/pooling_test.py", "repo_id": "tf-keras", "token_count": 3857 }
197
# Copyright 2016 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 TF-Keras metrics.""" import tensorflow.compat.v2 as tf from tf_keras import metrics from tf_keras.testing_infra import test_combinations @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class HingeTest(tf.test.TestCase): def test_config(self): hinge_obj = metrics.Hinge(name="hinge", dtype=tf.int32) self.assertEqual(hinge_obj.name, "hinge") self.assertEqual(hinge_obj._dtype, tf.int32) # Check save and restore config hinge_obj2 = metrics.Hinge.from_config(hinge_obj.get_config()) self.assertEqual(hinge_obj2.name, "hinge") self.assertEqual(hinge_obj2._dtype, tf.int32) def test_unweighted(self): hinge_obj = metrics.Hinge() self.evaluate(tf.compat.v1.variables_initializer(hinge_obj.variables)) y_true = tf.constant([[0, 1, 0, 1], [0, 0, 1, 1]]) y_pred = tf.constant([[-0.3, 0.2, -0.1, 1.6], [-0.25, -1.0, 0.5, 0.6]]) # metric = max(0, 1-y_true * y_pred), where y_true is -1/1 # y_true = [[-1, 1, -1, 1], [-1, -1, 1, 1]] # y_true * y_pred = [[0.3, 0.2, 0.1, 1.6], [0.25, 1, 0.5, 0.6]] # 1 - y_true * y_pred = [[0.7, 0.8, 0.9, -0.6], [0.75, 0, 0.5, 0.4]] # metric = [(0.7 + 0.8 + 0.9 + 0) / 4, (0.75 + 0 + 0.5 + 0.4) / 4] # = [0.6, 0.4125] # reduced metric = (0.6 + 0.4125) / 2 update_op = hinge_obj.update_state(y_true, y_pred) self.evaluate(update_op) result = hinge_obj.result() self.assertAllClose(0.506, result, atol=1e-3) def test_weighted(self): hinge_obj = metrics.Hinge() self.evaluate(tf.compat.v1.variables_initializer(hinge_obj.variables)) y_true = tf.constant([[-1, 1, -1, 1], [-1, -1, 1, 1]]) y_pred = tf.constant([[-0.3, 0.2, -0.1, 1.6], [-0.25, -1.0, 0.5, 0.6]]) sample_weight = tf.constant([1.5, 2.0]) # metric = max(0, 1-y_true * y_pred), where y_true is -1/1 # y_true * y_pred = [[0.3, 0.2, 0.1, 1.6], [0.25, 1, 0.5, 0.6]] # 1 - y_true * y_pred = [[0.7, 0.8, 0.9, -0.6], [0.75, 0, 0.5, 0.4]] # metric = [(0.7 + 0.8 + 0.9 + 0) / 4, (0.75 + 0 + 0.5 + 0.4) / 4] # = [0.6, 0.4125] # weighted metric = [0.6 * 1.5, 0.4125 * 2] # reduced metric = (0.6 * 1.5 + 0.4125 * 2) / (1.5 + 2) result = hinge_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAllClose(0.493, self.evaluate(result), atol=1e-3) @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class SquaredHingeTest(tf.test.TestCase): def test_config(self): sq_hinge_obj = metrics.SquaredHinge(name="sq_hinge", dtype=tf.int32) self.assertEqual(sq_hinge_obj.name, "sq_hinge") self.assertEqual(sq_hinge_obj._dtype, tf.int32) # Check save and restore config sq_hinge_obj2 = metrics.SquaredHinge.from_config( sq_hinge_obj.get_config() ) self.assertEqual(sq_hinge_obj2.name, "sq_hinge") self.assertEqual(sq_hinge_obj2._dtype, tf.int32) def test_unweighted(self): sq_hinge_obj = metrics.SquaredHinge() self.evaluate( tf.compat.v1.variables_initializer(sq_hinge_obj.variables) ) y_true = tf.constant([[0, 1, 0, 1], [0, 0, 1, 1]]) y_pred = tf.constant([[-0.3, 0.2, -0.1, 1.6], [-0.25, -1.0, 0.5, 0.6]]) # metric = max(0, 1-y_true * y_pred), where y_true is -1/1 # y_true = [[-1, 1, -1, 1], [-1, -1, 1, 1]] # y_true * y_pred = [[0.3, 0.2, 0.1, 1.6], [0.25, 1, 0.5, 0.6]] # 1 - y_true * y_pred = [[0.7, 0.8, 0.9, -0.6], [0.75, 0, 0.5, 0.4]] # max(0, 1 - y_true * y_pred) = [[0.7, 0.8, 0.9, 0], [0.75, 0, 0.5, # 0.4]] # squared(max(0, 1 - y_true * y_pred)) = [[0.49, 0.64, 0.81, 0], # [0.5625, 0, 0.25, 0.16]] # metric = [(0.49 + 0.64 + 0.81 + 0) / 4, (0.5625 + 0 + 0.25 + 0.16) / # 4] # = [0.485, 0.2431] # reduced metric = (0.485 + 0.2431) / 2 update_op = sq_hinge_obj.update_state(y_true, y_pred) self.evaluate(update_op) result = sq_hinge_obj.result() self.assertAllClose(0.364, result, atol=1e-3) def test_weighted(self): sq_hinge_obj = metrics.SquaredHinge() self.evaluate( tf.compat.v1.variables_initializer(sq_hinge_obj.variables) ) y_true = tf.constant([[-1, 1, -1, 1], [-1, -1, 1, 1]]) y_pred = tf.constant([[-0.3, 0.2, -0.1, 1.6], [-0.25, -1.0, 0.5, 0.6]]) sample_weight = tf.constant([1.5, 2.0]) # metric = max(0, 1-y_true * y_pred), where y_true is -1/1 # y_true * y_pred = [[0.3, 0.2, 0.1, 1.6], [0.25, 1, 0.5, 0.6]] # 1 - y_true * y_pred = [[0.7, 0.8, 0.9, -0.6], [0.75, 0, 0.5, 0.4]] # max(0, 1 - y_true * y_pred) = [[0.7, 0.8, 0.9, 0], [0.75, 0, 0.5, # 0.4]] # squared(max(0, 1 - y_true * y_pred)) = [[0.49, 0.64, 0.81, 0], # [0.5625, 0, 0.25, 0.16]] # metric = [(0.49 + 0.64 + 0.81 + 0) / 4, (0.5625 + 0 + 0.25 + 0.16) / # 4] # = [0.485, 0.2431] # weighted metric = [0.485 * 1.5, 0.2431 * 2] # reduced metric = (0.485 * 1.5 + 0.2431 * 2) / (1.5 + 2) result = sq_hinge_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAllClose(0.347, self.evaluate(result), atol=1e-3) @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class CategoricalHingeTest(tf.test.TestCase): def test_config(self): cat_hinge_obj = metrics.CategoricalHinge( name="cat_hinge", dtype=tf.int32 ) self.assertEqual(cat_hinge_obj.name, "cat_hinge") self.assertEqual(cat_hinge_obj._dtype, tf.int32) # Check save and restore config cat_hinge_obj2 = metrics.CategoricalHinge.from_config( cat_hinge_obj.get_config() ) self.assertEqual(cat_hinge_obj2.name, "cat_hinge") self.assertEqual(cat_hinge_obj2._dtype, tf.int32) def test_unweighted(self): cat_hinge_obj = metrics.CategoricalHinge() self.evaluate( tf.compat.v1.variables_initializer(cat_hinge_obj.variables) ) y_true = tf.constant( ((0, 1, 0, 1, 0), (0, 0, 1, 1, 1), (1, 1, 1, 1, 0), (0, 0, 0, 0, 1)) ) y_pred = tf.constant( ((0, 0, 1, 1, 0), (1, 1, 1, 1, 1), (0, 1, 0, 1, 0), (1, 1, 1, 1, 1)) ) update_op = cat_hinge_obj.update_state(y_true, y_pred) self.evaluate(update_op) result = cat_hinge_obj.result() self.assertAllClose(0.5, result, atol=1e-5) def test_weighted(self): cat_hinge_obj = metrics.CategoricalHinge() self.evaluate( tf.compat.v1.variables_initializer(cat_hinge_obj.variables) ) y_true = tf.constant( ((0, 1, 0, 1, 0), (0, 0, 1, 1, 1), (1, 1, 1, 1, 0), (0, 0, 0, 0, 1)) ) y_pred = tf.constant( ((0, 0, 1, 1, 0), (1, 1, 1, 1, 1), (0, 1, 0, 1, 0), (1, 1, 1, 1, 1)) ) sample_weight = tf.constant((1.0, 1.5, 2.0, 2.5)) result = cat_hinge_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAllClose(0.5, self.evaluate(result), atol=1e-5) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/metrics/hinge_metrics_test.py/0
{ "file_path": "tf-keras/tf_keras/metrics/hinge_metrics_test.py", "repo_id": "tf-keras", "token_count": 4240 }
198
# Copyright 2019 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 the device compatibility check.""" import re import tensorflow.compat.v2 as tf from tf_keras.mixed_precision import device_compatibility_check from tf_keras.testing_infra import test_combinations # isort: off from tensorflow.python.platform import tf_logging def device_details(device_name, compute_capability=None): details = {} if device_name: details["device_name"] = device_name if compute_capability: details["compute_capability"] = compute_capability return details @test_combinations.generate(test_combinations.combine(mode=["graph", "eager"])) class DeviceCompatibilityCheckTest(tf.test.TestCase): def _test_compat_check( self, device_attr_list, should_warn, expected_regex, policy_name="mixed_float16", ): with tf.compat.v1.test.mock.patch.object( tf_logging, "warning" ) as mock_warn, tf.compat.v1.test.mock.patch.object( tf_logging, "info" ) as mock_info: device_compatibility_check._log_device_compatibility_check( policy_name, device_attr_list ) if should_warn: self.assertRegex(mock_warn.call_args[0][0], expected_regex) mock_info.assert_not_called() else: self.assertRegex(mock_info.call_args[0][0], expected_regex) mock_warn.assert_not_called() def test_supported(self): details_list = [device_details("GPU 1", (7, 1))] regex = re.compile( r".*compatibility check \(mixed_float16\): OK\n" r"Your GPU will likely run quickly with dtype policy mixed_float16 " r"as it has compute capability of at least 7.0. Your GPU: GPU 1, " r"compute capability 7.1", flags=re.MULTILINE, ) self._test_compat_check(details_list, False, regex) details_list = [ device_details("GPU 1", (7, 0)), device_details("GPU 2", (7, 1)), device_details("GPU 3", (8, 0)), ] regex = re.compile( r".*compatibility check \(mixed_float16\): OK\n" r"Your GPUs will likely run quickly with dtype policy " r"mixed_float16 as they all have compute capability of " r"at least 7.0", flags=re.MULTILINE, ) self._test_compat_check(details_list, False, regex) def test_unsupported(self): details_list = [device_details("GPU 1", (6, 0))] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"Your GPU may run slowly with dtype policy mixed_float16.*\n" r" GPU 1, compute capability 6.0\n" r"See.*", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) details_list = [device_details(None)] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"Your GPU may run slowly with dtype policy mixed_float16.*\n" r" Unknown GPU, no compute capability " r"\(probably not an Nvidia GPU\)\nSee.*", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) details_list = [ device_details("GPU 1", (6, 0)), device_details("GPU 2", (3, 10)), ] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"Your GPUs may run slowly with dtype policy mixed_float16.*\n" r" GPU 1, compute capability 6.0\n" r" GPU 2, compute capability 3.10\n" r"See.*", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) details_list = [ device_details("GPU 1", (6, 0)), device_details("GPU 1", (6, 0)), device_details("GPU 1", (6, 0)), device_details("GPU 2", (3, 10)), ] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"Your GPUs may run slowly with dtype policy mixed_float16.*\n" r" GPU 1, compute capability 6.0 \(x3\)\n" r" GPU 2, compute capability 3.10\n" r"See.*", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) details_list = [] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"The dtype policy mixed_float16 may run slowly because this " r"machine does not have a GPU", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) def test_mix_of_supported_and_unsupported(self): details_list = [ device_details("GPU 1", (7, 0)), device_details("GPU 1", (7, 0)), device_details("GPU 2", (6, 0)), ] regex = re.compile( r".*compatibility check \(mixed_float16\): WARNING\n" r"Some of your GPUs may run slowly with dtype policy " r"mixed_float16.*\n GPU 1, compute capability 7.0 \(x2\)\n" r" GPU 2, compute capability 6.0\n" r"See.*", flags=re.MULTILINE, ) self._test_compat_check(details_list, True, regex) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/mixed_precision/device_compatibility_check_test.py/0
{ "file_path": "tf-keras/tf_keras/mixed_precision/device_compatibility_check_test.py", "repo_id": "tf-keras", "token_count": 2774 }
199
# Copyright 2022 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. # ============================================================================== """Adamax optimizer implementation.""" import tensorflow.compat.v2 as tf from tf_keras.optimizers import optimizer from tf_keras.saving.object_registration import register_keras_serializable # isort: off from tensorflow.python.util.tf_export import keras_export @register_keras_serializable() @keras_export( "keras.optimizers.Adamax", "keras.optimizers.experimental.Adamax", v1=[] ) class Adamax(optimizer.Optimizer): """Optimizer that implements the Adamax algorithm. Adamax, a variant of Adam based on the infinity norm, is a first-order gradient-based optimization method. Due to its capability of adjusting the learning rate based on data characteristics, it is suited to learn time-variant process, e.g., speech data with dynamically changed noise conditions. Default parameters follow those provided in the paper (see references below). Initialization: ```python m = 0 # Initialize initial 1st moment vector u = 0 # Initialize the exponentially weighted infinity norm t = 0 # Initialize timestep ``` The update rule for parameter `w` with gradient `g` is described at the end of section 7.1 of the paper (see the referenece section): ```python t += 1 m = beta1 * m + (1 - beta) * g u = max(beta2 * u, abs(g)) current_lr = learning_rate / (1 - beta1 ** t) w = w - current_lr * m / (u + epsilon) ``` Args: learning_rate: A `tf.Tensor`, floating point value, a schedule that is a `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable that takes no arguments and returns the actual value to use. The learning rate. Defaults to `0.001`. beta_1: A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates. beta_2: A float value or a constant float tensor. The exponential decay rate for the exponentially weighted infinity norm. epsilon: A small constant for numerical stability. {{base_optimizer_keyword_args}} Reference: - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) """ def __init__( self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, weight_decay=None, clipnorm=None, clipvalue=None, global_clipnorm=None, use_ema=False, ema_momentum=0.99, ema_overwrite_frequency=None, jit_compile=True, name="Adamax", **kwargs ): super().__init__( name=name, weight_decay=weight_decay, clipnorm=clipnorm, clipvalue=clipvalue, global_clipnorm=global_clipnorm, use_ema=use_ema, ema_momentum=ema_momentum, ema_overwrite_frequency=ema_overwrite_frequency, jit_compile=jit_compile, **kwargs ) self._learning_rate = self._build_learning_rate(learning_rate) self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon def build(self, var_list): """Initialize optimizer variables. Adamax optimizer has 2 types of variables: momentums (denoted as m), exponentially weighted infinity norm (denoted as u). Args: var_list: list of model variables to build Adamax variables on. """ super().build(var_list) if hasattr(self, "_built") and self._built: return self._built = True self._m = [] self._u = [] for var in var_list: self._m.append( self.add_variable_from_reference( model_variable=var, variable_name="m" ) ) self._u.append( self.add_variable_from_reference( model_variable=var, variable_name="u" ) ) def update_step(self, gradient, variable): """Update step given gradient and the associated model variable.""" lr = tf.cast(self.learning_rate, variable.dtype) local_step = tf.cast(self.iterations + 1, variable.dtype) beta_1_power = tf.pow(tf.cast(self.beta_1, variable.dtype), local_step) var_key = self._var_key(variable) m = self._m[self._index_dict[var_key]] u = self._u[self._index_dict[var_key]] if isinstance(gradient, tf.IndexedSlices): # Sparse gradients. indices = gradient.indices m.assign_add(-m * (1 - self.beta_1)) m.scatter_add( tf.IndexedSlices(gradient.values * (1 - self.beta_1), indices) ) u.assign(u * self.beta_2) u_slice = tf.gather(u, indices) u_slice_incremental = ( tf.maximum(u_slice, tf.abs(gradient.values)) - u_slice ) u.scatter_add(tf.IndexedSlices(u_slice_incremental, indices)) variable.assign_sub( (lr * m) / ((1 - beta_1_power) * (u + self.epsilon)) ) else: # Dense gradients. m.assign_add((gradient - m) * (1 - self.beta_1)) u.assign(tf.maximum(self.beta_2 * u, tf.abs(gradient))) variable.assign_sub( (lr * m) / ((1 - beta_1_power) * (u + self.epsilon)) ) def get_config(self): config = super().get_config() config.update( { "learning_rate": self._serialize_hyperparameter( self._learning_rate ), "beta_1": self.beta_1, "beta_2": self.beta_2, "epsilon": self.epsilon, } ) return config Adamax.__doc__ = Adamax.__doc__.replace( "{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args )
tf-keras/tf_keras/optimizers/adamax.py/0
{ "file_path": "tf-keras/tf_keras/optimizers/adamax.py", "repo_id": "tf-keras", "token_count": 2927 }
200
# 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. # ============================================================================== """Functional test for GradientDescent.""" import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized from tf_keras.optimizers.legacy import gradient_descent from tf_keras.optimizers.schedules import learning_rate_schedule from tf_keras.testing_infra import test_combinations class GradientDescentOptimizerTest(tf.test.TestCase, parameterized.TestCase): @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasic(self): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) sgd = gradient_descent.SGD(3.0) sgd_op = sgd.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], self.evaluate(var1) ) def _test_basic_sgd_with_learning_rate_decay(self, sgd, dtype): var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) if not tf.executing_eagerly(): sgd_op = sgd.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 2 steps of sgd if not tf.executing_eagerly(): self.evaluate(sgd_op) else: sgd.apply_gradients(zip([grads0, grads1], [var0, var1])) # Validate updated params self.assertAllCloseAccordingToType( [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], self.evaluate(var1) ) if not tf.executing_eagerly(): self.evaluate(sgd_op) else: sgd.apply_gradients(zip([grads0, grads1], [var0, var1])) # Validate updated params self.assertAllCloseAccordingToType( [1.0 - 3.0 * 0.1 - 2.0 * 0.1, 2.0 - 3.0 * 0.1 - 2.0 * 0.1], self.evaluate(var0), ) self.assertAllCloseAccordingToType( [3.0 - 3.0 * 0.01 - 2.0 * 0.01, 4.0 - 3.0 * 0.01 - 2.0 * 0.01], self.evaluate(var1), ) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasicWithLearningRateDecay(self): for dtype in [tf.half, tf.float32, tf.float64]: learning_rate = 3.0 decay = 0.5 sgd = gradient_descent.SGD(learning_rate=learning_rate, decay=decay) self._test_basic_sgd_with_learning_rate_decay(sgd, dtype) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasicWithLearningRateInverseTimeDecay(self): for dtype in [tf.half, tf.float32, tf.float64]: learning_rate = learning_rate_schedule.InverseTimeDecay( 3.0, decay_steps=1.0, decay_rate=0.5 ) sgd = gradient_descent.SGD(learning_rate=learning_rate) self._test_basic_sgd_with_learning_rate_decay(sgd, dtype) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasicWithLearningRateInverseTimeDecaySerializeAndDeserialize(self): for dtype in [tf.half, tf.float32, tf.float64]: learning_rate = learning_rate_schedule.InverseTimeDecay( 3.0, decay_steps=1.0, decay_rate=0.5 ) sgd = gradient_descent.SGD(learning_rate=learning_rate) sgd = gradient_descent.SGD.from_config(sgd.get_config()) self._test_basic_sgd_with_learning_rate_decay(sgd, dtype) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasicCallableParams(self): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) lr = lambda: 3.0 sgd = gradient_descent.SGD(lr) sgd_op = sgd.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], self.evaluate(var1) ) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testMinimizeResourceVariable(self): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0, 2.0]], dtype=dtype) var1 = tf.Variable([3.0], dtype=dtype) x = tf.constant([[4.0], [5.0]], dtype=dtype) loss = lambda: tf.matmul(var0, x) + var1 sgd = gradient_descent.SGD(1.0) sgd_op = sgd.minimize(loss, [var0, var1]) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [[1.0 - 4.0, 2.0 - 5.0]], self.evaluate(var0) ) self.assertAllCloseAccordingToType([3.0 - 1.0], self.evaluate(var1)) def testMinimizeSparseResourceVariable(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0, 2.0]], dtype=dtype) var1 = tf.Variable([3.0], dtype=dtype) x = tf.constant([[4.0], [5.0]], dtype=dtype) def loss(): pred = tf.matmul( tf.compat.v1.nn.embedding_lookup([var0], [0]), x ) pred += var1 return pred * pred sgd_op = gradient_descent.SGD(1.0).minimize(loss, [var0, var1]) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params np_pred = 1.0 * 4.0 + 2.0 * 5.0 + 3.0 np_grad = 2 * np_pred self.assertAllCloseAccordingToType( [[1.0 - np_grad * 4.0, 2.0 - np_grad * 5.0]], self.evaluate(var0), ) self.assertAllCloseAccordingToType( [3.0 - np_grad], self.evaluate(var1) ) def testTensorLearningRate(self): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) lrate = tf.constant(3.0) sgd_op = gradient_descent.SGD(lrate).apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], self.evaluate(var1) ) def testGradWrtRef(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: opt = gradient_descent.SGD(3.0) values = [1.0, 3.0] vars_ = [tf.Variable([v], dtype=dtype) for v in values] loss = lambda: vars_[0] + vars_[1] grads_and_vars = opt._compute_gradients(loss, vars_) self.evaluate(tf.compat.v1.global_variables_initializer()) for grad, _ in grads_and_vars: self.assertAllCloseAccordingToType( [1.0], self.evaluate(grad) ) def testSparseBasic(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0], [2.0]], dtype=dtype) var1 = tf.Variable([[3.0], [4.0]], dtype=dtype) grads0 = tf.IndexedSlices( tf.constant([0.1], shape=[1, 1], dtype=dtype), tf.constant([0]), tf.constant([2, 1]), ) grads1 = tf.IndexedSlices( tf.constant([0.01], shape=[1, 1], dtype=dtype), tf.constant([1]), tf.constant([2, 1]), ) sgd_op = gradient_descent.SGD(3.0).apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [[1.0 - 3.0 * 0.1], [2.0]], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [[3.0], [4.0 - 3.0 * 0.01]], self.evaluate(var1) ) def testSparseBasicWithLearningRateDecay(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0], [2.0]], dtype=dtype) var1 = tf.Variable([[3.0], [4.0]], dtype=dtype) grads0 = tf.IndexedSlices( tf.constant([0.1], shape=[1, 1], dtype=dtype), tf.constant([0]), tf.constant([2, 1]), ) grads1 = tf.IndexedSlices( tf.constant([0.01], shape=[1, 1], dtype=dtype), tf.constant([1]), tf.constant([2, 1]), ) sgd_op = gradient_descent.SGD(3.0, decay=0.5).apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 2 steps of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [[1.0 - 3.0 * 0.1], [2.0]], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [[3.0], [4.0 - 3.0 * 0.01]], self.evaluate(var1) ) self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [[1.0 - 3.0 * 0.1 - 2.0 * 0.1], [2.0]], self.evaluate(var0) ) self.assertAllCloseAccordingToType( [[3.0], [4.0 - 3.0 * 0.01 - 2.0 * 0.01]], self.evaluate(var1), ) @test_combinations.generate(test_combinations.combine(mode=["eager"])) def testCapturingInFunctionWhileExecutingEagerly(self): optimizer = gradient_descent.SGD(1.0) var_holder = {} def step(): if not var_holder: var_holder["var"] = tf.Variable(1.0) else: var_holder["var"].assign(1.0) with tf.GradientTape() as tape: loss = var_holder["var"] ** 2 grad = tape.gradient(loss, var_holder["var"]) optimizer.apply_gradients([(grad, var_holder["var"])]) return var_holder["var"].read_value() compiled_step = tf.function(step) self.assertEqual(float(step()), -1.0) self.assertEqual(float(compiled_step()), -1.0) # This shouldn't fail; in particular, the learning rate tensor should # be an EagerTensor once again, not a graph Tensor. self.assertEqual(float(step()), -1.0) def testConstructSGDWithLR(self): opt = gradient_descent.SGD(lr=1.0) opt_2 = gradient_descent.SGD(learning_rate=0.1, lr=1.0) opt_3 = gradient_descent.SGD(learning_rate=0.1) self.assertIsInstance(opt.lr, tf.Variable) self.assertIsInstance(opt_2.lr, tf.Variable) self.assertIsInstance(opt_3.lr, tf.Variable) self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllClose(self.evaluate(opt.lr), (1.0)) self.assertAllClose(self.evaluate(opt_2.lr), (1.0)) self.assertAllClose(self.evaluate(opt_3.lr), (0.1)) class MomentumOptimizerTest(tf.test.TestCase, parameterized.TestCase): def _update_nesterov_momentum_numpy(self, var, accum, g, lr, momentum): accum = accum * momentum - g * lr var += accum * momentum - g * lr return var, accum @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testBasic(self): for _, dtype in enumerate([tf.half, tf.float32, tf.float64]): var0 = tf.Variable([1.0, 2.0], dtype=dtype, name="var0") var1 = tf.Variable([3.0, 4.0], dtype=dtype, name="var1") grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) learning_rate = 2.0 momentum = 0.9 mom_opt = gradient_descent.SGD( learning_rate=learning_rate, momentum=momentum ) # self.assertFalse(mom_opt._initial_decay) mom_update = mom_opt.apply_gradients( zip([grads0, grads1], [var0, var1]) ) # Check we have slots slot0 = mom_opt.get_slot(var0, "momentum") self.assertEqual(slot0.shape, var0.shape) slot1 = mom_opt.get_slot(var1, "momentum") self.assertEqual(slot1.shape, var1.shape) # Step 1: the momentum accumulators where 0. So we should see a # normal update: v -= grad * learning_rate self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array([-0.2, -0.2]), self.evaluate(slot0) ) self.assertAllCloseAccordingToType( np.array([-0.02, -0.02]), self.evaluate(slot1) ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), self.evaluate(var1), ) # Step 2: the momentum accumulators contain the previous update. self.evaluate(mom_update) if tf.executing_eagerly(): mom_opt.apply_gradients(zip([grads0, grads1], [var0, var1])) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array( [(0.9 * (-0.2) - 2.0 * 0.1), (0.9 * (-0.2) - 2.0 * 0.1)] ), self.evaluate(slot0), ) self.assertAllCloseAccordingToType( np.array( [(0.9 * (-0.02) - 2.0 * 0.01), (0.9 * (-0.02) - 2.0 * 0.01)] ), self.evaluate(slot1), ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array( [ 1.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), 2.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), ] ), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array( [ 2.98 - ((0.9 * 0.01 + 0.01) * 2.0), 3.98 - ((0.9 * 0.01 + 0.01) * 2.0), ] ), self.evaluate(var1), ) def testNesterovMomentum(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype, name="var0") var1 = tf.Variable([3.0, 4.0], dtype=dtype, name="var1") var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) accum0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) accum1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) loss = lambda: 5 * var0 * var0 + 3 * var1 mom_op = gradient_descent.SGD( learning_rate=2.0, momentum=0.9, nesterov=True ) opt_op = mom_op.minimize(loss, [var0, var1]) self.evaluate(tf.compat.v1.global_variables_initializer()) for _ in range(1, 5): self.evaluate(opt_op) var0_np, accum0_np = self._update_nesterov_momentum_numpy( var0_np, accum0_np, var0_np * 10, 2.0, 0.9 ) var1_np, accum1_np = self._update_nesterov_momentum_numpy( var1_np, accum1_np, 3, 2.0, 0.9 ) self.assertAllClose(var0_np, self.evaluate(var0)) self.assertAllClose(var1_np, self.evaluate(var1)) def testSparseNesterovMomentum(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. for dtype in [tf.float32, tf.float64]: with tf.Graph().as_default(), self.cached_session() as sess: var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) accum0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) accum1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) grads = [] for t in range(1, 5): grads.append(var0_np * 10) var0_np, accum0_np = self._update_nesterov_momentum_numpy( var0_np, accum0_np, var0_np * 10, 2.0, 0.9 ) var1_np, accum1_np = self._update_nesterov_momentum_numpy( var1_np, accum1_np, 3, 2.0, 0.9 ) var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) accum0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) accum1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype) var0 = tf.Variable(var0_np, dtype=dtype, name="var0") var1 = tf.Variable(var1_np, dtype=dtype, name="var1") mom_op = gradient_descent.SGD( learning_rate=2.0, momentum=0.9, nesterov=True ) x_feed = tf.compat.v1.placeholder(dtype) y_feed = tf.IndexedSlices( x_feed, tf.constant([0, 1]), tf.constant([2]) ) grads_and_vars = [ (y_feed, var0), (tf.constant([3.0, 3.0], dtype=dtype), var1), ] opt_update = mom_op.apply_gradients(grads_and_vars) self.evaluate(tf.compat.v1.global_variables_initializer()) for t in range(1, 5): sess.run(opt_update, feed_dict={x_feed: grads[t - 1]}) var0_np, accum0_np = self._update_nesterov_momentum_numpy( var0_np, accum0_np, var0_np * 10, 2.0, 0.9 ) var1_np, accum1_np = self._update_nesterov_momentum_numpy( var1_np, accum1_np, 3, 2.0, 0.9 ) self.assertAllClose(var0_np, self.evaluate(var0)) self.assertAllClose(var1_np, self.evaluate(var1)) def testMinimizeSparseResourceVariable(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0, 2.0]], dtype=dtype) def loss(): x = tf.constant([[4.0], [5.0]], dtype=dtype) pred = tf.matmul( tf.compat.v1.nn.embedding_lookup([var0], [0]), x ) return pred * pred opt = gradient_descent.SGD(learning_rate=1.0, momentum=0.9) sgd_op = opt.minimize(loss, [var0]) self.evaluate(tf.compat.v1.global_variables_initializer()) # Run 1 step of sgd self.evaluate(sgd_op) # Validate updated params self.assertAllCloseAccordingToType( [[-111, -138]], self.evaluate(var0) ) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testMinimizeWith2DIndicesForEmbeddingLookup(self): var0 = tf.Variable(tf.ones([2, 2])) def loss(): return tf.reduce_sum(tf.compat.v1.nn.embedding_lookup(var0, [[1]])) opt = gradient_descent.SGD(learning_rate=1.0, momentum=0.9) sgd_op = opt.minimize(loss, [var0]) self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(sgd_op) self.assertAllCloseAccordingToType( [[1, 1], [0, 0]], self.evaluate(var0) ) def testTensorLearningRateAndMomentum(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) mom_opt = gradient_descent.SGD( learning_rate=tf.constant(2.0), momentum=tf.constant(0.9) ) mom_update = mom_opt.apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) # Check we have slots slot0 = mom_opt.get_slot(var0, "momentum") self.assertEqual(slot0.shape, var0.shape) slot1 = mom_opt.get_slot(var1, "momentum") self.assertEqual(slot1.shape, var1.shape) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Step 1: the momentum accumulators where 0. So we should see a # normal update: v -= grad * learning_rate self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array([-0.2, -0.2]), self.evaluate(slot0) ) self.assertAllCloseAccordingToType( np.array([-0.02, -0.02]), self.evaluate(slot1) ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), self.evaluate(var1), ) # Step 2: the momentum accumulators contain the previous update. self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array( [(0.9 * (-0.2) - 2.0 * 0.1), (0.9 * (-0.2) - 2.0 * 0.1)] ), self.evaluate(slot0), ) self.assertAllCloseAccordingToType( np.array( [ (0.9 * (-0.02) - 2.0 * 0.01), (0.9 * (-0.02) - 2.0 * 0.01), ] ), self.evaluate(slot1), ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array( [ 1.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), 2.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), ] ), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array( [ 2.98 - ((0.9 * 0.01 + 0.01) * 2.0), 3.98 - ((0.9 * 0.01 + 0.01) * 2.0), ] ), self.evaluate(var1), ) def testSparse(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable(tf.zeros([4, 2], dtype=dtype)) var1 = tf.Variable(tf.constant(1.0, dtype, [4, 2])) grads0 = tf.IndexedSlices( tf.constant([[0.1, 0.1]], dtype=dtype), tf.constant([1]), tf.constant([4, 2]), ) grads1 = tf.IndexedSlices( tf.constant([[0.01, 0.01], [0.01, 0.01]], dtype=dtype), tf.constant([2, 3]), tf.constant([4, 2]), ) mom_opt = gradient_descent.SGD(learning_rate=2.0, momentum=0.9) mom_update = mom_opt.apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) # Check we have slots slot0 = mom_opt.get_slot(var0, "momentum") self.assertEqual(slot0.shape, var0.shape) slot1 = mom_opt.get_slot(var1, "momentum") self.assertEqual(slot1.shape, var1.shape) # Fetch params to validate initial values self.assertAllClose([0, 0], self.evaluate(var0)[0]) self.assertAllClose([0, 0], self.evaluate(var0)[1]) self.assertAllClose([1, 1], self.evaluate(var1)[2]) # Step 1: the momentum accumulators are 0. So we should see a # normal update: v -= grad * learning_rate self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array([0, 0]), self.evaluate(slot0)[0] ) self.assertAllCloseAccordingToType( np.array([-2.0 * 0.1, -2.0 * 0.1]), self.evaluate(slot0)[1] ) self.assertAllCloseAccordingToType( np.array([-2.0 * 0.01, -2.0 * 0.01]), self.evaluate(slot1)[2], ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array([0, 0]), self.evaluate(var0)[0] ) self.assertAllCloseAccordingToType( np.array([-(0.1 * 2.0), -(0.1 * 2.0)]), self.evaluate(var0)[1], ) self.assertAllCloseAccordingToType( np.array([1.0 - (0.01 * 2.0), 1.0 - (0.01 * 2.0)]), self.evaluate(var1)[2], ) # Step 2: the momentum accumulators contain the previous update. self.evaluate(mom_update) # Check that the momentum accumulators have been updated. self.assertAllClose(np.array([0, 0]), self.evaluate(slot0)[0]) self.assertAllCloseAccordingToType( np.array( [(0.9 * (-0.2) - 2.0 * 0.1), (0.9 * (-0.2) - 2.0 * 0.1)] ), self.evaluate(slot0)[1], ) self.assertAllCloseAccordingToType( np.array( [ (0.9 * (-0.02) - 2.0 * 0.01), (0.9 * (-0.02) - 2.0 * 0.01), ] ), self.evaluate(slot1)[2], ) # Check that the parameters have been updated. self.assertAllClose(np.array([0, 0]), self.evaluate(var0)[0]) self.assertAllCloseAccordingToType( np.array( [ -(0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), -(0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), ] ), self.evaluate(var0)[1], ) self.assertAllCloseAccordingToType( np.array( [ 0.98 - ((0.9 * 0.01 + 0.01) * 2.0), 0.98 - ((0.9 * 0.01 + 0.01) * 2.0), ] ), self.evaluate(var1)[2], ) def testSharing(self): # TODO(tanzheny, omalleyt): Fix test in eager mode. with tf.Graph().as_default(): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([1.0, 2.0], dtype=dtype) var1 = tf.Variable([3.0, 4.0], dtype=dtype) grads0 = tf.constant([0.1, 0.1], dtype=dtype) grads1 = tf.constant([0.01, 0.01], dtype=dtype) mom_opt = gradient_descent.SGD(learning_rate=2.0, momentum=0.9) mom_update1 = mom_opt.apply_gradients( zip([grads0, grads1], [var0, var1]) ) mom_update2 = mom_opt.apply_gradients( zip([grads0, grads1], [var0, var1]) ) self.evaluate(tf.compat.v1.global_variables_initializer()) slot0 = mom_opt.get_slot(var0, "momentum") self.assertEqual(slot0.shape, var0.shape) slot1 = mom_opt.get_slot(var1, "momentum") self.assertEqual(slot1.shape, var1.shape) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Step 1: the momentum accumulators where 0. So we should see a # normal update: v -= grad * learning_rate self.evaluate(mom_update1) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array([-0.2, -0.2]), self.evaluate(slot0) ) self.assertAllCloseAccordingToType( np.array([-0.02, -0.02]), self.evaluate(slot1) ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), self.evaluate(var1), ) # Step 2: the second momentum accumulators contain the previous # update. self.evaluate(mom_update2) # Check that the momentum accumulators have been updated. self.assertAllCloseAccordingToType( np.array( [(0.9 * (-0.2) - 2.0 * 0.1), (0.9 * (-0.2) - 2.0 * 0.1)] ), self.evaluate(slot0), ) self.assertAllCloseAccordingToType( np.array( [ (0.9 * (-0.02) - 2.0 * 0.01), (0.9 * (-0.02) - 2.0 * 0.01), ] ), self.evaluate(slot1), ) # Check that the parameters have been updated. self.assertAllCloseAccordingToType( np.array( [ 1.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), 2.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), ] ), self.evaluate(var0), ) self.assertAllCloseAccordingToType( np.array( [ 2.98 - ((0.9 * 0.01 + 0.01) * 2.0), 3.98 - ((0.9 * 0.01 + 0.01) * 2.0), ] ), self.evaluate(var1), ) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def testConfig(self): opt = gradient_descent.SGD( learning_rate=1.0, momentum=0.9, nesterov=True ) config = opt.get_config() opt2 = gradient_descent.SGD.from_config(config) lr = opt.lr lr2 = opt2.lr self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllClose(self.evaluate(lr), self.evaluate(lr2)) self.assertAllClose( self.evaluate(opt._get_hyper("momentum")), self.evaluate(opt2._get_hyper("momentum")), ) self.assertAllClose( self.evaluate(opt._get_hyper("decay")), self.evaluate(opt2._get_hyper("decay")), ) var0 = tf.Variable([[1.0], [2.0]], dtype=tf.float32) loss = lambda: 3 * var0 # learning rate variable created when calling minimize. opt.minimize(loss, [var0]) self.evaluate(tf.compat.v1.global_variables_initializer()) config = opt.get_config() opt3 = gradient_descent.SGD.from_config(config) lr3 = opt3.lr self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllClose(self.evaluate(lr), self.evaluate(lr3)) self.assertAllClose( self.evaluate(opt._get_hyper("momentum")), self.evaluate(opt3._get_hyper("momentum")), ) self.assertAllClose( self.evaluate(opt._get_hyper("decay")), self.evaluate(opt3._get_hyper("decay")), ) self.assertTrue(opt3.nesterov) def testNesterovWithoutMomentum(self): with self.assertRaisesRegex(ValueError, "must be between"): gradient_descent.SGD(learning_rate=1.0, momentum=2.0) def testConstructMomentumWithLR(self): opt = gradient_descent.SGD(lr=1.0, momentum=0.9) opt_2 = gradient_descent.SGD(learning_rate=0.1, momentum=0.9, lr=1.0) opt_3 = gradient_descent.SGD(learning_rate=0.1, momentum=0.9) self.assertIsInstance(opt.lr, tf.Variable) self.assertIsInstance(opt_2.lr, tf.Variable) self.assertIsInstance(opt_3.lr, tf.Variable) self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllClose(self.evaluate(opt.lr), (1.0)) self.assertAllClose(self.evaluate(opt_2.lr), (1.0)) self.assertAllClose(self.evaluate(opt_3.lr), (0.1)) @test_combinations.generate(test_combinations.combine(mode=["eager"])) def testMinimizeLossTensor(self): for dtype in [tf.half, tf.float32, tf.float64]: var0 = tf.Variable([[1.0, 2.0]], dtype=dtype) var1 = tf.Variable([3.0], dtype=dtype) x = tf.constant([[4.0], [5.0]], dtype=dtype) tape = tf.GradientTape() with tape: loss = tf.matmul(var0, x) + var1 sgd = gradient_descent.SGD(1.0) with self.assertRaisesRegex(ValueError, "`tape` is required"): sgd.minimize(loss, [var0, var1]) sgd.minimize(loss, [var0, var1], tape=tape) self.assertAllCloseAccordingToType( [[1.0 - 4.0, 2.0 - 5.0]], self.evaluate(var0) ) self.assertAllCloseAccordingToType([3.0 - 1.0], self.evaluate(var1)) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/optimizers/legacy/gradient_descent_test.py/0
{ "file_path": "tf-keras/tf_keras/optimizers/legacy/gradient_descent_test.py", "repo_id": "tf-keras", "token_count": 22363 }
201
# Copyright 2016 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 TF-Keras optimizers.""" import gc import weakref import numpy as np import tensorflow.compat.v2 as tf import tf_keras as keras from tf_keras.optimizers import optimizer_v1 from tf_keras.testing_infra import test_combinations from tf_keras.testing_infra import test_utils from tf_keras.utils import np_utils # isort: off from tensorflow.python.training.adam import AdamOptimizer from tensorflow.python.training.experimental.loss_scale_optimizer import ( # noqa: E501 MixedPrecisionLossScaleOptimizer, ) def _get_model(input_dim, num_hidden, output_dim): model = keras.models.Sequential() model.add( keras.layers.Dense( num_hidden, activation="relu", input_shape=(input_dim,) ) ) model.add(keras.layers.Dense(output_dim, activation="softmax")) return model @test_combinations.run_all_keras_modes class KerasOptimizersTest(test_combinations.TestCase): def _test_optimizer(self, optimizer, target=0.75): if tf.executing_eagerly(): self.skipTest("v1 optimizer does not run in eager mode") np.random.seed(1337) (x_train, y_train), _ = test_utils.get_test_data( train_samples=1000, test_samples=200, input_shape=(10,), num_classes=2, ) y_train = np_utils.to_categorical(y_train) model = _get_model(x_train.shape[1], 20, y_train.shape[1]) model.compile( loss="categorical_crossentropy", optimizer=optimizer, metrics=["acc"], run_eagerly=test_utils.should_run_eagerly(), ) np.testing.assert_equal( keras.backend.get_value(model.optimizer.iterations), 0 ) history = model.fit( x_train, y_train, epochs=2, batch_size=16, verbose=0 ) np.testing.assert_equal( keras.backend.get_value(model.optimizer.iterations), 126 ) # 63 steps per epoch self.assertGreaterEqual(history.history["acc"][-1], target) config = keras.optimizers.serialize(optimizer) optim = keras.optimizers.deserialize(config) new_config = keras.optimizers.serialize(optim) new_config["class_name"] = new_config["class_name"].lower() new_config["config"].pop("name", None) if "amsgrad" not in config["config"]: new_config["config"].pop("amsgrad", None) if ( "decay" in new_config["config"] and "schedule_decay" in config["config"] ): new_config["config"]["schedule_decay"] = new_config["config"].pop( "decay" ) if "momentum" not in config["config"]: new_config["config"].pop("momentum", None) if "centered" not in config["config"]: new_config["config"].pop("centered", None) self.assertDictEqual(config, new_config) # Test constraints. model = keras.models.Sequential() dense = keras.layers.Dense( 10, input_shape=(x_train.shape[1],), kernel_constraint=lambda x: 0.0 * x + 1.0, bias_constraint=lambda x: 0.0 * x + 2.0, activation="relu", ) model.add(dense) model.add(keras.layers.Dense(y_train.shape[1], activation="softmax")) model.compile( loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"], run_eagerly=test_utils.should_run_eagerly(), ) np.testing.assert_equal( keras.backend.get_value(model.optimizer.iterations), 126 ) # Using same optimizer from before model.train_on_batch(x_train[:10], y_train[:10]) np.testing.assert_equal( keras.backend.get_value(model.optimizer.iterations), 127 ) kernel, bias = dense.get_weights() np.testing.assert_allclose(kernel, 1.0, atol=1e-3) np.testing.assert_allclose(bias, 2.0, atol=1e-3) def test_sgd(self): with self.cached_session(): self._test_optimizer(optimizer_v1.SGD()) def test_momentum(self): with self.cached_session(): self._test_optimizer( optimizer_v1.SGD(lr=0.01, momentum=0.9, nesterov=True) ) def test_rmsprop(self): with self.cached_session(): self._test_optimizer(optimizer_v1.RMSprop()) self._test_optimizer(optimizer_v1.RMSprop(decay=1e-3)) def test_adagrad(self): with self.cached_session(): self._test_optimizer(optimizer_v1.Adagrad()) self._test_optimizer(optimizer_v1.Adagrad(decay=1e-3)) def test_adadelta(self): with self.cached_session(): self._test_optimizer(optimizer_v1.Adadelta(), target=0.6) # Accuracy seems dependent on the initialization. Even adding # tf.compat.v1.Print nodes in the graph seemed to affect the # initialization seed, and hence the accuracy. self._test_optimizer(optimizer_v1.Adadelta(decay=1e-3), target=0.4) def test_adam(self): with self.cached_session(): self._test_optimizer(optimizer_v1.Adam()) # Accuracy seems dependent on the seed initialization. # TODO(b/121051441): fix test flakiness. self._test_optimizer(optimizer_v1.Adam(decay=1e-3), target=0.73) self._test_optimizer(optimizer_v1.Adam(amsgrad=True)) def test_adamax(self): with self.cached_session(): self._test_optimizer(optimizer_v1.Adamax()) self._test_optimizer(optimizer_v1.Adamax(decay=1e-3)) def test_nadam(self): with self.cached_session(): self._test_optimizer(optimizer_v1.Nadam()) def test_clipnorm(self): with self.cached_session(): self._test_optimizer( optimizer_v1.SGD(lr=0.01, momentum=0.9, clipnorm=0.5) ) def test_clipvalue(self): with self.cached_session(): self._test_optimizer( optimizer_v1.SGD(lr=0.01, momentum=0.9, clipvalue=0.5) ) def test_tf_optimizer(self): if tf.executing_eagerly(): self.skipTest("v1 optimizer does not run in eager mode") optimizer = optimizer_v1.TFOptimizer(AdamOptimizer(0.01)) model = keras.models.Sequential() model.add( keras.layers.Dense( 2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1), ) ) # This is possible model.compile( loss="mean_squared_error", optimizer=optimizer, run_eagerly=test_utils.should_run_eagerly(), ) keras.backend.track_tf_optimizer(optimizer) model.fit( np.random.random((5, 3)), np.random.random((5, 2)), epochs=1, batch_size=5, verbose=0, ) # not supported with self.assertRaises(NotImplementedError): _ = optimizer.weights with self.assertRaises(NotImplementedError): optimizer.get_config() with self.assertRaises(NotImplementedError): optimizer.from_config(None) def test_optimizer_garbage_collection(self): if tf.executing_eagerly(): self.skipTest("v1 optimizer does not run in eager mode") graph = tf.Graph() with graph.as_default(): optimizer = optimizer_v1.TFOptimizer(AdamOptimizer(0.01)) keras.backend.track_tf_optimizer(optimizer) optimizer_weak = weakref.ref(optimizer) graph_weak = weakref.ref(graph) del graph, optimizer gc.collect() # Check that the weak references are dead now. self.assertIs(graph_weak(), None) self.assertIs(optimizer_weak(), None) def test_tf_optimizer_iterations(self): if tf.executing_eagerly(): self.skipTest("v1 optimizer does not run in eager mode") with self.cached_session(): optimizer = optimizer_v1.TFOptimizer(AdamOptimizer(0.01)) model = keras.models.Sequential() model.add( keras.layers.Dense( 2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1), ) ) model.compile( loss="mean_squared_error", optimizer=optimizer, run_eagerly=test_utils.should_run_eagerly(), ) keras.backend.track_tf_optimizer(optimizer) self.assertEqual( keras.backend.get_value(model.optimizer.iterations), 0 ) model.fit( np.random.random((55, 3)), np.random.random((55, 2)), epochs=1, batch_size=5, verbose=0, ) self.assertEqual( keras.backend.get_value(model.optimizer.iterations), 11 ) def test_negative_clipvalue_or_clipnorm(self): with self.assertRaises(ValueError): _ = optimizer_v1.SGD(lr=0.01, clipvalue=-0.5) with self.assertRaises(ValueError): _ = optimizer_v1.Adam(clipnorm=-2.0) def test_mixed_precision_loss_scale_optimizer(self): if tf.executing_eagerly(): self.skipTest("v1 optimizer does not run in eager mode") optimizer = MixedPrecisionLossScaleOptimizer(AdamOptimizer(), "dynamic") model = keras.models.Sequential() model.add( keras.layers.Dense( 2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1), ) ) model.compile( loss="mean_squared_error", optimizer=optimizer, run_eagerly=test_utils.should_run_eagerly(), ) model.fit( np.random.random((5, 3)), np.random.random((5, 2)), epochs=1, batch_size=5, verbose=0, ) def test_deserialization_error(self): with self.assertRaisesRegex( ValueError, "Could not interpret optimizer" ): keras.optimizers.get(0) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/optimizers/optimizer_v1_test.py/0
{ "file_path": "tf-keras/tf_keras/optimizers/optimizer_v1_test.py", "repo_id": "tf-keras", "token_count": 5414 }
202
# Copyright 2019 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 TF-Keras losses serialization.""" import os import shutil import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized import tf_keras as keras from tf_keras import layers from tf_keras import losses from tf_keras.optimizers import legacy as optimizer_legacy from tf_keras.testing_infra import test_combinations from tf_keras.testing_infra import test_utils from tf_keras.utils import losses_utils try: import h5py except ImportError: h5py = None # Custom loss class class MyMeanAbsoluteError(losses.LossFunctionWrapper): def __init__( self, reduction=losses_utils.ReductionV2.AUTO, name="mean_absolute_error", ): super().__init__(my_mae, name=name, reduction=reduction) # Custom loss function def my_mae(y_true, y_pred): return keras.backend.mean(tf.abs(y_pred - y_true), axis=-1) def _get_multi_io_model(): inp_1 = layers.Input(shape=(1,), name="input_1") inp_2 = layers.Input(shape=(1,), name="input_2") d = test_utils.Bias(name="output") out_1 = d(inp_1) out_2 = d(inp_2) return keras.Model([inp_1, inp_2], [out_1, out_2]) @test_combinations.run_all_keras_modes @parameterized.named_parameters( [ dict(testcase_name="string", value="mae"), dict(testcase_name="built_in_fn", value=losses.mae), dict(testcase_name="built_in_class", value=losses.MeanAbsoluteError()), dict(testcase_name="custom_fn", value=my_mae), dict(testcase_name="custom_class", value=MyMeanAbsoluteError()), dict(testcase_name="list_of_strings", value=["mae", "mae"]), dict( testcase_name="list_of_built_in_fns", value=[losses.mae, losses.mae] ), dict( testcase_name="list_of_built_in_classes", value=[losses.MeanAbsoluteError(), losses.MeanAbsoluteError()], ), dict(testcase_name="list_of_custom_fns", value=[my_mae, my_mae]), dict( testcase_name="list_of_custom_classes", value=[MyMeanAbsoluteError(), MyMeanAbsoluteError()], ), dict( testcase_name="dict_of_string", value={ "output": "mae", "output_1": "mae", }, ), dict( testcase_name="dict_of_built_in_fn", value={ "output": losses.mae, "output_1": losses.mae, }, ), dict( testcase_name="dict_of_built_in_class", value={ "output": losses.MeanAbsoluteError(), "output_1": losses.MeanAbsoluteError(), }, ), dict( testcase_name="dict_of_custom_fn", value={"output": my_mae, "output_1": my_mae}, ), dict( testcase_name="dict_of_custom_class", value={ "output": MyMeanAbsoluteError(), "output_1": MyMeanAbsoluteError(), }, ), ] ) class LossesSerialization(test_combinations.TestCase): def setUp(self): super(LossesSerialization, self).setUp() tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir) self.model_filename = os.path.join(tmpdir, "tmp_model_loss.h5") self.x = np.array([[0.0], [1.0], [2.0]], dtype="float32") self.y = np.array([[0.5], [2.0], [3.5]], dtype="float32") self.w = np.array([1.25, 0.5, 1.25], dtype="float32") def test_serializing_model_with_loss_with_custom_object_scope(self, value): with keras.utils.custom_object_scope( { "MyMeanAbsoluteError": MyMeanAbsoluteError, "my_mae": my_mae, "Bias": test_utils.Bias, } ): model = _get_multi_io_model() model.compile( optimizer_legacy.gradient_descent.SGD(0.1), loss=value, run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit( [self.x, self.x], [self.y, self.y], batch_size=3, epochs=3, sample_weight=[self.w, self.w], ) # Assert training. self.assertAllClose(history.history["loss"], [2.0, 1.6, 1.2], 1e-3) eval_results = model.evaluate( [self.x, self.x], [self.y, self.y], sample_weight=[self.w, self.w], ) if h5py is None: return model.save(self.model_filename) loaded_model = keras.models.load_model(self.model_filename) loaded_model.predict([self.x, self.x]) loaded_eval_results = loaded_model.evaluate( [self.x, self.x], [self.y, self.y], sample_weight=[self.w, self.w], ) # Assert all evaluation results are the same. self.assertAllClose(eval_results, loaded_eval_results, 1e-9) def test_serializing_model_with_loss_with_custom_objects(self, value): model = _get_multi_io_model() model.compile( optimizer_legacy.gradient_descent.SGD(0.1), loss=value, run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit( [self.x, self.x], [self.y, self.y], batch_size=3, epochs=3, sample_weight=[self.w, self.w], ) # Assert training. self.assertAllClose(history.history["loss"], [2.0, 1.6, 1.2], 1e-3) eval_results = model.evaluate( [self.x, self.x], [self.y, self.y], sample_weight=[self.w, self.w] ) if h5py is None: return model.save(self.model_filename) loaded_model = keras.models.load_model( self.model_filename, custom_objects={ "MyMeanAbsoluteError": MyMeanAbsoluteError, "my_mae": my_mae, "Bias": test_utils.Bias, }, ) loaded_model.predict([self.x, self.x]) loaded_eval_results = loaded_model.evaluate( [self.x, self.x], [self.y, self.y], sample_weight=[self.w, self.w] ) # Assert all evaluation results are the same. self.assertAllClose(eval_results, loaded_eval_results, 1e-9) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/saving/legacy/losses_serialization_test.py/0
{ "file_path": "tf-keras/tf_keras/saving/legacy/losses_serialization_test.py", "repo_id": "tf-keras", "token_count": 3559 }
203
# Copyright 2018 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. # ============================================================================== """Keras SavedModel deserialization.""" import re import types import warnings import tensorflow.compat.v1.logging as logging import tensorflow.compat.v2 as tf from google.protobuf import message from tf_keras import backend from tf_keras import regularizers from tf_keras.engine import input_spec from tf_keras.optimizers.legacy import optimizer_v2 from tf_keras.protobuf import saved_metadata_pb2 from tf_keras.protobuf import versions_pb2 from tf_keras.saving import object_registration from tf_keras.saving.legacy import model_config from tf_keras.saving.legacy import saving_utils from tf_keras.saving.legacy import serialization from tf_keras.saving.legacy.saved_model import constants from tf_keras.saving.legacy.saved_model import json_utils from tf_keras.saving.legacy.saved_model import utils from tf_keras.saving.legacy.saved_model.serialized_attributes import ( CommonEndpoints, ) from tf_keras.utils import layer_utils from tf_keras.utils import metrics_utils from tf_keras.utils import tf_inspect from tf_keras.utils.generic_utils import LazyLoader # To avoid circular dependencies between keras/engine and keras/saving, # code in keras/saving must delay imports. # TODO(b/134426265): Switch back to single-quotes to match the rest of the file # once the issue with copybara is fixed. models_lib = LazyLoader("models_lib", globals(), "tf_keras.models") base_layer = LazyLoader("base_layer", globals(), "tf_keras.engine.base_layer") layers_module = LazyLoader("layers_module", globals(), "tf_keras.layers") input_layer = LazyLoader( "input_layer", globals(), "tf_keras.engine.input_layer" ) functional_lib = LazyLoader( "functional_lib", globals(), "tf_keras.engine.functional" ) training_lib = LazyLoader("training_lib", globals(), "tf_keras.engine.training") training_lib_v1 = LazyLoader( "training_lib_v1", globals(), "tf_keras.engine.training_v1" ) metrics = LazyLoader("metrics", globals(), "tf_keras.metrics") base_rnn = LazyLoader("base_rnn", globals(), "tf_keras.layers.rnn.base_rnn") PUBLIC_ATTRIBUTES = CommonEndpoints.all_functions.union( CommonEndpoints.all_checkpointable_objects ) PUBLIC_ATTRIBUTES.add(constants.KERAS_ATTR) def load(path, compile=True, options=None): """Loads TF-Keras objects from a SavedModel. Any TF-Keras layer or model saved to the SavedModel will be loaded back as TF-Keras objects. Other objects are loaded as regular trackable objects (same as `tf.saved_model.load`). Currently, TF-Keras saving/loading only retains the TF-Keras object's weights, losses, and call function. The loaded model can be re-compiled, but the original optimizer, compiled loss functions, and metrics are not retained. This is temporary, and `model.save` will soon be able to serialize compiled models. Args: path: Path to SavedModel. compile: If true, compile the model after loading it. options: Optional `tf.saved_model.LoadOptions` object that specifies options for loading from SavedModel. Returns: Object loaded from SavedModel. """ # TODO(kathywu): Add saving/loading of optimizer, compiled losses and # metrics. # TODO(kathywu): Add code to load from objects that contain all endpoints # Look for metadata file or parse the SavedModel metadata = saved_metadata_pb2.SavedMetadata() meta_graph_def = tf.__internal__.saved_model.parse_saved_model( path ).meta_graphs[0] object_graph_def = meta_graph_def.object_graph_def path_to_metadata_pb = tf.io.gfile.join(path, constants.SAVED_METADATA_PATH) if tf.compat.v1.gfile.Exists(path_to_metadata_pb): try: with tf.io.gfile.GFile(path_to_metadata_pb, "rb") as f: file_content = f.read() metadata.ParseFromString(file_content) except message.DecodeError as e: raise IOError( f"Cannot parse keras metadata at path {path_to_metadata_pb}: " f"Received error: {e}" ) else: logging.warning( "SavedModel saved prior to TF 2.5 detected when loading " "Keras model. Please ensure that you are saving the model " "with model.save() or tf.keras.models.save_model(), *NOT* " "tf.saved_model.save(). To confirm, there should be a file " 'named "keras_metadata.pb" in the SavedModel directory.' ) _read_legacy_metadata(object_graph_def, metadata, path) if not metadata.nodes: # When there are no TF-Keras objects, return the results from the core # loader return tf.saved_model.load(path, options=options) metadata = _update_to_current_version(metadata) # Recreate layers and metrics using the info stored in the metadata. keras_loader = KerasObjectLoader(metadata, object_graph_def) keras_loader.load_layers(compile=compile) # Generate a dictionary of all loaded nodes. nodes_to_load = {"root": None} for node_id, loaded_node in keras_loader.loaded_nodes.items(): nodes_to_load[keras_loader.get_path(node_id)] = loaded_node with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="Trying to load ShardedVariables" ) loaded = tf.__internal__.saved_model.load_partial( path, nodes_to_load, options=options ) # Finalize the loaded layers and remove the extra tracked dependencies. keras_loader.finalize_objects() keras_loader.del_tracking() model = loaded["root"] if isinstance(model, training_lib.Model) and compile: # TODO(kathywu): Use compiled objects from SavedModel, instead of # creating new objects from the training config. training_config = model._serialized_attributes["metadata"].get( "training_config", None ) if training_config is not None: model.compile( **saving_utils.compile_args_from_training_config( training_config ), from_serialized=True, ) saving_utils.try_build_compiled_arguments(model) if isinstance(model.optimizer, optimizer_v2.OptimizerV2): if model.optimizer.get_slot_names(): logging.warning( "Your optimizer uses slots. " "Slots cannot be restored from saved_model, " "as a result, your model is starting with " "a new initialized optimizer." ) else: logging.warning( "No training configuration found in save file, so the " "model was *not* compiled. Compile it manually." ) # Force variables and resources to initialize. if not tf.executing_eagerly(): sess = backend.get_session() # Variables are initialized by this call. sess.run( tf.compat.v1.get_collection( tf.compat.v1.GraphKeys.TABLE_INITIALIZERS ) ) return model def _update_to_current_version(metadata): """Applies version updates to the metadata proto for backwards compat.""" for node in metadata.nodes: if node.version.producer == 1 and node.identifier in [ constants.MODEL_IDENTIFIER, constants.SEQUENTIAL_IDENTIFIER, constants.NETWORK_IDENTIFIER, ]: node_metadata = json_utils.decode(node.metadata) save_spec = node_metadata.get("save_spec") if save_spec is not None: node_metadata["full_save_spec"] = ([save_spec], {}) node.metadata = json_utils.Encoder().encode(node_metadata) return metadata def _read_legacy_metadata(object_graph_def, metadata, path): """Builds a KerasMetadata proto from the SavedModel ObjectGraphDef.""" # Older SavedModels store the metadata directly in the proto instead of the # separate pb file. node_paths = _generate_object_paths(object_graph_def) for node_id, proto in enumerate(object_graph_def.nodes): if ( proto.WhichOneof("kind") == "user_object" and proto.user_object.identifier in constants.KERAS_OBJECT_IDENTIFIERS ): if not proto.user_object.metadata: raise ValueError( "Unable to create a TF-Keras model from SavedModel at " f"{path}. This SavedModel was exported with " "`tf.saved_model.save`, and lacks the TF-Keras metadata " "file. Please save your TF-Keras model by calling " "`model.save` or `tf.keras.models.save_model`. Note that " "you can still load this SavedModel with " "`tf.saved_model.load`." ) metadata.nodes.add( node_id=node_id, node_path=node_paths[node_id], version=versions_pb2.VersionDef( producer=1, min_consumer=1, bad_consumers=[] ), identifier=proto.user_object.identifier, metadata=proto.user_object.metadata, ) def _generate_object_paths(object_graph_def): """Traverses through an ObjectGraphDef and builds a map of all node paths.""" paths = {0: "root"} nodes_to_visit = [0] while nodes_to_visit: current_node = nodes_to_visit.pop() current_path = paths[current_node] for reference in object_graph_def.nodes[current_node].children: if reference.node_id in paths: continue paths[reference.node_id] = f"{current_path}.{reference.local_name}" nodes_to_visit.append(reference.node_id) return paths def _is_graph_network(layer): """Determines whether the layer is a graph network.""" if isinstance(layer, RevivedNetwork): return False elif isinstance(layer, functional_lib.Functional): return layer._is_graph_network or isinstance( layer, models_lib.Sequential ) return False class KerasObjectLoader: """Loader that recreates TF-Keras objects (e.g. layers, models). Layers and models are revived from either the config or SavedModel following these rules: 1. If object is a graph network (i.e. Sequential or Functional) then it will be initialized using the structure from the config only after the children layers have been created. Graph networks must be initialized with inputs and outputs, so all child layers must be created beforehand. 2. If object's config exists and the class can be found, then revive from config. 3. Object may have already been created if its parent was revived from config. In this case, do nothing. 4. If nothing of the above applies, compose the various artifacts from the SavedModel to create a subclassed layer or model. At this time, custom metrics are not supported. """ def __init__(self, metadata, object_graph_def): self._metadata = {x.node_id: x for x in metadata.nodes} self._proto = object_graph_def self._node_paths = { node_data.node_id: node_data.node_path for node_data in metadata.nodes } self.loaded_nodes = {} # Maps node path -> loaded node # Store all node ids that have already been traversed when tracking # nodes that were recreated from the config. self._traversed_nodes_from_config = set() # Maps model id -> (blank model obj, list of child layer or their node # ids) This tracks all layers in functional and sequential models. These # models are only reconstructed after all of their child layers have # been created. self.model_layer_dependencies = {} self._models_to_reconstruct = [] def del_tracking(self): """Removes tracked references that are only used when loading the model.""" # Now that the node object has been fully loaded, and the checkpoint has # been restored, the object no longer needs to track objects added from # SerializedAttributes. (Note that saving a training checkpoint still # functions correctly, because layers and variables are tracked # separately by the Layer object.) # TODO(kathywu): Instead of outright deleting these nodes (which would # make restoring from a different checkpoint tricky), mark them as extra # dependencies that are OK to overwrite. for node in self.loaded_nodes.values(): node = node[0] if not isinstance(node, base_layer.Layer): # Loaded nodes can contain other trackable objects created when # loading layers from the config, such as variables. continue for name in PUBLIC_ATTRIBUTES: node._delete_tracking(name) if isinstance(node, functional_lib.Functional): # Delete the temporary layer dependencies, which were used to # restore the checkpointed values. When the model is live, the # user can delete or add layers to the model at any time, so # these layer dependencies may be obsolete. dependencies = list(node._self_unconditional_dependency_names) for name in dependencies: if ( re.match(r"^layer(_with_weights)?-[\d+]", name) is not None ): node._delete_tracking(name) def _add_children_recreated_from_config(self, obj, proto, node_id): """Recursively records objects recreated from config.""" if node_id in self._traversed_nodes_from_config: return parent_path = self._node_paths[node_id] self._traversed_nodes_from_config.add(node_id) obj._maybe_initialize_trackable() if isinstance(obj, base_layer.Layer) and not obj.built: metadata = json_utils.decode(self._metadata[node_id].metadata) self._try_build_layer( obj, node_id, metadata.get("build_input_shape") ) # Create list of all possible children children = [] # Look for direct children for reference in proto.children: obj_child = obj._lookup_dependency(reference.local_name) children.append( (obj_child, reference.node_id, reference.local_name) ) # Add metrics that may have been added to the layer._metrics list. # This is stored in the SavedModel as layer.keras_api.layer_metrics in # SavedModels created after Tf 2.2. metric_list_node_id = self._search_for_child_node( node_id, [constants.KERAS_ATTR, "layer_metrics"] ) if metric_list_node_id is not None and hasattr(obj, "_metrics"): obj_metrics = {m.name: m for m in obj._metrics} for reference in self._proto.nodes[metric_list_node_id].children: metric = obj_metrics.get(reference.local_name) if metric is not None: metric_path = "{}.layer_metrics.{}".format( constants.KERAS_ATTR, reference.local_name ) children.append((metric, reference.node_id, metric_path)) for obj_child, child_id, child_name in children: child_proto = self._proto.nodes[child_id] if not isinstance(obj_child, tf.__internal__.tracking.Trackable): continue if ( child_proto.user_object.identifier in tf.__internal__.saved_model.load.registered_identifiers() ): setter = tf.__internal__.saved_model.load.get_setter( child_proto.user_object ) elif ( obj_child._object_identifier in constants.KERAS_OBJECT_IDENTIFIERS ): setter = _revive_setter else: setter = setattr if child_id in self.loaded_nodes: if self.loaded_nodes[child_id][0] is not obj_child: # This means that the same trackable object is referenced by # two different objects that were recreated from the config. logging.warning( "Looks like there is an object (perhaps variable or " "layer) that is shared between different " "layers/models. This may cause issues when restoring " "the variable values. Object: {}".format(obj_child) ) continue # Overwrite variable names with the ones saved in the SavedModel. if ( child_proto.WhichOneof("kind") == "variable" and child_proto.variable.name ): obj_child._handle_name = child_proto.variable.name + ":0" if isinstance( obj_child, tf.__internal__.tracking.TrackableDataStructure ): setter = lambda *args: None child_path = f"{parent_path}.{child_name}" self._node_paths[child_id] = child_path self._add_children_recreated_from_config( obj_child, child_proto, child_id ) self.loaded_nodes[child_id] = obj_child, setter def load_layers(self, compile=True): """Load all layer nodes from the metadata.""" # Load metrics after models and layers, since it's likely that models # and layers will create the metric when initialized (this avoids # wasting time by creating objects multiple times). metric_list = [] for node_metadata in self._metadata.values(): if node_metadata.identifier == constants.METRIC_IDENTIFIER: metric_list.append(node_metadata) continue self.loaded_nodes[node_metadata.node_id] = self._load_layer( node_metadata.node_id, node_metadata.identifier, node_metadata.metadata, ) for node_metadata in metric_list: try: self.loaded_nodes[node_metadata.node_id] = self._load_layer( node_metadata.node_id, node_metadata.identifier, node_metadata.metadata, ) except ValueError as e: # Metrics are only needed when the model is compiled later. We # ignore errors when trying to load custom metrics when # `compile=False` until custom metrics are serialized properly # (b/135550038). if compile: raise e logging.warning( "Unable to restore custom metric. Please ensure that " "the layer implements `get_config` and `from_config` " "when saving. In addition, please use the " "`custom_objects` arg when calling `load_model()`." ) def _load_layer(self, node_id, identifier, metadata): """Load a single layer from a SavedUserObject proto.""" metadata = json_utils.decode(metadata) # If node was already created if node_id in self.loaded_nodes: node, setter = self.loaded_nodes[node_id] # Revive setter requires the object to have a # `_serialized_attributes` property. Add it here. _maybe_add_serialized_attributes(node, metadata) config = metadata.get("config") if _is_graph_network(node) and serialization.validate_config( config ): child_nodes = self._get_child_layer_node_ids(node_id) self.model_layer_dependencies[node_id] = (node, child_nodes) if not child_nodes: self._models_to_reconstruct.append(node_id) return node, setter # Detect whether this object can be revived from the config. If not, # then revive from the SavedModel instead. obj, setter = self._revive_from_config(identifier, metadata, node_id) if obj is None: obj, setter = revive_custom_object(identifier, metadata) # Add an attribute that stores the extra functions/objects saved in the # SavedModel. Most of these functions/objects are ignored, but some are # used later in the loading process (e.g. the list of regularization # losses, or the training config of compiled models). _maybe_add_serialized_attributes(obj, metadata) return obj, setter def _revive_from_config(self, identifier, metadata, node_id): """Revives a layer/model from config, or returns None.""" if identifier == constants.METRIC_IDENTIFIER: obj = self._revive_metric_from_config(metadata) else: obj = self._revive_graph_network( identifier, metadata, node_id ) or self._revive_layer_or_model_from_config(metadata, node_id) if obj is None: return None, None setter = self._config_node_setter(_revive_setter) self._add_children_recreated_from_config( obj, self._proto.nodes[node_id], node_id ) return obj, setter def _revive_graph_network(self, identifier, metadata, node_id): """Revives a graph network from config.""" # Determine whether the metadata contains information for reviving a # functional or Sequential model. config = metadata.get("config") if not serialization.validate_config(config): return None class_name = tf.compat.as_str(metadata["class_name"]) if object_registration.get_registered_object(class_name) is not None: return None model_is_functional_or_sequential = ( metadata.get("is_graph_network", False) or class_name == "Sequential" or class_name == "Functional" ) if not model_is_functional_or_sequential: return None # Revive functional and sequential models as blank model objects for now # ( must be initialized to enable setattr tracking and attribute # caching). Reconstruction of the network is deferred until all of the # model's layers have been revived. if class_name == "Sequential": model = models_lib.Sequential(name=config["name"]) # The model is a custom Sequential model. elif identifier == constants.SEQUENTIAL_IDENTIFIER: # Uses the custom class name, since the config does not have one. model = models_lib.Sequential(name=class_name) else: model = models_lib.Functional( inputs=[], outputs=[], name=config["name"] ) # Record this model and its layers. This will later be used to # reconstruct the model. layers = self._get_child_layer_node_ids(node_id) self.model_layer_dependencies[node_id] = (model, layers) if not layers: self._models_to_reconstruct.append(node_id) return model def _revive_layer_or_model_from_config(self, metadata, node_id): """Revives a layer/custom model from config; returns None if infeasible.""" # Check that the following requirements are met for reviving from # config: # 1. Object can be deserialized from config. # 2. If the object needs to be built, then the build input shape can # be found. class_name = metadata.get("class_name") config = metadata.get("config") shared_object_id = metadata.get("shared_object_id") must_restore_from_config = metadata.get("must_restore_from_config") if not serialization.validate_config(config): return None try: try: obj = model_config.model_from_config( serialization.serialize_keras_class_and_config( class_name, config, shared_object_id=shared_object_id ) ) except (TypeError, KeyError) as e: # A name conflict has occurred. The `class_name` is in the Keras # native framework; however, the value in the framework is # different from the user's class definition which confuses the # KerasObjectLoader. builtin_layer = layers_module.get_builtin_layer(class_name) if builtin_layer: raise RuntimeError( f"Unable to restore object of class '{class_name}'. " "One of several possible causes could be " "a missing custom object. " "Decorate your custom object with " "`@keras.utils.register_keras_serializable()` and " "include that file in your program, " "or pass your class in a " "`keras.utils.CustomObjectScope` " "that wraps this load call. " f"\n\nException: {e}" ) from e else: raise except Exception as e: if must_restore_from_config: raise e else: return None # Use the dtype, name, and trainable status. Often times these are not # specified in custom configs, so retrieve their values from the # metadata. obj._name = metadata["name"] if metadata.get("trainable") is not None: obj.trainable = metadata["trainable"] if metadata.get("dtype") is not None: obj._set_dtype_policy(metadata["dtype"]) if metadata.get("stateful") is not None: obj.stateful = metadata["stateful"] if metadata.get("autocast") is not None: obj._autocast = metadata["autocast"] # Restore model save spec for subclassed models. (layers do not store a # SaveSpec) if isinstance(obj, training_lib.Model): full_save_spec = metadata.get("full_save_spec") if full_save_spec is not None: args_spec, kwargs_spec = full_save_spec inputs_spec = args_spec.pop(0) obj._set_save_spec(inputs_spec, args_spec, kwargs_spec) build_input_shape = metadata.get("build_input_shape") built = self._try_build_layer(obj, node_id, build_input_shape) if not built: # If the layer cannot be built, revive a custom layer instead. return None return obj def _revive_metric_from_config(self, metadata): """Revives a metric object using the config saved in the metadata.""" class_name = tf.compat.as_str(metadata["class_name"]) config = metadata.get("config") if not serialization.validate_config(config): return None try: obj = metrics.deserialize( serialization.serialize_keras_class_and_config( class_name, config ) ) except ValueError: return None build_input_shape = metadata.get("build_input_shape") if build_input_shape is not None and hasattr(obj, "_build"): obj._build(build_input_shape) return obj def _try_build_layer(self, obj, node_id, build_input_shape): """Attempts to build the layer.""" if obj.built or hasattr(obj.build, "_is_default"): obj.built = True return True if build_input_shape is None: build_input_shape = self._infer_inputs( node_id, convert_to_shapes=True ) if build_input_shape is not None: obj.build(build_input_shape) base_layer.Layer.build(obj, build_input_shape) return True return False def get_path(self, node_id): return self._node_paths[node_id] def finalize_objects(self): """Finish setting up TF-Keras objects. This function is executed after all objects and functions have been created. Call functions and losses are attached to each layer, and once all layers have been fully set up, graph networks are initialized. Subclassed models that are revived from the SavedModel are treated like layers, and have their call/loss functions attached here. """ # Finish setting up layers and subclassed models. This step attaches # call functions and losses to each object, and sets model # inputs/outputs. layers_revived_from_config = [] layers_revived_from_saved_model = [] for node_id, (node, _) in self.loaded_nodes.items(): if ( not isinstance(node, base_layer.Layer) # Don't finalize models until all layers have finished loading. or node_id in self.model_layer_dependencies ): continue self._unblock_model_reconstruction(node_id, node) if isinstance(node, input_layer.InputLayer): continue elif isinstance(node, metrics.Metric): continue if isinstance(node, (RevivedLayer, RevivedInputLayer)): layers_revived_from_saved_model.append(node) else: layers_revived_from_config.append(node) _finalize_saved_model_layers(layers_revived_from_saved_model) _finalize_config_layers(layers_revived_from_config) # Initialize graph networks, now that layer dependencies have been # resolved. self._reconstruct_all_models() def _unblock_model_reconstruction(self, layer_id, layer): """Removes layer from blocking model reconstruction.""" for model_id, v in self.model_layer_dependencies.items(): _, layers = v if layer_id not in layers: continue layers[layers.index(layer_id)] = layer if all(isinstance(x, base_layer.Layer) for x in layers): self._models_to_reconstruct.append(model_id) def _reconstruct_all_models(self): """Reconstructs the network structure of all models.""" all_initialized_models = set() while self._models_to_reconstruct: model_id = self._models_to_reconstruct.pop(0) all_initialized_models.add(model_id) model, layers = self.model_layer_dependencies[model_id] self._reconstruct_model(model_id, model, layers) _finalize_config_layers([model]) if all_initialized_models != set(self.model_layer_dependencies.keys()): # This should not happen. uninitialized_model_ids = ( set(self.model_layer_dependencies.keys()) - all_initialized_models ) uninitialized_model_names = [ self.model_layer_dependencies[model_id][0].name for model_id in uninitialized_model_ids ] raise ValueError( "Error loading model(s) in the SavedModel format. " "The following model(s) could not be initialized: " f"{uninitialized_model_names}" ) def _reconstruct_model(self, model_id, model, layers): """Reconstructs the network structure.""" config = json_utils.decode(self._metadata[model_id].metadata)["config"] # Set up model inputs if model.inputs: # Inputs may already be created if the model is instantiated in # another object's __init__. pass elif isinstance(model, models_lib.Sequential): if not layers or not isinstance(layers[0], input_layer.InputLayer): if config["layers"][0]["class_name"] == "InputLayer": layers.insert( 0, input_layer.InputLayer.from_config( config["layers"][0]["config"] ), ) elif "batch_input_shape" in config["layers"][0]["config"]: batch_input_shape = config["layers"][0]["config"][ "batch_input_shape" ] layers.insert( 0, input_layer.InputLayer( input_shape=batch_input_shape[1:], batch_size=batch_input_shape[0], dtype=layers[0].dtype, name=layers[0].name + "_input", ), ) model.__init__(layers, name=config["name"]) if not model.inputs: first_layer = self._get_child_layer_node_ids(model_id)[0] input_specs = self._infer_inputs(first_layer) input_shapes = self._infer_inputs( first_layer, convert_to_shapes=True ) model._set_inputs(input_specs) if not model.built and not isinstance(input_specs, dict): model.build(input_shapes) else: # Reconstruct functional model ( inputs, outputs, created_layers, ) = functional_lib.reconstruct_from_config( config, created_layers={layer.name: layer for layer in layers} ) model.__init__(inputs, outputs, name=config["name"]) functional_lib.connect_ancillary_layers(model, created_layers) # Set model dtype. _set_network_attributes_from_metadata(model) # Unblock models that are dependent on this model. self._unblock_model_reconstruction(model_id, model) def _get_child_layer_node_ids(self, node_id): """Returns the node ids of each layer in a Sequential/Functional model.""" # Sequential and Functional track layers with names following the format # "layer-N". Use this to generate the list of layers. num_layers = 0 child_layers = {} pattern = re.compile("layer-(\\d+)") for child in self._proto.nodes[node_id].children: m = pattern.match(child.local_name) if m is None: continue layer_n = int(m.group(1)) num_layers = max(layer_n + 1, num_layers) child_layers[layer_n] = child.node_id ordered = [] for n in range(num_layers): child = child_layers.get(n) if child is None: break ordered.append(child) return ordered def _search_for_child_node(self, parent_id, path_to_child): """Returns node id of child node. A helper method for traversing the object graph proto. As an example, say that the object graph proto in the SavedModel contains an object with the following child and grandchild attributes: `parent.child_a.child_b` This method can be used to retrieve the node id of `child_b` using the parent's node id by calling: `_search_for_child_node(parent_id, ['child_a', 'child_b'])`. Args: parent_id: node id of parent node path_to_child: list of children names. Returns: node_id of child, or None if child isn't found. """ if not path_to_child: return parent_id for child in self._proto.nodes[parent_id].children: if child.local_name == path_to_child[0]: return self._search_for_child_node( child.node_id, path_to_child[1:] ) return None def _infer_inputs(self, layer_node_id, convert_to_shapes=False): """Infers input shape of layer from SavedModel functions.""" call_fn_id = self._search_for_child_node( layer_node_id, ["call_and_return_all_conditional_losses"] ) if call_fn_id is None: return None concrete_functions = self._proto.nodes[ call_fn_id ].function.concrete_functions if not concrete_functions: return None call_fn_name = concrete_functions[0] call_fn_proto = self._proto.concrete_functions[call_fn_name] structured_input_signature = tf.__internal__.saved_model.decode_proto( call_fn_proto.canonicalized_input_signature ) inputs = structured_input_signature[0][0] if convert_to_shapes: return tf.nest.map_structure(lambda spec: spec.shape, inputs) else: return inputs def _config_node_setter(self, setter): """Creates edges for nodes that are recreated from config.""" def setattr_wrapper(obj, name, value): # Avoid overwriting attributes of objects recreated from the config. if obj._lookup_dependency(name) is None: setter(obj, name, value) return setattr_wrapper def _finalize_saved_model_layers(layers): """Runs the final steps of loading TF-Keras Layers from SavedModel.""" # 1. Set up call functions for all layers initialized from the SavedModel ( # and not the config) for layer in layers: layer.built = True layer_call = getattr( _get_keras_attr(layer), "call_and_return_conditional_losses", None ) if layer_call and layer_call.concrete_functions: call_spec = layer_utils.CallFunctionSpec( tf_inspect.getfullargspec(layer_call) ) layer.call = utils.use_wrapped_call( layer, layer_call, call_spec, return_method=True ) expects_training_arg = layer._serialized_attributes["metadata"][ "expects_training_arg" ] if "training" in layer_call.function_spec.arg_names: # This could change the value of `expects_training_arg` if this # layer doesn't expect a training arg, but has a child layer # that does. expects_training_arg = True layer._init_call_fn_args(expects_training_arg) else: layer.call = types.MethodType( _unable_to_call_layer_due_to_serialization_issue, layer ) for layer in layers: # 2. Set model inputs and outputs. if isinstance(layer, RevivedNetwork): _set_network_attributes_from_metadata(layer) if hasattr( _get_keras_attr(layer), "call_and_return_conditional_losses" ): call_fn = _get_keras_attr( layer ).call_and_return_conditional_losses if not call_fn.concrete_functions: continue if call_fn.input_signature is None: args, kwargs = infer_inputs_from_restored_call_function( call_fn ) args = list(args) inputs = args.pop(0) else: args = call_fn.input_signature args = list(args) inputs = args.pop(0) kwargs = None layer._set_save_spec(inputs, args, kwargs) # V1 models require calling _set_inputs to set the `.inputs` # attr. Skip this step when there are multiple tensor inputs # (this behavior is not well supported in V1 models). if not any( isinstance(x, tf.TensorSpec) for x in tf.nest.flatten([args, kwargs]) ): layer._set_inputs(inputs) # 3. Add losses that aren't generated by the layer.call function. _restore_layer_unconditional_losses(layer) _restore_layer_activation_loss(layer) # 4. Restore metrics list _restore_layer_metrics(layer) def _unable_to_call_layer_due_to_serialization_issue( layer, *unused_args, **unused_kwargs ): """Replaces the `layer.call` if the layer was not fully serialized. TF-Keras Model/Layer serialization is relatively relaxed because SavedModels are not always loaded back as keras models. Thus, when there is an issue tracing a non-signature function, a warning is logged instead of raising an error. This results in a SavedModel where the model's call function is saved, but the internal layer call functions are not. When deserialized with `tf.keras.models.load_model`, the internal layers which do not have serialized call functions should raise an error when called. Args: layer: Layer without the serialized call function. Raises: ValueError """ raise ValueError( f"Cannot call custom layer {layer.name} of type {type(layer)}, because " "the call function was not serialized to the SavedModel." "Please try one of the following methods to fix this issue:" "\n\n(1) Implement `get_config` and `from_config` in the layer/model " "class, and pass the object to the `custom_objects` argument when " "loading the model. For more details, see: " "https://www.tensorflow.org/guide/keras/save_and_serialize" "\n\n(2) Ensure that the subclassed model or layer overwrites `call` " "and not `__call__`. The input shape and dtype will be automatically " "recorded when the object is called, and used when saving. To manually " "specify the input shape/dtype, decorate the call function with " "`@tf.function(input_signature=...)`." ) def _finalize_config_layers(layers): """Runs the final steps of loading TF-Keras Layers from config.""" for layer in layers: # It is assumed that layers define their unconditional losses after # being recreated from the config and built. The exceptions to this are # Functional and Sequential models, which only store conditional losses # (losses dependent on the inputs) in the config. Unconditional losses # like weight regularization must be revived from the SavedModel. if _is_graph_network(layer): _restore_layer_unconditional_losses(layer) # Some layers, like Dense, record their activation loss function in the # config. However, not all layers do this, so the activation loss may be # missing when restored from the config/hdf5. # TODO(kathywu): Investigate ways to improve the config to ensure # consistent loading behavior between HDF5 and SavedModel. _restore_layer_activation_loss(layer) # Restore metrics list. _restore_layer_metrics(layer) # Restore RNN layer states. if ( isinstance(layer, base_rnn.RNN) and layer.stateful and hasattr(_get_keras_attr(layer), "states") ): layer.states = getattr(_get_keras_attr(layer), "states", None) for variable in tf.nest.flatten(layer.states): backend.track_variable(variable) # Perform any layer defined finalization of the layer state. layer.finalize_state() def _finalize_metric(metric): metric.update_state = types.MethodType( metrics_utils.update_state_wrapper(metric.keras_api.update_state), metric, ) metric.result = metric.keras_api.result def _restore_layer_unconditional_losses(layer): """Restore unconditional losses from SavedModel.""" if hasattr(_get_keras_attr(layer), "layer_regularization_losses"): losses = getattr( _get_keras_attr(layer), "layer_regularization_losses", [] ) else: # Some earlier SavedModels may not have layer_regularization_losses # serialized separately. Fall back to using the regularization_losses # list if it does not exist. losses = layer._serialized_attributes.get("regularization_losses", []) for loss in losses: layer.add_loss(loss) def _restore_layer_activation_loss(layer): """Restore actiation loss from SavedModel.""" # Use wrapped activity regularizer function if the layer's activity # regularizer wasn't created during initialization. activity_regularizer = getattr( _get_keras_attr(layer), "activity_regularizer_fn", None ) if activity_regularizer and not layer.activity_regularizer: try: layer.activity_regularizer = activity_regularizer except AttributeError: # This may happen if a layer wrapper is saved with an activity # regularizer. The wrapper object's activity regularizer is # unsettable. pass def revive_custom_object(identifier, metadata): """Revives object from SavedModel.""" if tf.compat.v1.executing_eagerly_outside_functions(): model_class = training_lib.Model else: model_class = training_lib_v1.Model revived_classes = { constants.INPUT_LAYER_IDENTIFIER: ( RevivedInputLayer, input_layer.InputLayer, ), constants.LAYER_IDENTIFIER: (RevivedLayer, base_layer.Layer), constants.MODEL_IDENTIFIER: (RevivedNetwork, model_class), constants.NETWORK_IDENTIFIER: ( RevivedNetwork, functional_lib.Functional, ), constants.SEQUENTIAL_IDENTIFIER: ( RevivedNetwork, models_lib.Sequential, ), } parent_classes = revived_classes.get(identifier, None) class_name = tf.compat.as_str(metadata["class_name"]) if parent_classes is not None: parent_classes = revived_classes[identifier] revived_cls = type(class_name, parent_classes, {}) return revived_cls._init_from_metadata(metadata) else: raise ValueError( f'Unable to restore custom object of class "{class_name}" ' f"(type {identifier}). Please make sure that this class is " "included in the `custom_objects` arg when calling `load_model()`. " "Also, check that the class implements `get_config` and " f"`from_config`.\n\nComplete metadata: {metadata}" ) def _restore_layer_metrics(layer): metrics_list = getattr(_get_keras_attr(layer), "layer_metrics", {}) layer_metrics = {m.name: m for m in layer._metrics} for name, metric in metrics_list.items(): if name not in layer_metrics: # Metrics may be added during initialization/building of custom # layers. layer._metrics.append(metric) # TODO(kathywu): Centrally define keys and functions for both serialization and # deserialization. class RevivedLayer: """Keras layer loaded from a SavedModel.""" @classmethod def _init_from_metadata(cls, metadata): """Create revived layer from metadata stored in the SavedModel proto.""" init_args = dict(name=metadata["name"], trainable=metadata["trainable"]) if metadata.get("dtype") is not None: init_args["dtype"] = metadata["dtype"] if metadata.get("batch_input_shape") is not None: init_args["batch_input_shape"] = metadata["batch_input_shape"] revived_obj = cls(**init_args) with utils.no_automatic_dependency_tracking_scope(revived_obj): revived_obj._call_spec.expects_training_arg = metadata[ "expects_training_arg" ] config = metadata.get("config") if serialization.validate_config(config): revived_obj._config = config if metadata.get("input_spec") is not None: revived_obj.input_spec = recursively_deserialize_keras_object( metadata["input_spec"], module_objects={"InputSpec": input_spec.InputSpec}, ) if metadata.get("activity_regularizer") is not None: revived_obj.activity_regularizer = regularizers.deserialize( metadata["activity_regularizer"] ) if metadata.get("_is_feature_layer") is not None: revived_obj._is_feature_layer = metadata["_is_feature_layer"] if metadata.get("stateful") is not None: revived_obj.stateful = metadata["stateful"] if metadata.get("autocast") is not None: revived_obj._autocast = metadata["autocast"] if metadata.get("preserve_input_structure_in_config") is not None: revived_obj._preserve_input_structure_in_config = metadata[ "preserve_input_structure_in_config" ] return revived_obj, _revive_setter @property def keras_api(self): return self._serialized_attributes.get(constants.KERAS_ATTR, None) def get_config(self): if hasattr(self, "_config"): return self._config else: raise NotImplementedError def _revive_setter(layer, name, value): """Setter function that saves some attributes to separate dictionary.""" # Many attributes in the SavedModel conflict with properties defined in # Layer and Model. Save these attributes to a separate dictionary. if name in PUBLIC_ATTRIBUTES: if isinstance(value, tf.__internal__.tracking.Trackable): layer._track_trackable(value, name=name) layer._serialized_attributes[name] = value elif ( isinstance(layer, functional_lib.Functional) and re.match(r"^layer(_with_weights)?-[\d+]", name) is not None ): # Edges named "layer-n" or "layer_with_weights-n", which are tracked in # network._track_layers, should not be added as an attribute. They # should be temporarily added as a dependency so that checkpointed # values can be restored. These dependencies are manually deleted in # KerasObjectLoader.del_tracking. # Set `overwrite=True` in the case that `layer` already tracks a # different layer-n. This may cause variable values to not be loaded # properly in the original layer-n, but we already warn the users about # this (ctrl-f "shared between different layers/models"). layer._track_trackable(value, name, overwrite=True) elif getattr(layer, name, None) is not None: # Don't overwrite already defined attributes. pass else: setattr(layer, name, value) class RevivedInputLayer: """InputLayer loaded from a SavedModel.""" @classmethod def _init_from_metadata(cls, metadata): """Revives the saved InputLayer from the Metadata.""" init_args = dict( name=metadata["name"], dtype=metadata["dtype"], sparse=metadata["sparse"], ragged=metadata["ragged"], batch_input_shape=metadata["batch_input_shape"], ) revived_obj = cls(**init_args) with utils.no_automatic_dependency_tracking_scope(revived_obj): revived_obj._config = metadata["config"] return revived_obj, setattr def get_config(self): return self._config def recursively_deserialize_keras_object(config, module_objects=None): """Deserialize TF-Keras object from a nested structure.""" if isinstance(config, dict): if "class_name" in config: return serialization.deserialize_keras_object( config, module_objects=module_objects ) else: return { key: recursively_deserialize_keras_object( config[key], module_objects ) for key in config } elif isinstance(config, (tuple, list)): return [ recursively_deserialize_keras_object(x, module_objects) for x in config ] else: raise ValueError( "Unable to decode TF-Keras layer config. Config should be a " f"dictionary, tuple or list. Received: config={config}" ) def infer_inputs_from_restored_call_function(fn): """Returns TypeSpec of inputs from a restored call function. Args: fn: Restored layer call function. It is assumed that `fn` has at least one concrete function and that the inputs are in the first argument. Returns: TypeSpec of call function inputs in the form of (args, kwargs) """ def common_spec(x, y): if not isinstance(x, tf.TypeSpec): # Doesn't particularly matter what is returned in this case because # the result will be filtered out in _set_input_shape. return x result = x._without_tensor_names().most_specific_common_supertype( [y._without_tensor_names()] ) if result is None: # Please file a bug if you are being hindered by this error. raise TypeError(f"No common supertype of {x} and {y}.") return result spec = fn.concrete_functions[0].structured_input_signature for concrete in fn.concrete_functions[1:]: spec2 = concrete.structured_input_signature spec = tf.nest.map_structure(common_spec, spec, spec2) return spec class RevivedNetwork(RevivedLayer): """Keras network of layers loaded from a SavedModel.""" @classmethod def _init_from_metadata(cls, metadata): """Create revived network from metadata stored in the SavedModel proto.""" revived_obj = cls(name=metadata["name"]) # Store attributes revived from SerializedAttributes in a un-tracked # dictionary. The attributes are the ones listed in CommonEndpoints or # "keras_api" for keras-specific attributes. with utils.no_automatic_dependency_tracking_scope(revived_obj): revived_obj._call_spec.expects_training_arg = metadata[ "expects_training_arg" ] config = metadata.get("config") if serialization.validate_config(config): revived_obj._config = config if metadata.get("activity_regularizer") is not None: revived_obj.activity_regularizer = regularizers.deserialize( metadata["activity_regularizer"] ) if metadata.get("autocast") is not None: revived_obj._autocast = metadata["autocast"] return revived_obj, _revive_setter def _set_network_attributes_from_metadata(revived_obj): """Sets attributes recorded in the metadata.""" with utils.no_automatic_dependency_tracking_scope(revived_obj): metadata = revived_obj._serialized_attributes["metadata"] if metadata.get("dtype") is not None: revived_obj._set_dtype_policy(metadata["dtype"]) revived_obj._trainable = metadata["trainable"] def _maybe_add_serialized_attributes(layer, metadata): # Store attributes revived from SerializedAttributes in a un-tracked # dictionary. The attributes are the ones listed in CommonEndpoints or # "keras_api" for keras-specific attributes. if not hasattr(layer, "_serialized_attributes"): with utils.no_automatic_dependency_tracking_scope(layer): layer._serialized_attributes = {"metadata": metadata} def _get_keras_attr(layer): return getattr(layer, "_serialized_attributes", {}).get( constants.KERAS_ATTR, None )
tf-keras/tf_keras/saving/legacy/saved_model/load.py/0
{ "file_path": "tf-keras/tf_keras/saving/legacy/saved_model/load.py", "repo_id": "tf-keras", "token_count": 24765 }
204
# Copyright 2021 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. # ============================================================================== """Saving utilities to support Python's Pickle protocol.""" import os import tempfile import tensorflow.compat.v2 as tf from tf_keras.saving import saving_lib def deserialize_model_from_bytecode(serialized_model): """Reconstruct a Model from the output of `serialize_model_as_bytecode`. Args: serialized_model: (bytes) return value from `serialize_model_as_bytecode`. Returns: TF-Keras Model instance. """ # Note: we don't use a RAM path for this because zipfile cannot write # to such paths. temp_dir = tempfile.mkdtemp() try: filepath = os.path.join(temp_dir, "model.keras") with open(filepath, "wb") as f: f.write(serialized_model) # When loading, direct import will work for most custom objects # though it will require get_config() to be implemented. # Some custom objects (e.g. an activation in a Dense layer, # serialized as a string by Dense.get_config()) will require # a custom_object_scope. model = saving_lib.load_model(filepath, safe_mode=False) except Exception as e: raise e else: return model finally: tf.io.gfile.rmtree(temp_dir) def serialize_model_as_bytecode(model): """Convert a TF-Keras Model into a bytecode representation for pickling. Args: model: TF-Keras Model instance. Returns: Tuple that can be read by `deserialize_from_bytecode`. """ # Note: we don't use a RAM path for this because zipfile cannot write # to such paths. temp_dir = tempfile.mkdtemp() try: filepath = os.path.join(temp_dir, "model.keras") saving_lib.save_model(model, filepath) with open(filepath, "rb") as f: data = f.read() except Exception as e: raise e else: return data finally: tf.io.gfile.rmtree(temp_dir)
tf-keras/tf_keras/saving/pickle_utils.py/0
{ "file_path": "tf-keras/tf_keras/saving/pickle_utils.py", "repo_id": "tf-keras", "token_count": 943 }
205
# Copyright 2019 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 add_loss API correctness.""" import numpy as np import tensorflow.compat.v2 as tf from tf_keras import Input from tf_keras import Model from tf_keras import Sequential from tf_keras import layers from tf_keras import losses from tf_keras.optimizers import legacy as optimizer_legacy from tf_keras.testing_infra import test_combinations from tf_keras.testing_infra import test_utils # isort: off from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training.rmsprop import ( RMSPropOptimizer, ) MAE = losses.MeanAbsoluteError mae = losses.mean_absolute_error def get_ctl_train_step(model): optimizer = optimizer_legacy.gradient_descent.SGD(0.05) def train_step(x, y, w=None): with tf.GradientTape() as tape: if w is not None: model([x, y, w]) else: model([x, y]) loss = tf.reduce_sum(model.losses) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) return loss return train_step # TODO(psv): Add tests cases where a model is used in loss function but is # not part of the training model. class TestAddLossCorrectness(test_combinations.TestCase): def setUp(self): super().setUp() self.x = np.array([[0.0], [1.0], [2.0]], dtype="float32") self.y = np.array([[0.5], [2.0], [3.5]], dtype="float32") self.w = np.array([[1.25], [0.5], [1.25]], dtype="float32") @test_combinations.run_all_keras_modes def test_loss_on_model_fit(self): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets], outputs) model.add_loss(MAE()(targets, outputs)) model.add_loss(tf.reduce_mean(mae(targets, outputs))) model.compile( optimizer_legacy.gradient_descent.SGD(0.05), run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit([self.x, self.y], batch_size=3, epochs=5) self.assertAllClose( history.history["loss"], [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3 ) @test_combinations.run_with_all_model_types(exclude_models=["sequential"]) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_loss_callable_on_model_fit(self): model = test_utils.get_model_from_layers( [test_utils.Bias()], input_shape=(1,) ) def callable_loss(): return tf.reduce_sum(model.weights) model.add_loss(callable_loss) model.compile( optimizer_legacy.gradient_descent.SGD(0.1), run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit(self.x, batch_size=3, epochs=5) self.assertAllClose( history.history["loss"], [0.0, -0.1, -0.2, -0.3, -0.4], 1e-3 ) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_loss_on_model_ctl(self): def get_model_and_train_step(): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets], outputs) model.add_loss(MAE()(targets, outputs)) model.add_loss(tf.reduce_mean(mae(targets, outputs))) return get_ctl_train_step(model) train_step = get_model_and_train_step() loss = [train_step(self.x, self.y) for _ in range(5)] self.assertAllClose(loss, [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3) train_step = tf.function(get_model_and_train_step()) loss = [train_step(self.x, self.y) for _ in range(5)] self.assertAllClose(loss, [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_loss_callable_on_model_ctl(self): def get_model_and_train_step(): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets], outputs) def callable_loss(): return tf.reduce_sum(model.weights) model.add_loss(callable_loss) return get_ctl_train_step(model) train_step = get_model_and_train_step() loss = [train_step(self.x, self.y) for _ in range(5)] self.assertAllClose(loss, [0.0, -0.05, -0.1, -0.15, -0.2], 1e-3) train_step = tf.function(get_model_and_train_step()) loss = [train_step(self.x, self.y) for _ in range(5)] self.assertAllClose(loss, [0.0, -0.05, -0.1, -0.15, -0.2], 1e-3) @test_combinations.run_all_keras_modes def test_loss_with_sample_weight_on_model_fit(self): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) sw = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets, sw], outputs) model.add_loss(MAE()(targets, outputs, sw)) model.add_loss(3 * tf.reduce_mean(sw * mae(targets, outputs))) model.compile( optimizer_legacy.gradient_descent.SGD(0.025), run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit([self.x, self.y, self.w], batch_size=3, epochs=5) self.assertAllClose( history.history["loss"], [4.0, 3.6, 3.2, 2.8, 2.4], 1e-3 ) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_loss_with_sample_weight_on_model_ctl(self): def get_model_and_train_step(): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) sw = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets, sw], outputs) model.add_loss(MAE()(targets, outputs, sw)) model.add_loss(tf.reduce_mean(sw * mae(targets, outputs))) return get_ctl_train_step(model) train_step = get_model_and_train_step() loss = [train_step(self.x, self.y, self.w) for _ in range(5)] self.assertAllClose(loss, [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3) train_step = tf.function(get_model_and_train_step()) loss = [train_step(self.x, self.y, self.w) for _ in range(5)] self.assertAllClose(loss, [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3) @test_combinations.run_all_keras_modes def test_loss_with_sample_weight_in_model_call(self): class MyModel(Model): def __init__(self): super().__init__() self.bias = test_utils.Bias() def call(self, inputs): outputs = self.bias(inputs[0]) self.add_loss(MAE()(inputs[1], outputs, inputs[2])) self.add_loss( tf.reduce_mean(inputs[2] * mae(inputs[1], outputs)) ) return outputs model = MyModel() model.predict([self.x, self.y, self.w]) model.compile( optimizer_legacy.gradient_descent.SGD(0.05), run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit([self.x, self.y, self.w], batch_size=3, epochs=5) self.assertEqual(len(model.losses), 2) self.assertAllClose( history.history["loss"], [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3 ) eval_out = model.evaluate([self.x, self.y, self.w]) self.assertAlmostEqual(eval_out, 1.0, 3) @test_combinations.run_all_keras_modes def test_loss_with_sample_weight_in_layer_call(self): class MyLayer(layers.Layer): def __init__(self): super().__init__() self.bias = test_utils.Bias() def call(self, inputs): out = self.bias(inputs[0]) self.add_loss(MAE()(inputs[1], out, inputs[2])) self.add_loss(tf.reduce_mean(inputs[2] * mae(inputs[1], out))) return out inputs = Input(shape=(1,)) targets = Input(shape=(1,)) sw = Input(shape=(1,)) outputs = MyLayer()([inputs, targets, sw]) model = Model([inputs, targets, sw], outputs) model.predict([self.x, self.y, self.w]) model.compile( optimizer_legacy.gradient_descent.SGD(0.05), run_eagerly=test_utils.should_run_eagerly(), ) history = model.fit([self.x, self.y, self.w], batch_size=3, epochs=5) self.assertAllClose( history.history["loss"], [2.0, 1.8, 1.6, 1.4, 1.2], 1e-3 ) output = model.evaluate([self.x, self.y, self.w]) self.assertAlmostEqual(output, 1.0, 3) output = model.test_on_batch([self.x, self.y, self.w]) self.assertAlmostEqual(output, 1.0, 3) @test_combinations.run_all_keras_modes def test_loss_on_layer(self): class MyLayer(layers.Layer): def call(self, inputs): self.add_loss(tf.reduce_sum(inputs)) return inputs inputs = Input((3,)) layer = MyLayer() outputs = layer(inputs) model = Model(inputs, outputs) self.assertLen(model.losses, 1) model.compile("sgd", "mse", run_eagerly=test_utils.should_run_eagerly()) loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(loss, 2 * 3) @test_combinations.run_all_keras_modes @test_combinations.run_with_all_model_types def test_activity_regularizer(self): loss = {} for reg in [None, "l2"]: model_layers = [ layers.Dense( 10, activation="relu", activity_regularizer=reg, kernel_initializer="ones", use_bias=False, ), layers.Dense( 1, activation="sigmoid", kernel_initializer="ones", use_bias=False, ), ] model = test_utils.get_model_from_layers( model_layers, input_shape=(10,) ) x = np.ones((10, 10), "float32") y = np.zeros((10, 1), "float32") optimizer = RMSPropOptimizer(learning_rate=0.001) model.compile( optimizer, "binary_crossentropy", run_eagerly=test_utils.should_run_eagerly(), ) model.fit(x, y, batch_size=2, epochs=5) loss[reg] = model.evaluate(x, y) self.assertLess(loss[None], loss["l2"]) @test_combinations.run_all_keras_modes @test_combinations.run_with_all_model_types def test_activity_regularizer_loss_value(self): layer = layers.Dense( 1, kernel_initializer="zeros", bias_initializer="ones", activity_regularizer="l2", ) model = test_utils.get_model_from_layers([layer], input_shape=(10,)) x = np.ones((10, 10), "float32") optimizer = RMSPropOptimizer(learning_rate=0.001) model.compile(optimizer, run_eagerly=test_utils.should_run_eagerly()) loss = model.test_on_batch(x) self.assertAlmostEqual(0.01, loss, places=4) @test_combinations.run_all_keras_modes def test_activity_regularizer_batch_independent(self): inputs = layers.Input(shape=(10,)) x = layers.Dense(10, activation="relu", activity_regularizer="l2")( inputs ) outputs = layers.Dense(1, activation="sigmoid")(x) model = Model(inputs, outputs) optimizer = RMSPropOptimizer(learning_rate=0.001) model.compile(optimizer, run_eagerly=test_utils.should_run_eagerly()) loss_small_batch = model.test_on_batch(np.ones((10, 10), "float32")) loss_big_batch = model.test_on_batch(np.ones((20, 10), "float32")) self.assertAlmostEqual(loss_small_batch, loss_big_batch, places=4) @test_combinations.run_all_keras_modes def test_with_shared_layer(self): class LayerWithLoss(layers.Layer): def call(self, inputs): self.add_loss(tf.reduce_sum(inputs)) return inputs * 2 shared_layer = LayerWithLoss() m = Sequential([shared_layer]) m2 = Sequential([shared_layer, m]) m2(tf.constant([1, 2, 3])) self.assertEqual(len(m2.losses), 2) self.assertAllClose(m2.losses, [6, 12]) @test_combinations.run_all_keras_modes def test_with_shared_nested_layer(self): class LayerWithLoss(layers.Layer): def call(self, inputs): self.add_loss(tf.reduce_sum(inputs)) return inputs * 2 class LayerWithNestedLayerWithLoss(layers.Layer): def __init__(self): super().__init__() self.loss_layer = LayerWithLoss() def call(self, inputs): return self.loss_layer(inputs) shared_layer = LayerWithNestedLayerWithLoss() m = Sequential([shared_layer]) m2 = Sequential([shared_layer, m]) m2(tf.constant([1, 2, 3])) self.assertLen(m2.losses, 2) self.assertAllClose(m2.losses, [6, 12]) @test_combinations.run_all_keras_modes def test_clear_losses(self): class LayerWithSharedNestedLossLayer(layers.Layer): def __init__(self): super().__init__() self.loss_layer = layers.ActivityRegularization(l2=0.001) self.add_weight(shape=(1,), regularizer="l2") def call(self, x): x = self.loss_layer(x) return self.loss_layer(x) inputs = Input(shape=(1,)) l = LayerWithSharedNestedLossLayer() # Weight loss + 2 activity losses. x1 = tf.ones((1, 1)) _ = l(x1) if not tf.executing_eagerly(): self.assertLen(l.get_losses_for(x1), 2) self.assertLen(l.get_losses_for(None), 1) x2 = tf.ones((1, 1)) _ = l(x2) if not tf.executing_eagerly(): self.assertLen(l.get_losses_for(x1), 2) self.assertLen(l.get_losses_for(x2), 2) self.assertLen(l.get_losses_for(None), 1) outputs = l(inputs) model = Model(inputs, outputs) if not tf.executing_eagerly(): self.assertLen(model.losses, 7) self.assertLen(l.get_losses_for(x1), 2) self.assertLen(l.get_losses_for(x2), 2) self.assertLen(l.get_losses_for(None), 1) x3 = tf.ones((1, 1)) model(x3) x4 = tf.ones((1, 1)) model(x4) if tf.executing_eagerly(): # Eager losses are cleared every `__call__`. self.assertLen(model.losses, 3) else: self.assertLen(model.losses, 11) self.assertLen(l.get_losses_for(x3), 2) self.assertLen(l.get_losses_for(x4), 2) self.assertLen(l.get_losses_for(None), 1) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_invalid_constant_input(self): inputs = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model(inputs, outputs) with self.assertRaisesRegex( ValueError, "Expected a symbolic Tensors or a callable for the loss value", ): model.add_loss(1.0) @test_combinations.run_all_keras_modes(always_skip_v1=True) def test_invalid_variable_input(self): inputs = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model(inputs, outputs) with self.assertRaisesRegex( ValueError, "Expected a symbolic Tensors or a callable for the loss value", ): model.add_loss(model.weights[0]) @test_combinations.run_all_keras_modes def test_add_entropy_loss_on_functional_model(self): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = test_utils.Bias()(inputs) model = Model([inputs, targets], outputs) model.add_loss(losses.binary_crossentropy(targets, outputs)) model.compile("sgd", run_eagerly=test_utils.should_run_eagerly()) with tf.compat.v1.test.mock.patch.object( logging, "warning" ) as mock_log: model.fit([self.x, self.y], batch_size=3, epochs=5) self.assertNotIn( "Gradients do not exist for variables", str(mock_log.call_args) ) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/tests/add_loss_correctness_test.py/0
{ "file_path": "tf-keras/tf_keras/tests/add_loss_correctness_test.py", "repo_id": "tf-keras", "token_count": 8553 }
206
# Copyright 2018 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 trackable object SavedModel save.""" import os import tensorflow.compat.v2 as tf from tf_keras.layers import core from tf_keras.optimizers.legacy import adam # isort: off from tensorflow.python.framework import ( test_util as tf_test_utils, ) class _ModelWithOptimizerUsingDefun(tf.train.Checkpoint): def __init__(self): self.dense = core.Dense(1) self.optimizer = adam.Adam(0.01) @tf.function( input_signature=( tf.TensorSpec([None, 2], tf.float32), tf.TensorSpec([None], tf.float32), ), ) def call(self, x, y): with tf.GradientTape() as tape: loss = tf.reduce_mean((self.dense(x) - y) ** 2.0) trainable_variables = self.dense.trainable_variables gradients = tape.gradient(loss, trainable_variables) self.optimizer.apply_gradients(zip(gradients, trainable_variables)) return {"loss": loss} class MemoryTests(tf.test.TestCase): def setUp(self): super().setUp() self._model = _ModelWithOptimizerUsingDefun() @tf_test_utils.assert_no_garbage_created def DISABLED_test_no_reference_cycles(self): x = tf.constant([[3.0, 4.0]]) y = tf.constant([2.0]) self._model.call(x, y) save_dir = os.path.join(self.get_temp_dir(), "saved_model") tf.saved_model.save(self._model, save_dir, self._model.call) if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/tests/saved_model_test.py/0
{ "file_path": "tf-keras/tf_keras/tests/saved_model_test.py", "repo_id": "tf-keras", "token_count": 815 }
207
# Description: # Contains the TF-Keras Utilities (internal TensorFlow version). # Placeholder: load unaliased py_library load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test") package( # copybara:uncomment default_applicable_licenses = ["//tf_keras:license"], # TODO(scottzhu): Remove non-keras deps from TF. default_visibility = ["//tf_keras:friends"], licenses = ["notice"], ) py_library( name = "utils", srcs = [ "__init__.py", "legacy/__init__.py", ], srcs_version = "PY3", deps = [ ":audio_dataset", ":data_utils", ":feature_space", ":generic_utils", ":image_dataset", ":image_utils", ":layer_utils", ":np_utils", ":sidecar_evaluator", ":steps_per_execution_tuning", ":text_dataset", ":timed_threads", ":timeseries_dataset", ":vis_utils", ], ) py_library( name = "control_flow_util", srcs = ["control_flow_util.py"], srcs_version = "PY3", deps = [], ) py_library( name = "kpl_test_utils", srcs = ["kpl_test_utils.py"], srcs_version = "PY3", deps = [ "//tf_keras", "//tf_keras/layers/preprocessing:string_lookup", ], ) py_library( name = "data_utils", srcs = ["data_utils.py"], srcs_version = "PY3", deps = [ ":generic_utils", ":io_utils", ":tf_inspect", ], ) py_library( name = "engine_utils", srcs = [ "conv_utils.py", "losses_utils.py", ], srcs_version = "PY3", deps = [ ":data_utils", ":io_utils", ":tf_utils", "//tf_keras:backend", ], ) py_library( name = "io_utils", srcs = ["io_utils.py"], srcs_version = "PY3", deps = [ ":keras_logging", "//:expect_tensorflow_installed", ], ) py_library( name = "keras_logging", srcs = ["keras_logging.py"], srcs_version = "PY3", ) py_library( name = "tf_utils", srcs = ["tf_utils.py"], srcs_version = "PY3", deps = [ ":object_identity", "//:expect_tensorflow_installed", ], ) py_library( name = "traceback_utils", srcs = ["traceback_utils.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "generic_utils", srcs = [ "generic_utils.py", ], srcs_version = "PY3", deps = [ ":io_utils", ":tf_contextlib", ":tf_inspect", "//:expect_numpy_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "mode_keys", srcs = [ "mode_keys.py", ], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "layer_utils", srcs = [ "kernelized_utils.py", "layer_utils.py", ], srcs_version = "PY3", deps = [ ":engine_utils", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras:backend", ], ) py_library( name = "metrics_utils", srcs = [ "metrics_utils.py", ], srcs_version = "PY3", deps = [ ":generic_utils", ":tf_utils", "//:expect_tensorflow_installed", ], ) py_library( name = "version_utils", srcs = [ "version_utils.py", ], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "np_utils", srcs = [ "np_utils.py", ], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "object_identity", srcs = ["object_identity.py"], srcs_version = "PY3", deps = [], ) py_library( name = "tf_contextlib", srcs = ["tf_contextlib.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "tf_inspect", srcs = ["tf_inspect.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "vis_utils", srcs = [ "vis_utils.py", ], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "image_utils", srcs = [ "image_utils.py", ], srcs_version = "PY3", deps = [ "//:expect_pillow_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "dataset_creator", srcs = [ "dataset_creator.py", ], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", ], ) py_library( name = "image_dataset", srcs = [ "dataset_utils.py", "image_dataset.py", ], srcs_version = "PY3", deps = [ ":image_utils", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/layers/preprocessing:image_preprocessing", ], ) py_library( name = "text_dataset", srcs = [ "dataset_utils.py", "text_dataset.py", ], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "timeseries_dataset", srcs = [ "timeseries_dataset.py", ], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "audio_dataset", srcs = [ "audio_dataset.py", ], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "sidecar_evaluator", srcs = ["sidecar_evaluator.py"], srcs_version = "PY3", deps = [ "//:expect_tensorboard_installed", "//:expect_tensorflow_installed", ], ) py_library( name = "feature_space", srcs = ["feature_space.py"], srcs_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras:backend", "//tf_keras/layers", ], ) py_library( name = "timed_threads", srcs = ["timed_threads.py"], srcs_version = "PY3", ) py_library( name = "steps_per_execution_tuning", srcs = ["steps_per_execution_tuning.py"], srcs_version = "PY3", deps = [ "//:expect_numpy_installed", ], ) tf_py_test( name = "steps_per_execution_tuning_test", srcs = ["steps_per_execution_tuning_test.py"], python_version = "PY3", deps = [ ":steps_per_execution_tuning", "//:expect_tensorflow_installed", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "sidecar_evaluator_test", size = "medium", srcs = ["sidecar_evaluator_test.py"], python_version = "PY3", deps = [ ":sidecar_evaluator", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "dataset_creator_test", srcs = ["dataset_creator_test.py"], python_version = "PY3", deps = [ ":dataset_creator", "//:expect_portpicker_installed", "//:expect_tensorflow_installed", "//tf_keras/distribute:multi_worker_testing_utils", "//tf_keras/engine", "//tf_keras/layers/core", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "dataset_utils_test", size = "medium", timeout = "moderate", srcs = ["dataset_utils_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "data_utils_test", size = "medium", srcs = ["data_utils_test.py"], python_version = "PY3", shard_count = 6, tags = [ "noasan", # times out "notsan", "optonly", # times out ], deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "generic_utils_test", size = "small", srcs = ["generic_utils_test.py"], python_version = "PY3", deps = [ ":generic_utils", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "version_utils_test", size = "small", srcs = ["version_utils_test.py"], python_version = "PY3", deps = [ ":version_utils", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "tf_utils_test", size = "small", srcs = ["tf_utils_test.py"], python_version = "PY3", deps = [ ":tf_utils", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "composite_tensor_support_test", size = "medium", srcs = ["composite_tensor_support_test.py"], python_version = "PY3", shard_count = 8, deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras:engine", "//tf_keras/layers", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "io_utils_test", size = "small", srcs = ["io_utils_test.py"], python_version = "PY3", tags = [ "no_windows", # TODO: needs investigation on Windows "notsan", ], deps = [ ":io_utils", ":keras_logging", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "layer_utils_test", size = "small", srcs = ["layer_utils_test.py"], python_version = "PY3", deps = [ ":layer_utils", ":tf_utils", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras:backend", "//tf_keras/dtensor", "//tf_keras/dtensor:layout_map", "//tf_keras/dtensor:test_util", ], ) tf_py_test( name = "np_utils_test", size = "small", srcs = ["np_utils_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "kernelized_utils_test", size = "small", srcs = ["kernelized_utils_test.py"], python_version = "PY3", deps = [ ":layer_utils", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", ], ) tf_py_test( name = "vis_utils_test", size = "small", srcs = ["vis_utils_test.py"], python_version = "PY3", shard_count = 4, tags = [ "no_oss", # TODO(b/318174391) ], deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "image_utils_test", size = "small", srcs = ["image_utils_test.py"], python_version = "PY3", shard_count = 4, tags = [ "no_pip", ], deps = [ ":image_utils", "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "conv_utils_test", size = "small", srcs = ["conv_utils_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "metrics_utils_test", size = "small", srcs = ["metrics_utils_test.py"], python_version = "PY3", deps = [ "//:expect_absl_installed", # absl/testing:parameterized "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "losses_utils_test", size = "small", srcs = ["losses_utils_test.py"], python_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "traceback_utils_test", size = "small", srcs = ["traceback_utils_test.py"], python_version = "PY3", deps = [ "//:expect_tensorflow_installed", "//tf_keras", ], ) tf_py_test( name = "image_dataset_test", size = "small", srcs = ["image_dataset_test.py"], python_version = "PY3", deps = [ ":image_dataset", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "text_dataset_test", size = "small", srcs = ["text_dataset_test.py"], python_version = "PY3", deps = [ ":text_dataset", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", ], ) tf_py_test( name = "timeseries_dataset_test", size = "small", srcs = ["timeseries_dataset_test.py"], python_version = "PY3", deps = [ ":timeseries_dataset", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "audio_dataset_test", size = "small", srcs = ["audio_dataset_test.py"], python_version = "PY3", deps = [ ":audio_dataset", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "audio_dataset_with_tfio_test", size = "small", srcs = ["audio_dataset_with_tfio_test.py"], python_version = "PY3", deps = [ ":audio_dataset", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//:expect_tensorflow_io_installed", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "feature_space_test", size = "medium", srcs = ["feature_space_test.py"], python_version = "PY3", deps = [ ":feature_space", "//:expect_numpy_installed", "//:expect_tensorflow_installed", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], ) tf_py_test( name = "timed_threads_test", size = "small", timeout = "moderate", srcs = ["timed_threads_test.py"], deps = [ ":timed_threads", "//:expect_tensorflow_installed", "//tf_keras", "//tf_keras/testing_infra:test_combinations", "//tf_keras/testing_infra:test_utils", ], )
tf-keras/tf_keras/utils/BUILD/0
{ "file_path": "tf-keras/tf_keras/utils/BUILD", "repo_id": "tf-keras", "token_count": 8132 }
208
# Copyright 2022 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 FeatureSpace utility.""" import os import tensorflow.compat.v2 as tf import tf_keras as keras from tf_keras import layers from tf_keras.testing_infra import test_combinations from tf_keras.testing_infra import test_utils from tf_keras.utils import feature_space @test_utils.run_v2_only class FeatureSpaceTest(test_combinations.TestCase): def _get_train_data_dict( self, as_dataset=False, as_tf_tensors=False, as_labeled_dataset=False ): data = { "float_1": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], "float_2": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], "float_3": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], "string_1": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], "string_2": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], "int_1": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "int_2": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "int_3": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], } if as_dataset: return tf.data.Dataset.from_tensor_slices(data) elif as_tf_tensors: return tf.nest.map_structure(tf.convert_to_tensor, data) elif as_labeled_dataset: labels = [0, 1, 0, 1, 0, 0, 1, 0, 1, 1] return tf.data.Dataset.from_tensor_slices((data, labels)) return data def test_basic_usage(self): fs = feature_space.FeatureSpace( features={ "float_1": "float", "float_2": "float_normalized", "float_3": "float_discretized", "string_1": "string_categorical", "string_2": "string_hashed", "int_1": "integer_categorical", "int_2": "integer_hashed", "int_3": "integer_categorical", }, crosses=[("float_3", "string_1"), ("string_2", "int_2")], output_mode="concat", ) # Test unbatched adapt fs.adapt(self._get_train_data_dict(as_dataset=True)) # Test batched adapt fs.adapt(self._get_train_data_dict(as_dataset=True).batch(4)) # Test unbatched call on raw data data = { key: value[0] for key, value in self._get_train_data_dict().items() } out = fs(data) self.assertEqual(out.shape.as_list(), [195]) # Test unbatched call on TF tensors data = self._get_train_data_dict(as_tf_tensors=True) data = {key: value[0] for key, value in data.items()} out = fs(data) self.assertEqual(out.shape.as_list(), [195]) # Test batched call on raw data out = fs(self._get_train_data_dict()) self.assertEqual(out.shape.as_list(), [10, 195]) # Test batched call on TF tensors out = fs(self._get_train_data_dict(as_tf_tensors=True)) self.assertEqual(out.shape.as_list(), [10, 195]) def test_output_mode_dict(self): fs = feature_space.FeatureSpace( features={ "float_1": "float", "float_2": "float_normalized", "float_3": "float_discretized", "string_1": "string_categorical", "string_2": "string_hashed", "int_1": "integer_categorical", "int_2": "integer_hashed", "int_3": "integer_categorical", }, crosses=[("float_3", "string_1"), ("string_2", "int_2")], output_mode="dict", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) # Test unbatched call on raw data data = { key: value[0] for key, value in self._get_train_data_dict().items() } out = fs(data) self.assertIsInstance(out, dict) self.assertLen(out, 10) self.assertEqual(out["string_1"].shape.as_list(), [11]) self.assertEqual(out["int_2"].shape.as_list(), [32]) self.assertEqual(out["string_2_X_int_2"].shape.as_list(), [32]) # Test batched call on raw data out = fs(self._get_train_data_dict()) self.assertIsInstance(out, dict) self.assertLen(out, 10) self.assertEqual(out["string_1"].shape.as_list(), [10, 11]) self.assertEqual(out["int_2"].shape.as_list(), [10, 32]) self.assertEqual(out["string_2_X_int_2"].shape.as_list(), [10, 32]) # Test batched call on TF tensors out = fs(self._get_train_data_dict(as_tf_tensors=True)) self.assertIsInstance(out, dict) self.assertLen(out, 10) self.assertEqual(out["string_1"].shape.as_list(), [10, 11]) self.assertEqual(out["int_2"].shape.as_list(), [10, 32]) self.assertEqual(out["string_2_X_int_2"].shape.as_list(), [10, 32]) def test_output_mode_dict_of_ints(self): cls = feature_space.FeatureSpace fs = feature_space.FeatureSpace( features={ "float_1": "float", "float_2": "float_normalized", "float_3": "float_discretized", "string_1": cls.string_categorical(output_mode="int"), "string_2": cls.string_hashed(num_bins=32, output_mode="int"), "int_1": cls.integer_categorical(output_mode="int"), "int_2": cls.integer_hashed(num_bins=32, output_mode="int"), "int_3": cls.integer_categorical(output_mode="int"), }, crosses=[ cls.cross( ("float_3", "string_1"), output_mode="int", crossing_dim=32 ), cls.cross( ("string_2", "int_2"), output_mode="int", crossing_dim=32 ), ], output_mode="dict", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) data = { key: value[0] for key, value in self._get_train_data_dict().items() } out = fs(data) self.assertIsInstance(out, dict) self.assertLen(out, 10) self.assertEqual(out["string_1"].shape.as_list(), [1]) self.assertEqual(out["string_1"].dtype.name, "int64") self.assertEqual(out["int_2"].shape.as_list(), [1]) self.assertEqual(out["int_2"].dtype.name, "int64") self.assertEqual(out["string_2_X_int_2"].shape.as_list(), [1]) self.assertEqual(out["string_2_X_int_2"].dtype.name, "int64") def test_functional_api_sync_processing(self): fs = feature_space.FeatureSpace( features={ "float_1": "float", "float_2": "float_normalized", "float_3": "float_discretized", "string_1": "string_categorical", "string_2": "string_hashed", "int_1": "integer_categorical", "int_2": "integer_hashed", "int_3": "integer_categorical", }, crosses=[("float_3", "string_1"), ("string_2", "int_2")], output_mode="concat", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) inputs = fs.get_inputs() features = fs.get_encoded_features() outputs = layers.Dense(1)(features) model = keras.Model(inputs=inputs, outputs=outputs) model.compile("adam", "mse") ds = self._get_train_data_dict(as_labeled_dataset=True) model.fit(ds.batch(4)) model.evaluate(ds.batch(4)) ds = self._get_train_data_dict(as_dataset=True) model.predict(ds.batch(4)) def test_tf_data_async_processing(self): fs = feature_space.FeatureSpace( features={ "float_1": "float", "float_2": "float_normalized", "float_3": "float_discretized", "string_1": "string_categorical", "string_2": "string_hashed", "int_1": "integer_categorical", "int_2": "integer_hashed", "int_3": "integer_categorical", }, crosses=[("float_3", "string_1"), ("string_2", "int_2")], output_mode="concat", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) features = fs.get_encoded_features() outputs = layers.Dense(1)(features) model = keras.Model(inputs=features, outputs=outputs) model.compile("adam", "mse") ds = self._get_train_data_dict(as_labeled_dataset=True) # Try map before batch ds = ds.map(lambda x, y: (fs(x), y)) model.fit(ds.batch(4)) # Try map after batch ds = self._get_train_data_dict(as_labeled_dataset=True) ds = ds.batch(4) ds = ds.map(lambda x, y: (fs(x), y)) model.evaluate(ds) ds = self._get_train_data_dict(as_dataset=True) ds = ds.map(fs) model.predict(ds.batch(4)) def test_advanced_usage(self): cls = feature_space.FeatureSpace fs = feature_space.FeatureSpace( features={ "float_1": cls.float(), "float_2": cls.float_normalized(), "float_3": cls.float_discretized(num_bins=3), "string_1": cls.string_categorical(max_tokens=5), "string_2": cls.string_hashed(num_bins=32), "int_1": cls.integer_categorical( max_tokens=5, num_oov_indices=2 ), "int_2": cls.integer_hashed(num_bins=32), "int_3": cls.integer_categorical(max_tokens=5), }, crosses=[ cls.cross(("float_3", "string_1"), crossing_dim=32), cls.cross(("string_2", "int_2"), crossing_dim=32), ], output_mode="concat", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) data = { key: value[0] for key, value in self._get_train_data_dict().items() } out = fs(data) self.assertEqual(out.shape.as_list(), [148]) def test_manual_kpl(self): data = { "text": ["1st string", "2nd string", "3rd string"], } cls = feature_space.FeatureSpace # Test with a tf-idf TextVectorization layer tv = layers.TextVectorization(output_mode="tf_idf") fs = feature_space.FeatureSpace( features={ "text": cls.feature( preprocessor=tv, dtype="string", output_mode="float" ), }, output_mode="concat", ) fs.adapt(tf.data.Dataset.from_tensor_slices(data)) out = fs(data) self.assertEqual(out.shape.as_list(), [3, 5]) def test_no_adapt(self): data = { "int_1": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], } fs = feature_space.FeatureSpace( { "int_1": "integer_hashed", }, output_mode="concat", ) out = fs(data) self.assertEqual(out.shape.as_list(), [10, 32]) def test_saving(self): cls = feature_space.FeatureSpace fs = feature_space.FeatureSpace( features={ "float_1": cls.float(), "float_2": cls.float_normalized(), "float_3": cls.float_discretized(num_bins=3), "string_1": cls.string_categorical(max_tokens=5), "string_2": cls.string_hashed(num_bins=32), "int_1": cls.integer_categorical( max_tokens=5, num_oov_indices=2 ), "int_2": cls.integer_hashed(num_bins=32), "int_3": cls.integer_categorical(max_tokens=5), }, crosses=[ cls.cross(("float_3", "string_1"), crossing_dim=32), cls.cross(("string_2", "int_2"), crossing_dim=32), ], output_mode="concat", ) fs.adapt(self._get_train_data_dict(as_dataset=True)) data = { key: value[0] for key, value in self._get_train_data_dict().items() } ref_out = fs(data) temp_filepath = os.path.join(self.get_temp_dir(), "fs.keras") fs.save(temp_filepath) fs = keras.models.load_model(temp_filepath) # Save again immediately after loading to test idempotency temp_filepath = os.path.join(self.get_temp_dir(), "fs2.keras") fs.save(temp_filepath) # Test correctness of the first saved FS out = fs(data) self.assertAllClose(out, ref_out) inputs = fs.get_inputs() outputs = fs.get_encoded_features() model = keras.Model(inputs=inputs, outputs=outputs) ds = self._get_train_data_dict(as_dataset=True) out = model.predict(ds.batch(4)) self.assertAllClose(out[0], ref_out) # Test correctness of the re-saved FS fs = keras.models.load_model(temp_filepath) out = fs(data) self.assertAllClose(out, ref_out) def test_errors(self): # Test no features with self.assertRaisesRegex(ValueError, "cannot be None or empty"): feature_space.FeatureSpace(features={}) # Test no crossing dim with self.assertRaisesRegex(ValueError, "`crossing_dim`"): feature_space.FeatureSpace( features={ "f1": "integer_categorical", "f2": "integer_categorical", }, crosses=[("f1", "f2")], crossing_dim=None, ) # Test wrong cross feature name with self.assertRaisesRegex(ValueError, "should be present in "): feature_space.FeatureSpace( features={ "f1": "integer_categorical", "f2": "integer_categorical", }, crosses=[("f1", "unknown")], crossing_dim=32, ) # Test wrong output mode with self.assertRaisesRegex(ValueError, "for argument `output_mode`"): feature_space.FeatureSpace( features={ "f1": "integer_categorical", "f2": "integer_categorical", }, output_mode="unknown", ) # Test call before adapt with self.assertRaisesRegex(ValueError, "You need to call `.adapt"): fs = feature_space.FeatureSpace( features={ "f1": "integer_categorical", "f2": "integer_categorical", } ) fs({"f1": [0], "f2": [0]}) # Test get_encoded_features before adapt with self.assertRaisesRegex(ValueError, "You need to call `.adapt"): fs = feature_space.FeatureSpace( features={ "f1": "integer_categorical", "f2": "integer_categorical", } ) fs.get_encoded_features() if __name__ == "__main__": tf.test.main()
tf-keras/tf_keras/utils/feature_space_test.py/0
{ "file_path": "tf-keras/tf_keras/utils/feature_space_test.py", "repo_id": "tf-keras", "token_count": 8240 }
209
# Copyright 2018 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. # ============================================================================== """Utilities related to loss functions.""" import tensorflow.compat.v2 as tf from tf_keras import backend from tf_keras.engine import keras_tensor from tf_keras.utils import tf_utils # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export("keras.losses.Reduction", v1=[]) class ReductionV2: """Types of loss reduction. Contains the following values: * `AUTO`: Indicates that the reduction option will be determined by the usage context. For almost all cases this uses `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of built-in training loops such as `tf.keras` `compile` and `fit`, we expect reduction value to be `SUM` or `NONE`. Using `AUTO` in that case will raise an error. * `NONE`: No **additional** reduction is applied to the output of the wrapped loss function. When non-scalar losses are returned to Keras functions like `fit`/`evaluate`, the unreduced vector loss is passed to the optimizer but the reported loss will be a scalar value. Caution: **Verify the shape of the outputs when using** `Reduction.NONE`. The builtin loss functions wrapped by the loss classes reduce one dimension (`axis=-1`, or `axis` if specified by loss function). `Reduction.NONE` just means that no **additional** reduction is applied by the class wrapper. For categorical losses with an example input shape of `[batch, W, H, n_classes]` the `n_classes` dimension is reduced. For pointwise losses you must include a dummy axis so that `[batch, W, H, 1]` is reduced to `[batch, W, H]`. Without the dummy axis `[batch, W, H]` will be incorrectly reduced to `[batch, W]`. * `SUM`: Scalar sum of weighted losses. * `SUM_OVER_BATCH_SIZE`: Scalar `SUM` divided by number of elements in losses. This reduction type is not supported when used with `tf.distribute.Strategy` outside of built-in training loops like `tf.keras` `compile`/`fit`. You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: ``` with strategy.scope(): loss_obj = tf.keras.losses.CategoricalCrossentropy( reduction=tf.keras.losses.Reduction.NONE) .... loss = tf.reduce_sum(loss_obj(labels, predictions)) * (1. / global_batch_size) ``` Please see the [custom training guide]( https://www.tensorflow.org/tutorials/distribute/custom_training) for more details on this. """ AUTO = "auto" NONE = "none" SUM = "sum" SUM_OVER_BATCH_SIZE = "sum_over_batch_size" @classmethod def all(cls): return (cls.AUTO, cls.NONE, cls.SUM, cls.SUM_OVER_BATCH_SIZE) @classmethod def validate(cls, key): if key not in cls.all(): raise ValueError( f'Invalid Reduction Key: {key}. Expected keys are "{cls.all()}"' ) def remove_squeezable_dimensions( labels, predictions, expected_rank_diff=0, name=None ): """Squeeze last dim if ranks differ from expected by exactly 1. In the common case where we expect shapes to match, `expected_rank_diff` defaults to 0, and we squeeze the last dimension of the larger rank if they differ by 1. But, for example, if `labels` contains class IDs and `predictions` contains 1 probability per class, we expect `predictions` to have 1 more dimension than `labels`, so `expected_rank_diff` would be 1. In this case, we'd squeeze `labels` if `rank(predictions) - rank(labels) == 0`, and `predictions` if `rank(predictions) - rank(labels) == 2`. This will use static shape if available. Otherwise, it will add graph operations, which could result in a performance hit. Args: labels: Label values, a `Tensor` whose dimensions match `predictions`. predictions: Predicted values, a `Tensor` of arbitrary dimensions. expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. name: Name of the op. Returns: Tuple of `labels` and `predictions`, possibly with last dim squeezed. """ with backend.name_scope(name or "remove_squeezable_dimensions"): if not tf_utils.is_tensor_or_extension_type(predictions): predictions = tf.convert_to_tensor(predictions) if not tf_utils.is_tensor_or_extension_type(labels): labels = tf.convert_to_tensor(labels) predictions_shape = predictions.shape predictions_rank = predictions_shape.ndims labels_shape = labels.shape labels_rank = labels_shape.ndims if (labels_rank is not None) and (predictions_rank is not None): # Use static rank. rank_diff = predictions_rank - labels_rank if rank_diff == expected_rank_diff + 1 and predictions_shape.dims[ -1 ].is_compatible_with(1): predictions = tf.squeeze(predictions, [-1]) elif rank_diff == expected_rank_diff - 1 and labels_shape.dims[ -1 ].is_compatible_with(1): labels = tf.squeeze(labels, [-1]) return labels, predictions # Use dynamic rank. rank_diff = tf.rank(predictions) - tf.rank(labels) if (predictions_rank is None) or ( predictions_shape.dims[-1].is_compatible_with(1) ): predictions = tf.cond( tf.equal(expected_rank_diff + 1, rank_diff), lambda: tf.squeeze(predictions, [-1]), lambda: predictions, ) if (labels_rank is None) or ( labels_shape.dims[-1].is_compatible_with(1) ): labels = tf.cond( tf.equal(expected_rank_diff - 1, rank_diff), lambda: tf.squeeze(labels, [-1]), lambda: labels, ) return labels, predictions def squeeze_or_expand_dimensions(y_pred, y_true=None, sample_weight=None): """Squeeze or expand last dimension if needed. 1. Squeezes last dim of `y_pred` or `y_true` if their rank differs by 1 (using `remove_squeezable_dimensions`). 2. Squeezes or expands last dim of `sample_weight` if its rank differs by 1 from the new rank of `y_pred`. If `sample_weight` is scalar, it is kept scalar. This will use static shape if available. Otherwise, it will add graph operations, which could result in a performance hit. Args: y_pred: Predicted values, a `Tensor` of arbitrary dimensions. y_true: Optional label `Tensor` whose dimensions match `y_pred`. sample_weight: Optional weight scalar or `Tensor` whose dimensions match `y_pred`. Returns: Tuple of `y_pred`, `y_true` and `sample_weight`. Each of them possibly has the last dimension squeezed, `sample_weight` could be extended by one dimension. If `sample_weight` is None, (y_pred, y_true) is returned. """ y_pred_shape = y_pred.shape y_pred_rank = y_pred_shape.ndims if y_true is not None: # If sparse matrix is provided as `y_true`, the last dimension in # `y_pred` may be > 1. Eg: y_true = [0, 1, 2] (shape=(3,)), y_pred = # [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]] (shape=(3, 3)) In # this case, we should not try to remove squeezable dimension. y_true_shape = y_true.shape y_true_rank = y_true_shape.ndims if (y_true_rank is not None) and (y_pred_rank is not None): # Use static rank for `y_true` and `y_pred`. if (y_pred_rank - y_true_rank != 1) or y_pred_shape[-1] == 1: y_true, y_pred = remove_squeezable_dimensions(y_true, y_pred) else: # Use dynamic rank. rank_diff = tf.rank(y_pred) - tf.rank(y_true) squeeze_dims = lambda: remove_squeezable_dimensions(y_true, y_pred) is_last_dim_1 = tf.equal(1, tf.shape(y_pred)[-1]) maybe_squeeze_dims = lambda: tf.cond( is_last_dim_1, squeeze_dims, lambda: (y_true, y_pred) ) y_true, y_pred = tf.cond( tf.equal(1, rank_diff), maybe_squeeze_dims, squeeze_dims ) if sample_weight is None: return y_pred, y_true weights_shape = sample_weight.shape weights_rank = weights_shape.ndims if weights_rank == 0: # If weights is scalar, do nothing. return y_pred, y_true, sample_weight if (y_pred_rank is not None) and (weights_rank is not None): # Use static rank. if weights_rank - y_pred_rank == 1: sample_weight = tf.squeeze(sample_weight, [-1]) elif y_pred_rank - weights_rank == 1: sample_weight = tf.expand_dims(sample_weight, [-1]) return y_pred, y_true, sample_weight # Use dynamic rank. weights_rank_tensor = tf.rank(sample_weight) rank_diff = weights_rank_tensor - tf.rank(y_pred) maybe_squeeze_weights = lambda: tf.squeeze(sample_weight, [-1]) def _maybe_expand_weights(): expand_weights = lambda: tf.expand_dims(sample_weight, [-1]) return tf.cond( tf.equal(rank_diff, -1), expand_weights, lambda: sample_weight ) def _maybe_adjust_weights(): return tf.cond( tf.equal(rank_diff, 1), maybe_squeeze_weights, _maybe_expand_weights ) # squeeze or expand last dim of `sample_weight` if its rank differs by 1 # from the new rank of `y_pred`. sample_weight = tf.cond( tf.equal(weights_rank_tensor, 0), lambda: sample_weight, _maybe_adjust_weights, ) return y_pred, y_true, sample_weight def _safe_mean(losses, num_present): """Computes a safe mean of the losses. Args: losses: `Tensor` whose elements contain individual loss measurements. num_present: The number of measurable elements in `losses`. Returns: A scalar representing the mean of `losses`. If `num_present` is zero, then zero is returned. """ total_loss = tf.reduce_sum(losses) return tf.math.divide_no_nan(total_loss, num_present, name="value") def _num_elements(losses): """Computes the number of elements in `losses` tensor.""" with backend.name_scope("num_elements") as scope: return tf.cast(tf.size(losses, name=scope), dtype=losses.dtype) def reduce_weighted_loss( weighted_losses, reduction=ReductionV2.SUM_OVER_BATCH_SIZE ): """Reduces the individual weighted loss measurements.""" if reduction == ReductionV2.NONE: loss = weighted_losses else: loss = tf.reduce_sum(weighted_losses) if reduction == ReductionV2.SUM_OVER_BATCH_SIZE: loss = _safe_mean(loss, _num_elements(weighted_losses)) return loss @keras_export("keras.__internal__.losses.compute_weighted_loss", v1=[]) def compute_weighted_loss( losses, sample_weight=None, reduction=ReductionV2.SUM_OVER_BATCH_SIZE, name=None, ): """Computes the weighted loss. Args: losses: `Tensor` of shape `[batch_size, d1, ... dN]`. sample_weight: Optional `Tensor` whose rank is either 0, or the same rank as `losses`, or be broadcastable to `losses`. reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to loss. Default value is `SUM_OVER_BATCH_SIZE`. name: Optional name for the op. Raises: ValueError: If the shape of `sample_weight` is not compatible with `losses`. Returns: Weighted loss `Tensor` of the same type as `losses`. If `reduction` is `NONE`, this has the same shape as `losses`; otherwise, it is scalar. """ ReductionV2.validate(reduction) # If this function is called directly, then we just default 'AUTO' to # 'SUM_OVER_BATCH_SIZE'. Eg. Canned estimator use cases. if reduction == ReductionV2.AUTO: reduction = ReductionV2.SUM_OVER_BATCH_SIZE if sample_weight is None: sample_weight = 1.0 with backend.name_scope(name or "weighted_loss"): # Save the `reduction` argument for loss normalization when distributing # to multiple replicas. Used only for estimator + v1 optimizer flow. tf.compat.v1.get_default_graph()._last_loss_reduction = reduction if not isinstance(losses, (keras_tensor.KerasTensor, tf.RaggedTensor)): losses = tf.convert_to_tensor(losses) if not isinstance( sample_weight, (keras_tensor.KerasTensor, tf.RaggedTensor) ): sample_weight = tf.convert_to_tensor(sample_weight) # Convert any non float dtypes to floats, to avoid it loss any precision # for dtype like int or bool. if not losses.dtype.is_floating: input_dtype = losses.dtype losses = tf.cast(losses, "float32") input_casted = True else: input_casted = False sample_weight = tf.cast(sample_weight, losses.dtype) # Update dimensions of `sample_weight` to match with `losses` if # possible. ( losses, _, sample_weight, ) = squeeze_or_expand_dimensions(losses, None, sample_weight) weighted_losses = tf.multiply(losses, sample_weight) # Apply reduction function to the individual weighted losses. loss = reduce_weighted_loss(weighted_losses, reduction) if input_casted: # Convert the result back to the input type. loss = tf.cast(loss, input_dtype) return loss def scale_loss_for_distribution(loss_value): """Scales and returns the given loss value by the number of replicas.""" num_replicas = tf.distribute.get_strategy().num_replicas_in_sync if num_replicas > 1: loss_value *= 1.0 / num_replicas return loss_value def cast_losses_to_common_dtype(losses): """Cast a list of losses to a common dtype. If any loss is floating-point, they will all be casted to the most-precise floating-point loss. Otherwise the losses are not casted. We also skip casting losses if there are any complex losses. Args: losses: A list of losses. Returns: `losses`, but they have been casted to a common dtype. """ highest_float = None for loss in losses: if loss.dtype.is_floating: if highest_float is None or loss.dtype.size > highest_float.size: highest_float = loss.dtype elif {loss.dtype, highest_float} == {"bfloat16", "float16"}: highest_float = "float32" if loss.dtype.is_complex: return ( losses # If we find any complex losses, do not cast any losses ) if highest_float: losses = [tf.cast(loss, highest_float) for loss in losses] return losses def get_mask(y_p): """Returns TF-Keras mask from tensor.""" return getattr(y_p, "_keras_mask", None) def apply_mask(y_p, sw, mask): """Applies any mask on predictions to sample weights.""" if mask is not None: mask = tf.cast(mask, y_p.dtype) if sw is not None: sw = tf.cast(sw, mask.dtype) mask, _, sw = squeeze_or_expand_dimensions(mask, sample_weight=sw) sw *= mask else: sw = mask return sw def apply_valid_mask(losses, sw, mask, reduction): """Redistribute sample weights considering only valid entries.""" if mask is not None: mask = tf.cast(mask, losses.dtype) if reduction in (ReductionV2.AUTO, ReductionV2.SUM_OVER_BATCH_SIZE): # Valid entries have weight `total/valid`, while invalid ones # have 0. When summed over batch, they will be reduced to: # # mean(loss * sample_weight * total / valid) # = sum(loss * sample_weight * total / valid) / total # = sum(loss * sample_weight) / total * total / valid # = sum(loss * sample_weight) / valid total = tf.cast(tf.size(mask), losses.dtype) valid = tf.reduce_sum(mask) mask *= total / valid return apply_mask(losses, sw, mask)
tf-keras/tf_keras/utils/losses_utils.py/0
{ "file_path": "tf-keras/tf_keras/utils/losses_utils.py", "repo_id": "tf-keras", "token_count": 6899 }
210
# Copyright 2018 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. # ============================================================================== """TensorFlow-related utilities.""" import collections import contextlib import copy import platform import random import threading import numpy as np import tensorflow.compat.v2 as tf from absl import logging from tf_keras import backend from tf_keras.engine import keras_tensor from tf_keras.utils import object_identity from tf_keras.utils import tf_contextlib # isort: off from tensorflow.python.framework import ops from tensorflow.python.util.tf_export import keras_export from tensorflow.python import pywrap_tfe @keras_export("keras.utils.set_random_seed", v1=[]) def set_random_seed(seed): """Sets all random seeds for the program (Python, NumPy, and TensorFlow). You can use this utility to make almost any TF-Keras program fully deterministic. Some limitations apply in cases where network communications are involved (e.g. parameter server distribution), which creates additional sources of randomness, or when certain non-deterministic cuDNN ops are involved. Calling this utility is equivalent to the following: ```python import random import numpy as np import tensorflow as tf random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) ``` Arguments: seed: Integer, the random seed to use. """ if not isinstance(seed, int): raise ValueError( "Expected `seed` argument to be an integer. " f"Received: seed={seed} (of type {type(seed)})" ) random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) backend._SEED_GENERATOR.generator = random.Random(seed) def get_random_seed(): """Retrieve a seed value to seed a random generator. Returns: the random seed as an integer. """ if getattr(backend._SEED_GENERATOR, "generator", None): return backend._SEED_GENERATOR.generator.randint(1, 1e9) else: return random.randint(1, 1e9) def is_tensor_or_tensor_list(v): v = tf.nest.flatten(v) if v and isinstance(v[0], tf.Tensor): return True else: return False def get_reachable_from_inputs(inputs, targets=None): """Returns the set of tensors/ops reachable from `inputs`. Stops if all targets have been found (target is optional). Only valid in Symbolic mode, not Eager mode. Args: inputs: List of tensors. targets: List of tensors. Returns: A set of tensors reachable from the inputs (includes the inputs themselves). """ inputs = tf.nest.flatten(inputs, expand_composites=True) reachable = object_identity.ObjectIdentitySet(inputs) if targets: remaining_targets = object_identity.ObjectIdentitySet( tf.nest.flatten(targets) ) queue = collections.deque(inputs) while queue: x = queue.pop() if isinstance(x, tuple(_user_convertible_tensor_types)): # Can't find consumers of user-specific types. continue if isinstance(x, tf.Operation): outputs = x.outputs[:] or [] outputs += x._control_outputs elif isinstance(x, tf.Variable): try: outputs = [x.op] except AttributeError: # Variables can be created in an Eager context. outputs = [] elif tf.is_tensor(x): outputs = x.consumers() else: raise TypeError( "Expected tf.Operation, tf.Variable, or tf.Tensor. " f"Received: {x}" ) for y in outputs: if y not in reachable: reachable.add(y) if targets: remaining_targets.discard(y) queue.appendleft(y) if targets and not remaining_targets: return reachable return reachable # This function needs access to private functions of `nest`. def map_structure_with_atomic(is_atomic_fn, map_fn, nested): """Maps the atomic elements of a nested structure. Args: is_atomic_fn: A function that determines if an element of `nested` is atomic. map_fn: The function to apply to atomic elements of `nested`. nested: A nested structure. Returns: The nested structure, with atomic elements mapped according to `map_fn`. Raises: ValueError: If an element that is neither atomic nor a sequence is encountered. """ if is_atomic_fn(nested): return map_fn(nested) # Recursively convert. if not tf.nest.is_nested(nested): raise ValueError( f"Received non-atomic and non-sequence element: {nested} " f"of type {type(nested)}" ) if tf.__internal__.nest.is_mapping(nested): values = [nested[k] for k in sorted(nested.keys())] elif tf.__internal__.nest.is_attrs(nested): values = _astuple(nested) else: values = nested mapped_values = [ map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values ] return tf.__internal__.nest.sequence_like(nested, mapped_values) def get_shapes(tensors): """Gets shapes from tensors.""" return tf.nest.map_structure( lambda x: x.shape if hasattr(x, "shape") else None, tensors ) def convert_shapes(input_shape, to_tuples=True): """Converts nested shape representations to desired format. Performs: TensorShapes -> tuples if `to_tuples=True`. tuples of int or None -> TensorShapes if `to_tuples=False`. Valid objects to be converted are: - TensorShapes - tuples with elements of type int or None. - ints - None Args: input_shape: A nested structure of objects to be converted to TensorShapes. to_tuples: If `True`, converts all TensorShape to tuples. Otherwise converts all tuples representing shapes to TensorShapes. Returns: Nested structure of shapes in desired format. Raises: ValueError: when the input tensor shape can't be converted to tuples, eg unknown tensor shape. """ def _is_shape_component(value): return value is None or isinstance(value, (int, tf.compat.v1.Dimension)) def _is_atomic_shape(input_shape): # Ex: TensorShape or (None, 10, 32) or 5 or `None` if _is_shape_component(input_shape): return True if isinstance(input_shape, tf.TensorShape): return True if isinstance(input_shape, (tuple, list)) and all( _is_shape_component(ele) for ele in input_shape ): return True return False def _convert_shape(input_shape): input_shape = tf.TensorShape(input_shape) if to_tuples: input_shape = tuple(input_shape.as_list()) return input_shape return map_structure_with_atomic( _is_atomic_shape, _convert_shape, input_shape ) def validate_axis(axis, input_shape): """Validate an axis value and returns its standardized form. Args: axis: Value to validate. Can be an integer or a list/tuple of integers. Integers may be negative. input_shape: Reference input shape that the axis/axes refer to. Returns: Normalized form of `axis`, i.e. a list with all-positive values. """ input_shape = tf.TensorShape(input_shape) rank = input_shape.rank if not rank: raise ValueError( f"Input has undefined rank. Received: input_shape={input_shape}" ) # Convert axis to list and resolve negatives if isinstance(axis, int): axis = [axis] else: axis = list(axis) for idx, x in enumerate(axis): if x < 0: axis[idx] = rank + x # Validate axes for x in axis: if x < 0 or x >= rank: raise ValueError( "Invalid value for `axis` argument. " "Expected 0 <= axis < inputs.rank (with " f"inputs.rank={rank}). Received: axis={tuple(axis)}" ) if len(axis) != len(set(axis)): raise ValueError(f"Duplicate axis: {tuple(axis)}") return axis class ListWrapper: """A wrapper for lists to be treated as elements for `nest`.""" def __init__(self, list_to_wrap): self._list = list_to_wrap def as_list(self): return self._list def convert_inner_node_data(nested, wrap=False): """Either wraps or unwraps innermost node data lists in `ListWrapper` objects. Args: nested: A nested data structure. wrap: If `True`, wrap innermost lists in `ListWrapper` objects. If `False`, unwraps `ListWrapper` objects into lists. Returns: Structure of same type as nested, with lists wrapped/unwrapped. """ def _is_serialized_node_data(nested): # Node data can be of form `[layer_name, node_id, tensor_id]` or # `[layer_name, node_id, tensor_id, kwargs]`. if ( isinstance(nested, list) and (len(nested) in [3, 4]) and isinstance(nested[0], str) ): return True return False def _is_atomic_nested(nested): """Returns `True` if `nested` is a list representing node data.""" if isinstance(nested, ListWrapper): return True if _is_serialized_node_data(nested): return True return not tf.nest.is_nested(nested) def _convert_object_or_list(nested): """Convert b/t `ListWrapper` object and list representations.""" if wrap: if isinstance(nested, ListWrapper): return nested if _is_serialized_node_data(nested): return ListWrapper(nested) return nested else: if isinstance(nested, ListWrapper): return nested.as_list() return nested return map_structure_with_atomic( _is_atomic_nested, _convert_object_or_list, nested ) def shape_type_conversion(fn): """Decorator that handles tuple/TensorShape conversion. Used in `compute_output_shape` and `build`. Args: fn: function to wrap. Returns: Wrapped function. """ def wrapper(instance, input_shape): # Pass shapes as tuples to `fn` # This preserves compatibility with external TF-Keras. if input_shape is not None: input_shape = convert_shapes(input_shape, to_tuples=True) output_shape = fn(instance, input_shape) # Return shapes from `fn` as TensorShapes. if output_shape is not None: output_shape = convert_shapes(output_shape, to_tuples=False) return output_shape return wrapper def are_all_symbolic_tensors(tensors): return all(map(is_symbolic_tensor, tensors)) _user_convertible_tensor_types = set() def is_extension_type(tensor): """Returns whether a tensor is of an ExtensionType. github.com/tensorflow/community/pull/269 Currently it works by checking if `tensor` is a `CompositeTensor` instance, but this will be changed to use an appropriate extensiontype protocol check once ExtensionType is made public. Args: tensor: An object to test Returns: True if the tensor is an extension type object, false if not. """ return isinstance(tensor, tf.__internal__.CompositeTensor) def is_symbolic_tensor(tensor): """Returns whether a tensor is symbolic (from a TF graph) or an eager tensor. A Variable can be seen as either: it is considered symbolic when we are in a graph scope, and eager when we are in an eager scope. Args: tensor: A tensor instance to test. Returns: True for symbolic tensors, False for eager tensors. """ if isinstance(tensor, tf.Tensor): return hasattr(tensor, "graph") elif is_extension_type(tensor): component_tensors = tf.nest.flatten(tensor, expand_composites=True) return any(hasattr(t, "graph") for t in component_tensors) elif isinstance(tensor, tf.Variable): # Variables that are output of a TF-Keras Layer in Functional API mode # should be considered symbolic. # TODO(omalleyt): We need a better way to check this in order to # enable `run_eagerly=True` for Models containing Layers that # return Variables as outputs. return ( getattr(tensor, "_keras_history", False) or not tf.executing_eagerly() ) elif isinstance(tensor, tuple(_user_convertible_tensor_types)): tensor = ops.convert_to_tensor_or_composite(tensor) return is_symbolic_tensor(tensor) else: return False @keras_export("keras.__internal__.utils.register_symbolic_tensor_type", v1=[]) def register_symbolic_tensor_type(cls): """Allows users to specify types regarded as symbolic `Tensor`s. Used in conjunction with `tf.register_tensor_conversion_function`, calling `tf.keras.__internal__.utils.register_symbolic_tensor_type(cls)` allows non-`Tensor` objects to be plumbed through TF-Keras layers. Example: ```python # One-time setup. class Foo: def __init__(self, input_): self._input = input_ def value(self): return tf.constant(42.) tf.register_tensor_conversion_function( Foo, lambda x, *args, **kwargs: x.value()) tf.keras.__internal__.utils.register_symbolic_tensor_type(Foo) # User-land. layer = tf.keras.layers.Lambda(lambda input_: Foo(input_)) ``` Args: cls: A `class` type which shall be regarded as a symbolic `Tensor`. """ global _user_convertible_tensor_types if cls not in _user_convertible_tensor_types: keras_tensor.register_keras_tensor_specialization( cls, keras_tensor.UserRegisteredTypeKerasTensor ) _user_convertible_tensor_types.add(cls) def type_spec_from_value(value): """Grab type_spec without converting array-likes to tensors.""" if is_extension_type(value): return value._type_spec # Get a TensorSpec for array-like data without # converting the data to a Tensor if hasattr(value, "shape") and hasattr(value, "dtype"): return tf.TensorSpec(value.shape, value.dtype) else: return tf.type_spec_from_value(value) def is_ragged(tensor): """Returns true if `tensor` is a ragged tensor or ragged tensor value.""" return isinstance( tensor, (tf.RaggedTensor, tf.compat.v1.ragged.RaggedTensorValue) ) def is_sparse(tensor): """Returns true if `tensor` is a sparse tensor or sparse tensor value.""" return isinstance(tensor, (tf.SparseTensor, tf.compat.v1.SparseTensorValue)) def is_tensor_or_variable(x): return tf.is_tensor(x) or isinstance(x, tf.Variable) def is_tensor_or_extension_type(x): """Returns true if 'x' is a TF-native type or an ExtensionType.""" return tf.is_tensor(x) or is_extension_type(x) def convert_variables_to_tensors(values): """Converts `Variable`s in `values` to `Tensor`s. This is a TF-Keras version of `convert_variables_to_tensors` in TensorFlow variable_utils.py. If an object in `values` is an `ExtensionType` and it overrides its `_convert_variables_to_tensors` method, its `ResourceVariable` components will also be converted to `Tensor`s. Objects other than `ResourceVariable`s in `values` will be returned unchanged. Args: values: A nested structure of `ResourceVariable`s, or any other objects. Returns: A new structure with `ResourceVariable`s in `values` converted to `Tensor`s. """ def _convert_resource_variable_to_tensor(x): if isinstance(x, tf.Variable): return tf.convert_to_tensor(x) elif is_extension_type(x): return x._convert_variables_to_tensors() else: return x return tf.nest.map_structure(_convert_resource_variable_to_tensor, values) def assert_no_legacy_layers(layers): """Prevent tf.layers.Layers from being used with TF-Keras. Certain legacy layers inherit from their keras analogs; however they are not supported with keras and can lead to subtle and hard to diagnose bugs. Args: layers: A list of layers to check Raises: TypeError: If any elements of layers are tf.layers.Layers """ # isinstance check for tf.layers.Layer introduces a circular dependency. legacy_layers = [l for l in layers if getattr(l, "_is_legacy_layer", None)] if legacy_layers: layer_str = "\n".join(" " + str(l) for l in legacy_layers) raise TypeError( f"The following are legacy tf.layers.Layers:\n{layer_str}\n" "To use keras as a " "framework (for instance using the Network, Model, or Sequential " "classes), please use the tf.keras.layers implementation instead. " "(Or, if writing custom layers, subclass from tf.keras.layers " "rather than tf.layers)" ) @tf_contextlib.contextmanager def maybe_init_scope(layer): """Open an `init_scope` if in V2 mode and using the keras graph. Args: layer: The Layer/Model that is currently active. Yields: None """ # Don't open an init_scope in V1 mode, when using legacy tf.layers, or in a # local-variable scope. # The local-variable scope should ensure that created variables are local to # the function being executed, rather than lifted out of the graph by # `init_scope`. This way the variables are freely usable and mutable within # the function, which enables a visitation guarantee for model evaluation, # when the scope is applied to metric variable creation. if ( tf.compat.v1.executing_eagerly_outside_functions() and getattr(layer, "_keras_style", True) and not in_local_vars_context() ): with tf.init_scope(): yield else: yield @tf_contextlib.contextmanager def graph_context_for_symbolic_tensors(*args, **kwargs): """Returns graph context manager if any of the inputs is a symbolic tensor.""" if any(is_symbolic_tensor(v) for v in list(args) + list(kwargs.values())): with backend.get_graph().as_default(): yield else: yield def dataset_is_infinite(dataset): """True if the passed dataset is infinite.""" if tf.compat.v1.executing_eagerly_outside_functions(): return tf.equal( tf.data.experimental.cardinality(dataset), tf.data.experimental.INFINITE_CARDINALITY, ) else: dataset_size = backend.get_session().run( tf.data.experimental.cardinality(dataset) ) return dataset_size == tf.data.experimental.INFINITE_CARDINALITY def get_tensor_spec(t, dynamic_batch=False, name=None): """Returns a `TensorSpec` given a single `Tensor` or `TensorSpec`.""" if isinstance(t, tf.TypeSpec): spec = t elif is_extension_type(t): # TODO(b/148821952): Should these specs have a name attr? spec = t._type_spec elif hasattr(t, "_keras_history") and hasattr( t._keras_history[0], "_type_spec" ): return t._keras_history[0]._type_spec elif isinstance(t, keras_tensor.KerasTensor): spec = t.type_spec elif hasattr(t, "shape") and hasattr(t, "dtype"): spec = tf.TensorSpec(shape=t.shape, dtype=t.dtype, name=name) else: return None # Allow non-Tensors to pass through. if not dynamic_batch: return spec shape = spec.shape if shape.rank is None or shape.rank == 0: return spec shape_list = shape.as_list() shape_list[0] = None # TODO(b/203201161) Remove this deepcopy one type_spec_with_shape has been # updated to not mutate spec. spec = copy.deepcopy(spec) return keras_tensor.type_spec_with_shape(spec, tf.TensorShape(shape_list)) def sync_to_numpy_or_python_type(tensors): """Syncs and converts a structure of `Tensor`s to `NumPy` arrays or Python scalar types. For each tensor, it calls `tensor.numpy()`. If the result is a scalar value, it converts it to a Python type, such as a float or int, by calling `result.item()`. Numpy scalars are converted, as Python types are often more convenient to deal with. This is especially useful for bfloat16 Numpy scalars, which don't support as many operations as other Numpy values. Async strategies (such as `TPUStrategy` and `ParameterServerStrategy`) are forced to sync during this process. Args: tensors: A structure of tensors. Returns: `tensors`, but scalar tensors are converted to Python types and non-scalar tensors are converted to Numpy arrays. """ if isinstance(tensors, tf.distribute.experimental.coordinator.RemoteValue): tensors = tensors.fetch() if isinstance(tensors, list) and isinstance( tensors[0], tf.distribute.experimental.coordinator.RemoteValue ): tensors = tf.nest.map_structure(lambda t: t.fetch(), tensors) def _to_single_numpy_or_python_type(t): # Don't turn ragged or sparse tensors to NumPy. if isinstance(t, tf.Tensor): t = t.numpy() # Strings, ragged and sparse tensors don't have .item(). Return them # as-is. if not isinstance(t, (np.ndarray, np.generic)): return t return t.item() if np.ndim(t) == 0 else t return tf.nest.map_structure(_to_single_numpy_or_python_type, tensors) def _astuple(attrs): """Converts the given attrs to tuple non-recursively.""" cls = type(attrs) fields = getattr(cls, "__attrs_attrs__", None) if fields is None: raise ValueError(f"{cls} is not an attrs-decorated class.") values = [] for field in fields: values.append(getattr(attrs, field.name)) return tuple(values) def can_jit_compile(warn=False): """Returns True if TensorFlow XLA is available for the platform.""" if platform.system() == "Darwin" and "arm" in platform.processor().lower(): if warn: logging.warning( "XLA (`jit_compile`) is not yet supported on Apple M1/M2 ARM " "processors. Falling back to `jit_compile=False`." ) return False if pywrap_tfe.TF_ListPluggablePhysicalDevices(): if warn: logging.warning( "XLA (`jit_compile`) is not supported on your system. " "Falling back to `jit_compile=False`." ) return False return True _metric_local_vars_scope = threading.local() def get_metric_local_vars_scope(): try: return _metric_local_vars_scope.current except AttributeError: return None def in_local_vars_context(): ctx = get_metric_local_vars_scope() return ctx is not None @contextlib.contextmanager def with_metric_local_vars_scope(): previous_scope = getattr(_metric_local_vars_scope, "current", None) _metric_local_vars_scope.current = MetricLocalVarsScope() yield _metric_local_vars_scope.current = previous_scope class MetricLocalVarsScope: """Turn on local variable creation for Metrics. No functionality is needed here, it just exists to modulate Metric's variable creation."""
tf-keras/tf_keras/utils/tf_utils.py/0
{ "file_path": "tf-keras/tf_keras/utils/tf_utils.py", "repo_id": "tf-keras", "token_count": 9702 }
211
# Copyright 2020 The AutoKeras 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 # # 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. import numpy as np import pandas as pd import pytest import tensorflow as tf from autokeras import test_utils from autokeras.adapters import output_adapters def test_clf_head_transform_pd_series_to_dataset(): adapter = output_adapters.ClassificationAdapter(name="a") y = adapter.adapt( pd.read_csv(test_utils.TEST_CSV_PATH).pop("survived"), batch_size=32 ) assert isinstance(y, tf.data.Dataset) def test_clf_head_transform_df_to_dataset(): adapter = output_adapters.ClassificationAdapter(name="a") y = adapter.adapt( pd.DataFrame( test_utils.generate_one_hot_labels(dtype="np", num_classes=10) ), batch_size=32, ) assert isinstance(y, tf.data.Dataset) def test_unsupported_types_error(): adapter = output_adapters.ClassificationAdapter(name="a") with pytest.raises(TypeError) as info: adapter.adapt(1, batch_size=32) assert "Expect the target data of a to be tf" in str(info.value) def test_reg_head_transform_pd_series(): adapter = output_adapters.RegressionAdapter(name="a") y = adapter.adapt( pd.read_csv(test_utils.TEST_CSV_PATH).pop("survived"), batch_size=32 ) assert isinstance(y, tf.data.Dataset) def test_reg_head_transform_1d_np(): adapter = output_adapters.RegressionAdapter(name="a") y = adapter.adapt(np.random.rand(10), batch_size=32) assert isinstance(y, tf.data.Dataset)
autokeras/autokeras/adapters/output_adapters_test.py/0
{ "file_path": "autokeras/autokeras/adapters/output_adapters_test.py", "repo_id": "autokeras", "token_count": 731 }
0
# Copyright 2020 The AutoKeras 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 # # 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. import keras_tuner import tensorflow as tf from tensorflow import keras from tensorflow import nest from autokeras import blocks from autokeras import test_utils def test_merge_build_return_tensor(): block = blocks.Merge() outputs = block.build( keras_tuner.HyperParameters(), [ keras.Input(shape=(32,), dtype=tf.float32), keras.Input(shape=(4, 8), dtype=tf.float32), ], ) assert len(nest.flatten(outputs)) == 1 def test_merge_single_input_return_tensor(): block = blocks.Merge() outputs = block.build( keras_tuner.HyperParameters(), keras.Input(shape=(32,), dtype=tf.float32), ) assert len(nest.flatten(outputs)) == 1 def test_merge_inputs_with_same_shape_return_tensor(): block = blocks.Merge() outputs = block.build( keras_tuner.HyperParameters(), [ keras.Input(shape=(32,), dtype=tf.float32), keras.Input(shape=(32,), dtype=tf.float32), ], ) assert len(nest.flatten(outputs)) == 1 def test_merge_deserialize_to_merge(): serialized_block = blocks.serialize(blocks.Merge()) block = blocks.deserialize(serialized_block) assert isinstance(block, blocks.Merge) def test_merge_get_config_has_all_attributes(): block = blocks.Merge() config = block.get_config() assert test_utils.get_func_args(blocks.Merge.__init__).issubset( config.keys() ) def test_temporal_build_return_tensor(): block = blocks.TemporalReduction() outputs = block.build( keras_tuner.HyperParameters(), keras.Input(shape=(32, 10), dtype=tf.float32), ) assert len(nest.flatten(outputs)) == 1 def test_temporal_global_max_return_tensor(): block = blocks.TemporalReduction(reduction_type="global_max") outputs = block.build( keras_tuner.HyperParameters(), keras.Input(shape=(32, 10), dtype=tf.float32), ) assert len(nest.flatten(outputs)) == 1 def test_temporal_global_avg_return_tensor(): block = blocks.TemporalReduction(reduction_type="global_avg") outputs = block.build( keras_tuner.HyperParameters(), keras.Input(shape=(32, 10), dtype=tf.float32), ) assert len(nest.flatten(outputs)) == 1 def test_reduction_2d_tensor_return_input_node(): block = blocks.TemporalReduction() input_node = keras.Input(shape=(32,), dtype=tf.float32) outputs = block.build( keras_tuner.HyperParameters(), input_node, ) assert len(nest.flatten(outputs)) == 1 assert nest.flatten(outputs)[0] is input_node def test_temporal_deserialize_to_temporal(): serialized_block = blocks.serialize(blocks.TemporalReduction()) block = blocks.deserialize(serialized_block) assert isinstance(block, blocks.TemporalReduction) def test_temporal_get_config_has_all_attributes(): block = blocks.TemporalReduction() config = block.get_config() assert test_utils.get_func_args(blocks.TemporalReduction.__init__).issubset( config.keys() ) def test_spatial_build_return_tensor(): block = blocks.SpatialReduction() outputs = block.build( keras_tuner.HyperParameters(), keras.Input(shape=(32, 32, 3), dtype=tf.float32), ) assert len(nest.flatten(outputs)) == 1 def test_spatial_deserialize_to_spatial(): serialized_block = blocks.serialize(blocks.SpatialReduction()) block = blocks.deserialize(serialized_block) assert isinstance(block, blocks.SpatialReduction) def test_spatial_get_config_has_all_attributes(): block = blocks.SpatialReduction() config = block.get_config() assert test_utils.get_func_args(blocks.SpatialReduction.__init__).issubset( config.keys() )
autokeras/autokeras/blocks/reduction_test.py/0
{ "file_path": "autokeras/autokeras/blocks/reduction_test.py", "repo_id": "autokeras", "token_count": 1687 }
1
# Copyright 2020 The AutoKeras 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 # # 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. import keras_tuner from autokeras import blocks from autokeras import nodes def test_input_get_block_return_general_block(): input_node = nodes.Input() assert isinstance(input_node.get_block(), blocks.GeneralBlock) def test_time_series_input_node_build_no_error(): node = nodes.TimeseriesInput(lookback=2, shape=(32,)) hp = keras_tuner.HyperParameters() input_node = node.build_node(hp) node.build(hp, input_node) def test_time_series_input_node_deserialize_build_no_error(): node = nodes.TimeseriesInput(lookback=2, shape=(32,)) node = nodes.deserialize(nodes.serialize(node)) hp = keras_tuner.HyperParameters() input_node = node.build_node(hp) node.build(hp, input_node)
autokeras/autokeras/nodes_test.py/0
{ "file_path": "autokeras/autokeras/nodes_test.py", "repo_id": "autokeras", "token_count": 422 }
2
# Copyright 2020 The AutoKeras 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 # # 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. import threading from tensorflow import keras STATE = {} class State: # It is a global accessible object to record all the useful information of a # specific build of the Graph. def __init__(self): self.inputs = [] self.outputs = [] # This is a stack of blocks that current running their build() # functions. self.blocks = [] # Passing y class info from preprocessor to postprocessor. self.y_info def register_inputs(self, inputs): raise NotImplementedError def register_outputs(self, inputs): # Remember to check duplication raise NotImplementedError def register_preprocessor(self, inputs, outputs, preprocessor): raise NotImplementedError def build_model(self): self.model = keras.Model(inputs=self.inputs, outputs=self.outputs) return self.model def build_scope(self, block): self.blocks.append(block) try: yield finally: self.blocks.pop() def get_state(): return STATE[threading.get_ident()] def init_state(): state = State() STATE[threading.get_ident()] = state return state
autokeras/autokeras/prototype/graph_state.py/0
{ "file_path": "autokeras/autokeras/prototype/graph_state.py", "repo_id": "autokeras", "token_count": 620 }
3
# Copyright 2020 The AutoKeras 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 # # 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. from typing import Callable from typing import Dict from typing import List from typing import Union import numpy as np import tensorflow as tf from tensorflow.keras.losses import Loss from tensorflow.keras.metrics import Metric DatasetType = Union[np.ndarray, tf.data.Dataset] LossType = Union[str, Callable, Loss] AcceptableMetric = Union[str, Callable, Metric] MetricsType = Union[ List[AcceptableMetric], List[List[AcceptableMetric]], Dict[str, AcceptableMetric], ]
autokeras/autokeras/utils/types.py/0
{ "file_path": "autokeras/autokeras/utils/types.py", "repo_id": "autokeras", "token_count": 317 }
4
FROM ubuntu:18.04 RUN mkdir /app WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ python3.6 \ curl \ ca-certificates \ build-essential \ python3.6-dev \ python3-distutils \ git \ gcc \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN curl -O https://bootstrap.pypa.io/get-pip.py && \ python3.6 get-pip.py && \ rm get-pip.py RUN git clone https://github.com/keras-team/autokeras.git RUN python3.6 -m pip install -U keras RUN cd autokeras && python3.6 -m pip install -U . && cd .. RUN rm -rf autokeras CMD /bin/bash
autokeras/docker/devel.Dockerfile/0
{ "file_path": "autokeras/docker/devel.Dockerfile", "repo_id": "autokeras", "token_count": 312 }
5
from .autogen import DocumentationGenerator from .gathering_members import get_classes from .gathering_members import get_functions from .gathering_members import get_methods
autokeras/docs/keras_autodoc/__init__.py/0
{ "file_path": "autokeras/docs/keras_autodoc/__init__.py", "repo_id": "autokeras", "token_count": 44 }
6
"""shell pip install autokeras """ import os import numpy as np import tensorflow as tf from sklearn.datasets import load_files import autokeras as ak """ ## A Simple Example The first step is to prepare your data. Here we use the [IMDB dataset](https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification) as an example. """ dataset = tf.keras.utils.get_file( fname="aclImdb.tar.gz", origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz", extract=True, ) # set path to dataset IMDB_DATADIR = os.path.join(os.path.dirname(dataset), "aclImdb") classes = ["pos", "neg"] train_data = load_files( os.path.join(IMDB_DATADIR, "train"), shuffle=True, categories=classes ) test_data = load_files( os.path.join(IMDB_DATADIR, "test"), shuffle=False, categories=classes ) x_train = np.array(train_data.data) y_train = np.array(train_data.target) x_test = np.array(test_data.data) y_test = np.array(test_data.target) print(x_train.shape) # (25000,) print(y_train.shape) # (25000, 1) print(x_train[0][:50]) # this film was just brilliant casting """ The second step is to run the [TextClassifier](/text_classifier). As a quick demo, we set epochs to 2. You can also leave the epochs unspecified for an adaptive number of epochs. """ # Initialize the text classifier. clf = ak.TextClassifier( overwrite=True, max_trials=1 ) # It only tries 1 model as a quick demo. # Feed the text classifier with training data. clf.fit(x_train, y_train, epochs=2) # Predict with the best model. predicted_y = clf.predict(x_test) # Evaluate the best model with testing data. print(clf.evaluate(x_test, y_test)) """ ## Validation Data By default, AutoKeras use the last 20% of training data as validation data. As shown in the example below, you can use `validation_split` to specify the percentage. """ clf.fit( x_train, y_train, # Split the training data and use the last 15% as validation data. validation_split=0.15, ) """ You can also use your own validation set instead of splitting it from the training data with `validation_data`. """ split = 5000 x_val = x_train[split:] y_val = y_train[split:] x_train = x_train[:split] y_train = y_train[:split] clf.fit( x_train, y_train, epochs=2, # Use your own validation set. validation_data=(x_val, y_val), ) """ ## Customized Search Space For advanced users, you may customize your search space by using [AutoModel](/auto_model/#automodel-class) instead of [TextClassifier](/text_classifier). You can configure the [TextBlock](/block/#textblock-class) for some high-level configurations, e.g., `vectorizer` for the type of text vectorization method to use. You can use 'sequence', which uses [TextToInteSequence](/block/#texttointsequence-class) to convert the words to integers and use [Embedding](/block/#embedding-class) for embedding the integer sequences, or you can use 'ngram', which uses [TextToNgramVector](/block/#texttongramvector-class) to vectorize the sentences. You can also do not specify these arguments, which would leave the different choices to be tuned automatically. See the following example for detail. """ input_node = ak.TextInput() output_node = ak.TextBlock(block_type="ngram")(input_node) output_node = ak.ClassificationHead()(output_node) clf = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=1 ) clf.fit(x_train, y_train, epochs=2) """ The usage of [AutoModel](/auto_model/#automodel-class) is similar to the [functional API](https://www.tensorflow.org/guide/keras/functional) of Keras. Basically, you are building a graph, whose edges are blocks and the nodes are intermediate outputs of blocks. To add an edge from `input_node` to `output_node` with `output_node = ak.[some_block]([block_args])(input_node)`. You can even also use more fine grained blocks to customize the search space even further. See the following example. """ input_node = ak.TextInput() output_node = ak.TextToIntSequence()(input_node) output_node = ak.Embedding()(output_node) # Use separable Conv layers in Keras. output_node = ak.ConvBlock(separable=True)(output_node) output_node = ak.ClassificationHead()(output_node) clf = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=1 ) clf.fit(x_train, y_train, epochs=2) """ ## Data Format The AutoKeras TextClassifier is quite flexible for the data format. For the text, the input data should be one-dimensional For the classification labels, AutoKeras accepts both plain labels, i.e. strings or integers, and one-hot encoded encoded labels, i.e. vectors of 0s and 1s. We also support using [tf.data.Dataset]( https://www.tensorflow.org/api_docs/python/tf/data/Dataset?version=stable) format for the training data. """ train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,))).batch( 32 ) test_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,))).batch(32) clf = ak.TextClassifier(overwrite=True, max_trials=2) # Feed the tensorflow Dataset to the classifier. clf.fit(train_set, epochs=2) # Predict with the best model. predicted_y = clf.predict(test_set) # Evaluate the best model with testing data. print(clf.evaluate(test_set)) """ ## Reference [TextClassifier](/text_classifier), [AutoModel](/auto_model/#automodel-class), [TextBlock](/block/#textblock-class), [TextToInteSequence](/block/#texttointsequence-class), [Embedding](/block/#embedding-class), [TextToNgramVector](/block/#texttongramvector-class), [ConvBlock](/block/#convblock-class), [TextInput](/node/#textinput-class), [ClassificationHead](/block/#classificationhead-class). """
autokeras/docs/py/text_classification.py/0
{ "file_path": "autokeras/docs/py/text_classification.py", "repo_id": "autokeras", "token_count": 1958 }
7
## Requirements **Python 3**: Follow the TensorFlow install steps to install Python 3. **Pip**: Follow the TensorFlow install steps to install Pip. **Tensorflow >= 2.3.0**: AutoKeras is based on TensorFlow. Please follow [this tutorial](https://www.tensorflow.org/install/pip) to install TensorFlow for python3. **GPU Setup (Optional)**: If you have GPUs on your machine and want to use them to accelerate the training, you can follow [this tutorial](https://www.tensorflow.org/install/gpu) to setup. ## Install AutoKeras AutoKeras only support **Python 3**. If you followed previous steps to use virtualenv to install tensorflow, you can just activate the virtualenv and use the following command to install AutoKeras. ``` pip install git+https://github.com/keras-team/keras-tuner.git pip install autokeras ``` If you did not use virtualenv, and you use `python3` command to execute your python program, please use the following command to install AutoKeras. ``` python3 -m pip install git+https://github.com/keras-team/keras-tuner.git python3 -m pip install autokeras ```
autokeras/docs/templates/install.md/0
{ "file_path": "autokeras/docs/templates/install.md", "repo_id": "autokeras", "token_count": 324 }
8
[metadata] version = attr: autokeras.__version__ [tool:pytest] addopts=-v -p no:warnings --durations=10 --log-cli-level=CRITICAL # Do not run tests in the build folder norecursedirs= build [coverage:report] exclude_lines = pragma: no cover @abstract raise NotImplementedError omit = *test* autokeras/prototype/* [flake8] # imported but unused in __init__.py, that's ok. per-file-ignores = **/__init__.py:F401 ignore = E203, W503 max-line-length = 80
autokeras/setup.cfg/0
{ "file_path": "autokeras/setup.cfg", "repo_id": "autokeras", "token_count": 214 }
9
# keras-nlp Transformer Encoder API | Status | Proposed | :-------------- |:---------------------------------------------------- | | **Author(s)** | Zhenyu Tan ([email protected]), Francois Chollet ([email protected]), Hongkun Yu ([email protected])| | **Sponsor(s)** | Mark Omernick ([email protected])| | **Updated** | 2020-09-21 | ## Objective We aim at providing a set of Keras layers to handle Transformer-Encoder BERT-style models. ## Key Benefits BERT-style Transformer-Encoders are a state-of-art technique that powers many NLP tasks: - Single sentence classification task, e.g., sentiment analysis - Sentence pair classification task, e.g., next sentence prediction - Question answering task, e.g., SQuAD - Single sentence tagging task, e.g., named entity recognition With this proposal, Keras users will be able to handle the tasks above with a simple API. ## Design overview This proposal builds on the assumption that inputs are lookup indices, i.e., `tf.int64` sequences. Tokenization is not part of this proposal but will be our immediate next step. ### Classification task Case where a user want to use a pretrained BERT encoder for sentiment analysis: ```python # Considering a imbd review dataset import tensorflow as tf import tensorflow_datasets as tfds import keras_nlp import tensorflow_text as tftext imdb_reviews = tfds.load('imdb_reviews') train_ds = imdb_reviews['train'].batch(32) test_ds = imdb_reviews['test'].batch(32) # Tokenization with BertTokenizer vocab_path = "gs://<bucket_name>/<file_path>/vocab.txt" tokenizer = tftext.BertTokenizer(vocab_path, token_out_type=tf.int64, lower_case=False) SEQUENCE_LENGTH = 128 def preprocess(input_text): token_ids = tokenizer.tokenize_with_offsets(input_text) segment_ids = tf.concat([tf.zeros_like(cls), tf.ones_like(token_ids), tf.ones_like(sep)], axis=1) output_shape = [None, SEQUENCE_LENGTH] token_ids = token_ids.merge_dims(-2, -1) segment_ids = segment_ids.merge_dims(-2, -1).to_tensor(shape=output_shape) input_mask = tf.ones_like(token_ids).to_tensor(shape=output_shape) token_ids = token_ids.to_tensor(shape=output_shape) return { 'input_ids': token_ids, 'input_mask': input_mask, 'input_type_ids': segment_ids } strategy = tf.distribute.TPUStrategy(...) with strategy.scope(): encoder = keras_nlp.encoders.BertEncoder(vocab_size=30522, max_sequence_length=512, type_vocab_size=2) encoder.load_weights("gs://<bucket_name>/<file_path>") token_ids = tf.keras.layers.Input(shape=(SEQUENCE_LENGTH,), name='input_ids', dtype=tf.int32) input_mask = tf.keras.layers.Input(shape=(SEQUENCE_LENGTH,), name='input_mask', dtype=tf.int32) type_ids = tf.keras.layers.Input(shape=(128,), name='input_type_ids', dtype=tf.int32) x = encoder([token_ids, input_mask, type_ids])['pooled_output'] x = tf.keras.layers.Dropout(rate=0.1)(x) output = tf.keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.Model(inputs=[token_ids, input_mask, type_ids], outputs=output) model.compile('adam', 'binary_crossentropy', ['accuracy']) model.fit(train_ds, epochs=5, validation_data=test_ds) ``` ### Pretraining task We aim to provide pretrained checkpoints for `BertEncoder` with different datasets and different sizes through TF Hub, however the user can choose to pretrain a new BertEncoder based on their own dataset. ```python with strategy.scope(): encoder = keras_nlp.encoders.BertEncoder(vocab_size, max_sequence_length, type_vocab_size) token_ids = tf.keras.layers.Input(shape=(SEQUENCE_LENGTH,), name='word_token_ids', dtype=tf.int32) input_mask = tf.keras.layers.Input(shape=(SEQUENCE_LENGTH,), name='input_mask', dtype=tf.int32) type_ids = tf.keras.layers.Input(shape=(128,), name='input_type_ids', dtype=tf.int32) masked_lm_positions = tf.keras.layers.Input(shape=(None,), name='masked_lm_positions', dtype=tf.int32) x = encoder([token_ids, input_mask, type_ids])['pooled_output'] cls_output, sequence_output = output['pooled_output'], outputs['sequence_output'] masked_lm = keras_nlp.layers.MaskedLM(embedding_table=encoder.get_embedding_table()) lm_output = masked_lm(sequence_output, masked_positions=masked_lm_positions) cls_output = tf.keras.layers.Dense(units=num_classes, activation='softmax')(cls_output) model = tf.keras.Model(inputs=[token_ids, input_mask, type_ids, masked_lm_positions], outputs={'lm_output': masked_lm, 'cls_output': cls_output}) model.compile('adam', {'lm_output': 'sparse_categorical_crossentropy', 'cls_output': 'sparse_categorical_crossentropy'}) model.fit(train_ds, epochs=100) ``` ### Other encoder-based networks `BertEncoder` is the first encoder network we propose in this doc. However other encoder networks can be easily built on top of the `TransformerEncoder` layer. For example, for a transformer encoder sharing mechanism with [ALBERT](https://arxiv.org/pdf/1909.11942.pdf), this can be achieved by: ```python token_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_word_ids') mask = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_mask') type_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_type_ids') word_embeddings = keras_nlp.layers.OnDeviceEmbedding(vocab_size, embedding_width)(token_ids) position_embeddings = keras_nlp.layers.PositionEmbedding(max_sequence_length)(word_embeddings) type_embeddings = keras_nlp.layers.OnDeviceEmbedding( vocab_size=type_vocab_size, embedding_width=embedding_width, use_one_hot=True)(type_ids) embeddings = tf.keras.layers.Add()([word_embeddings, position_embeddings, type_embeddings]) embeddings = tf.keras.layers.LayerNormalization(axis=-1)(embeddings) embeddings = tf.keras.layers.Dropout(rate=dropout_rate)(embeddings) embeddings = tf.keras.layers.experimental.EinsumDense( '...x,xy->...y', output_shape=hidden_size, bias_axes='y')(embeddings) data = emnbeddings attention_mask = layers.SelfAttentionMask()([data, mask]) shared_layer = keras_nlp.layers.TransformerEncoder(num_attention_heads, inner_dim) for _ in range(num_layers): data = shared_layer([data, attention_mask]) first_token_tensor = tf.keras.layers.Lambda(lambda x: tf.squeeze(x[:, 0:1, :], axis=1))(data) cls_output = tf.keras.layers.Dense(units=hidden_size, activation='tanh')(first_token_tensor) outputs = dict(sequence_output=data, pooled_output=cls_output) model = tf.keras.Model(inputs=[word_ids, mask, type_ids], outputs=outputs) ``` ## Detailed Design ### Layers -- TransformerEncoder This layer encapsulates a single layer of Transformer Encoder. ```python class TransformerEncoder(tf.keras.layers.Layer): """TransformerEncoder layer. This layer implements the Transformer Encoder from "Attention Is All You Need". (https://arxiv.org/abs/1706.03762), which combines a `tf.keras.layers.MultiHeadAttention` layer with a two-layer feedforward network. References: [Attention Is All You Need](https://arxiv.org/abs/1706.03762) [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) """ def __init__(self, num_attention_heads, inner_dim, inner_activation, output_range=None, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, use_bias=True, norm_first=False, norm_epsilon=1e-12, output_dropout=0.0, attention_dropout=0.0, inner_dropout=0.0, attention_initializer=None, **kwargs): """Initializes `TransformerEncoder`. Arguments: num_attention_heads: Number of attention heads. inner_dim: The output dimension of the first Dense layer in a two-layer feedforward network. inner_activation: The activation for the first Dense layer in a two-layer feedforward network. output_range: the sequence output range, [0, output_range) for slicing the target sequence. `None` means the target sequence is not sliced. kernel_initializer: Initializer for dense layer kernels. bias_initializer: Initializer for dense layer biases. kernel_regularizer: Regularizer for dense layer kernels. bias_regularizer: Regularizer for dense layer biases. activity_regularizer: Regularizer for dense layer activity. kernel_constraint: Constraint for dense layer kernels. bias_constraint: Constraint for dense layer kernels. use_bias: Whether to enable use_bias in attention layer. If set False, use_bias in attention layer is disabled. norm_first: Whether to normalize inputs to attention and intermediate dense layers. If set False, output of attention and intermediate dense layers is normalized. norm_epsilon: Epsilon value to initialize normalization layers. output_dropout: Dropout probability for the post-attention and output dropout. attention_dropout: Dropout probability for within the attention layer. inner_dropout: Dropout probability for the first Dense layer in a two-layer feedforward network. attention_initializer: Initializer for kernels of attention layers. If set `None`, attention layers use kernel_initializer as initializer for kernel. **kwargs: keyword arguments/ """ ``` ### Layers -- SelfAttentionMask ```python class SelfAttentionMask(tf.keras.layers.Layer): """Create 3D attention mask from a 2D tensor mask.""" def call(self, inputs, to_mask): """ Args: inputs[0]: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. inputs[1]: to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, from_seq_length, to_seq_length]. """ ``` ### Layers -- OnDeviceEmbedding This is the experimental layer that would support either one-hot tf.matmul approach or tf.gather approach. ```python class OnDeviceEmbedding(tf.keras.layers.Layer): """Performs an embedding lookup suitable for accelerator devices. This layer uses either tf.gather or tf.one_hot to translate integer indices to float embeddings. Arguments: vocab_size: Number of elements in the vocabulary. embedding_width: Output size of the embedding layer. initializer: The initializer to use for the embedding weights. Defaults to "glorot_uniform". use_one_hot: Whether to use tf.one_hot over tf.gather for the embedding lookup. Defaults to False (that is, using tf.gather). Setting this option to True may improve performance, especially on small vocabulary sizes, but will generally require more memory. """ def __init__(self, vocab_size, embedding_width, initializer="glorot_uniform", use_one_hot=False, **kwargs): ``` ### Layers -- PositionEmbedding ```python class PositionEmbedding(tf.keras.layers.Layer): """Creates a positional embedding. Arguments: max_length: The maximum size of the dynamic sequence. initializer: The initializer to use for the embedding weights. Defaults to "glorot_uniform". Reference: This layer creates a positional embedding as described in [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805). """ ``` ### Layers -- MaskedLM ```python class MaskedLM(tf.keras.layers.Layer): """Masked language model network head for BERT modeling. This layer implements a masked language model based on the provided transformer based encoder. It assumes that the encoder network being passed has a "get_embedding_table()" method. Arguments: embedding_table: The embedding table from encoder network. activation: The activation, if any, for the dense layer. initializer: The initializer for the dense layer. Defaults to a Glorot uniform initializer. output: The output style for this layer. Can be either 'logits' or 'predictions'. """ def __init__(self, embedding_table, activation=None, initializer='glorot_uniform', output='logits', name=None, **kwargs): ``` ### Encoders -- BertEncoder ```python class BertEncoder(tf.keras.Model): """Bi-directional Transformer-based encoder network. This network implements a bi-directional Transformer-based encoder as described in "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding" (https://arxiv.org/abs/1810.04805). It includes the embedding lookups and transformer layers, but not the masked language model or classification task networks. The default values for this object are taken from the BERT-Base implementation in "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding". *Note* that the network is constructed by [Keras Functional API](https://keras.io/guides/functional_api/). Arguments: vocab_size: The size of the token vocabulary. hidden_size: The size of the transformer hidden layers. num_layers: The number of transformer layers. num_attention_heads: The number of attention heads for each transformer. The hidden size must be divisible by the number of attention heads. max_sequence_length: The maximum sequence length that this encoder can consume. If None, max_sequence_length uses the value from sequence length. This determines the variable shape for positional embeddings. type_vocab_size: The number of types that the 'type_ids' input can take. inner_dim: The output dimension of the first Dense layer in a two-layer feedforward network for each transformer. inner_activation: The activation for the first Dense layer in a two-layer feedforward network for each transformer. output_dropout: Dropout probability for the post-attention and output dropout. attention_dropout: The dropout rate to use for the attention layers within the transformer layers. initializer: The initialzer to use for all weights in this encoder. output_range: The sequence output range, [0, output_range), by slicing the target sequence of the last transformer layer. `None` means the entire target sequence will attend to the source sequence, which yeilds the full output. embedding_width: The width of the word embeddings. If the embedding width is not equal to hidden size, embedding parameters will be factorized into two matrices in the shape of ['vocab_size', 'embedding_width'] and ['embedding_width', 'hidden_size'] ('embedding_width' is usually much smaller than 'hidden_size'). """ def __init__( self, vocab_size, hidden_size=768, num_layers=12, num_attention_heads=12, max_sequence_length=512, type_vocab_size=16, inner_dim=3072, inner_activation='gelu', output_dropout=0.1, attention_dropout=0.1, initializer='truncated_normal', output_range=None, embedding_width=None, **kwargs): ``` ## Questions and Discussion Topics Gathering feedbacks on arguments & naming conventions.
governance/rfcs/20200920-keras-nlp-bert.md/0
{ "file_path": "governance/rfcs/20200920-keras-nlp-bert.md", "repo_id": "governance", "token_count": 5602 }
10
"""NASNet-A models for Keras. NASNet refers to Neural Architecture Search Network, a family of models that were designed automatically by learning the model architectures directly on the dataset of interest. Here we consider NASNet-A, the highest performance model that was found for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset, obtaining state of the art performance on CIFAR-10 and ImageNet 2012. Only the NASNet-A models, and their respective weights, which are suited for ImageNet 2012 are provided. The below table describes the performance on ImageNet 2012: -------------------------------------------------------------------------------- Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M) -------------------------------------------------------------------------------- | NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 | | NASNet-A (6 @ 4032) | 82.7 % | 96.2 % | 23.8 B | 88.9 | -------------------------------------------------------------------------------- Weights obtained from the official TensorFlow repository found at https://github.com/tensorflow/models/tree/master/research/slim/nets/nasnet # References - [Learning Transferable Architectures for Scalable Image Recognition] (https://arxiv.org/abs/1707.07012) (CVPR 2018) This model is based on the following implementations: - [TF Slim Implementation] (https://github.com/tensorflow/models/blob/master/research/slim/nets/nasnet/nasnet.py) - [TensorNets implementation] (https://github.com/taehoonlee/tensornets/blob/master/tensornets/nasnets.py) """ from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import warnings from . import correct_pad from . import get_submodules_from_kwargs from . import imagenet_utils from .imagenet_utils import decode_predictions from .imagenet_utils import _obtain_input_shape BASE_WEIGHTS_PATH = ('https://github.com/titu1994/Keras-NASNet/' 'releases/download/v1.2/') NASNET_MOBILE_WEIGHT_PATH = BASE_WEIGHTS_PATH + 'NASNet-mobile.h5' NASNET_MOBILE_WEIGHT_PATH_NO_TOP = BASE_WEIGHTS_PATH + 'NASNet-mobile-no-top.h5' NASNET_LARGE_WEIGHT_PATH = BASE_WEIGHTS_PATH + 'NASNet-large.h5' NASNET_LARGE_WEIGHT_PATH_NO_TOP = BASE_WEIGHTS_PATH + 'NASNet-large-no-top.h5' backend = None layers = None models = None keras_utils = None def NASNet(input_shape=None, penultimate_filters=4032, num_blocks=6, stem_block_filters=96, skip_reduction=True, filter_multiplier=2, include_top=True, weights=None, input_tensor=None, pooling=None, classes=1000, default_size=None, **kwargs): '''Instantiates a NASNet model. Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at `~/.keras/keras.json`. # Arguments input_shape: Optional shape tuple, the input shape is by default `(331, 331, 3)` for NASNetLarge and `(224, 224, 3)` for NASNetMobile. It should have exactly 3 input channels, and width and height should be no smaller than 32. E.g. `(224, 224, 3)` would be one valid value. penultimate_filters: Number of filters in the penultimate layer. NASNet models use the notation `NASNet (N @ P)`, where: - N is the number of blocks - P is the number of penultimate filters num_blocks: Number of repeated blocks of the NASNet model. NASNet models use the notation `NASNet (N @ P)`, where: - N is the number of blocks - P is the number of penultimate filters stem_block_filters: Number of filters in the initial stem block skip_reduction: Whether to skip the reduction step at the tail end of the network. filter_multiplier: Controls the width of the network. - If `filter_multiplier` < 1.0, proportionally decreases the number of filters in each layer. - If `filter_multiplier` > 1.0, proportionally increases the number of filters in each layer. - If `filter_multiplier` = 1, default number of filters from the paper are used at each layer. include_top: Whether to include the fully-connected layer at the top of the network. weights: `None` (random initialization) or `imagenet` (ImageNet weights) input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of the last convolutional block. - `avg` means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor. - `max` means that global max pooling will be applied. classes: Optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. default_size: Specifies the default image size of the model # Returns A Keras model instance. # Raises ValueError: In case of invalid argument for `weights`, invalid input shape or invalid `penultimate_filters` value. ''' global backend, layers, models, keras_utils backend, layers, models, keras_utils = get_submodules_from_kwargs(kwargs) if not (weights in {'imagenet', None} or os.path.exists(weights)): raise ValueError('The `weights` argument should be either ' '`None` (random initialization), `imagenet` ' '(pre-training on ImageNet), ' 'or the path to the weights file to be loaded.') if weights == 'imagenet' and include_top and classes != 1000: raise ValueError('If using `weights` as `"imagenet"` with `include_top` ' 'as true, `classes` should be 1000') if (isinstance(input_shape, tuple) and None in input_shape and weights == 'imagenet'): raise ValueError('When specifying the input shape of a NASNet' ' and loading `ImageNet` weights, ' 'the input_shape argument must be static ' '(no None entries). Got: `input_shape=' + str(input_shape) + '`.') if default_size is None: default_size = 331 # Determine proper input shape and default size. input_shape = _obtain_input_shape(input_shape, default_size=default_size, min_size=32, data_format=backend.image_data_format(), require_flatten=True, weights=weights) if backend.image_data_format() != 'channels_last': warnings.warn('The NASNet family of models is only available ' 'for the input data format "channels_last" ' '(width, height, channels). ' 'However your settings specify the default ' 'data format "channels_first" (channels, width, height).' ' You should set `image_data_format="channels_last"` ' 'in your Keras config located at ~/.keras/keras.json. ' 'The model being returned right now will expect inputs ' 'to follow the "channels_last" data format.') backend.set_image_data_format('channels_last') old_data_format = 'channels_first' else: old_data_format = None if input_tensor is None: img_input = layers.Input(shape=input_shape) else: if not backend.is_keras_tensor(input_tensor): img_input = layers.Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor if penultimate_filters % (24 * (filter_multiplier ** 2)) != 0: raise ValueError( 'For NASNet-A models, the `penultimate_filters` must be a multiple ' 'of 24 * (`filter_multiplier` ** 2). Current value: %d' % penultimate_filters) channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1 filters = penultimate_filters // 24 x = layers.Conv2D(stem_block_filters, (3, 3), strides=(2, 2), padding='valid', use_bias=False, name='stem_conv1', kernel_initializer='he_normal')(img_input) x = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='stem_bn1')(x) p = None x, p = _reduction_a_cell(x, p, filters // (filter_multiplier ** 2), block_id='stem_1') x, p = _reduction_a_cell(x, p, filters // filter_multiplier, block_id='stem_2') for i in range(num_blocks): x, p = _normal_a_cell(x, p, filters, block_id='%d' % (i)) x, p0 = _reduction_a_cell(x, p, filters * filter_multiplier, block_id='reduce_%d' % (num_blocks)) p = p0 if not skip_reduction else p for i in range(num_blocks): x, p = _normal_a_cell(x, p, filters * filter_multiplier, block_id='%d' % (num_blocks + i + 1)) x, p0 = _reduction_a_cell(x, p, filters * filter_multiplier ** 2, block_id='reduce_%d' % (2 * num_blocks)) p = p0 if not skip_reduction else p for i in range(num_blocks): x, p = _normal_a_cell(x, p, filters * filter_multiplier ** 2, block_id='%d' % (2 * num_blocks + i + 1)) x = layers.Activation('relu')(x) if include_top: x = layers.GlobalAveragePooling2D()(x) x = layers.Dense(classes, activation='softmax', name='predictions')(x) else: if pooling == 'avg': x = layers.GlobalAveragePooling2D()(x) elif pooling == 'max': x = layers.GlobalMaxPooling2D()(x) # Ensure that the model takes into account # any potential predecessors of `input_tensor`. if input_tensor is not None: inputs = keras_utils.get_source_inputs(input_tensor) else: inputs = img_input model = models.Model(inputs, x, name='NASNet') # Load weights. if weights == 'imagenet': if default_size == 224: # mobile version if include_top: weights_path = keras_utils.get_file( 'nasnet_mobile.h5', NASNET_MOBILE_WEIGHT_PATH, cache_subdir='models', file_hash='020fb642bf7360b370c678b08e0adf61') else: weights_path = keras_utils.get_file( 'nasnet_mobile_no_top.h5', NASNET_MOBILE_WEIGHT_PATH_NO_TOP, cache_subdir='models', file_hash='1ed92395b5b598bdda52abe5c0dbfd63') model.load_weights(weights_path) elif default_size == 331: # large version if include_top: weights_path = keras_utils.get_file( 'nasnet_large.h5', NASNET_LARGE_WEIGHT_PATH, cache_subdir='models', file_hash='11577c9a518f0070763c2b964a382f17') else: weights_path = keras_utils.get_file( 'nasnet_large_no_top.h5', NASNET_LARGE_WEIGHT_PATH_NO_TOP, cache_subdir='models', file_hash='d81d89dc07e6e56530c4e77faddd61b5') model.load_weights(weights_path) else: raise ValueError( 'ImageNet weights can only be loaded with NASNetLarge' ' or NASNetMobile') elif weights is not None: model.load_weights(weights) if old_data_format: backend.set_image_data_format(old_data_format) return model def NASNetLarge(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000, **kwargs): '''Instantiates a NASNet model in ImageNet mode. Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at `~/.keras/keras.json`. # Arguments input_shape: Optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(331, 331, 3)` for NASNetLarge. It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. `(224, 224, 3)` would be one valid value. include_top: Whether to include the fully-connected layer at the top of the network. weights: `None` (random initialization) or `imagenet` (ImageNet weights) input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of the last convolutional layer. - `avg` means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor. - `max` means that global max pooling will be applied. classes: Optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. # Returns A Keras model instance. # Raises ValueError: in case of invalid argument for `weights`, or invalid input shape. RuntimeError: If attempting to run this model with a backend that does not support separable convolutions. ''' return NASNet(input_shape, penultimate_filters=4032, num_blocks=6, stem_block_filters=96, skip_reduction=True, filter_multiplier=2, include_top=include_top, weights=weights, input_tensor=input_tensor, pooling=pooling, classes=classes, default_size=331, **kwargs) def NASNetMobile(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000, **kwargs): '''Instantiates a Mobile NASNet model in ImageNet mode. Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at `~/.keras/keras.json`. # Arguments input_shape: Optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(224, 224, 3)` for NASNetMobile It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. `(224, 224, 3)` would be one valid value. include_top: Whether to include the fully-connected layer at the top of the network. weights: `None` (random initialization) or `imagenet` (ImageNet weights) input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of the last convolutional layer. - `avg` means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor. - `max` means that global max pooling will be applied. classes: Optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. # Returns A Keras model instance. # Raises ValueError: In case of invalid argument for `weights`, or invalid input shape. RuntimeError: If attempting to run this model with a backend that does not support separable convolutions. ''' return NASNet(input_shape, penultimate_filters=1056, num_blocks=4, stem_block_filters=32, skip_reduction=False, filter_multiplier=2, include_top=include_top, weights=weights, input_tensor=input_tensor, pooling=pooling, classes=classes, default_size=224, **kwargs) def _separable_conv_block(ip, filters, kernel_size=(3, 3), strides=(1, 1), block_id=None): '''Adds 2 blocks of [relu-separable conv-batchnorm]. # Arguments ip: Input tensor filters: Number of output filters per layer kernel_size: Kernel size of separable convolutions strides: Strided convolution for downsampling block_id: String block_id # Returns A Keras tensor ''' channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1 with backend.name_scope('separable_conv_block_%s' % block_id): x = layers.Activation('relu')(ip) if strides == (2, 2): x = layers.ZeroPadding2D( padding=correct_pad(backend, x, kernel_size), name='separable_conv_1_pad_%s' % block_id)(x) conv_pad = 'valid' else: conv_pad = 'same' x = layers.SeparableConv2D(filters, kernel_size, strides=strides, name='separable_conv_1_%s' % block_id, padding=conv_pad, use_bias=False, kernel_initializer='he_normal')(x) x = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='separable_conv_1_bn_%s' % (block_id))(x) x = layers.Activation('relu')(x) x = layers.SeparableConv2D(filters, kernel_size, name='separable_conv_2_%s' % block_id, padding='same', use_bias=False, kernel_initializer='he_normal')(x) x = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='separable_conv_2_bn_%s' % (block_id))(x) return x def _adjust_block(p, ip, filters, block_id=None): '''Adjusts the input `previous path` to match the shape of the `input`. Used in situations where the output number of filters needs to be changed. # Arguments p: Input tensor which needs to be modified ip: Input tensor whose shape needs to be matched filters: Number of output filters to be matched block_id: String block_id # Returns Adjusted Keras tensor ''' channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1 img_dim = 2 if backend.image_data_format() == 'channels_first' else -2 ip_shape = backend.int_shape(ip) if p is not None: p_shape = backend.int_shape(p) with backend.name_scope('adjust_block'): if p is None: p = ip elif p_shape[img_dim] != ip_shape[img_dim]: with backend.name_scope('adjust_reduction_block_%s' % block_id): p = layers.Activation('relu', name='adjust_relu_1_%s' % block_id)(p) p1 = layers.AveragePooling2D( (1, 1), strides=(2, 2), padding='valid', name='adjust_avg_pool_1_%s' % block_id)(p) p1 = layers.Conv2D( filters // 2, (1, 1), padding='same', use_bias=False, name='adjust_conv_1_%s' % block_id, kernel_initializer='he_normal')(p1) p2 = layers.ZeroPadding2D(padding=((0, 1), (0, 1)))(p) p2 = layers.Cropping2D(cropping=((1, 0), (1, 0)))(p2) p2 = layers.AveragePooling2D( (1, 1), strides=(2, 2), padding='valid', name='adjust_avg_pool_2_%s' % block_id)(p2) p2 = layers.Conv2D( filters // 2, (1, 1), padding='same', use_bias=False, name='adjust_conv_2_%s' % block_id, kernel_initializer='he_normal')(p2) p = layers.concatenate([p1, p2], axis=channel_dim) p = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='adjust_bn_%s' % block_id)(p) elif p_shape[channel_dim] != filters: with backend.name_scope('adjust_projection_block_%s' % block_id): p = layers.Activation('relu')(p) p = layers.Conv2D( filters, (1, 1), strides=(1, 1), padding='same', name='adjust_conv_projection_%s' % block_id, use_bias=False, kernel_initializer='he_normal')(p) p = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='adjust_bn_%s' % block_id)(p) return p def _normal_a_cell(ip, p, filters, block_id=None): '''Adds a Normal cell for NASNet-A (Fig. 4 in the paper). # Arguments ip: Input tensor `x` p: Input tensor `p` filters: Number of output filters block_id: String block_id # Returns A Keras tensor ''' channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1 with backend.name_scope('normal_A_block_%s' % block_id): p = _adjust_block(p, ip, filters, block_id) h = layers.Activation('relu')(ip) h = layers.Conv2D( filters, (1, 1), strides=(1, 1), padding='same', name='normal_conv_1_%s' % block_id, use_bias=False, kernel_initializer='he_normal')(h) h = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='normal_bn_1_%s' % block_id)(h) with backend.name_scope('block_1'): x1_1 = _separable_conv_block( h, filters, kernel_size=(5, 5), block_id='normal_left1_%s' % block_id) x1_2 = _separable_conv_block( p, filters, block_id='normal_right1_%s' % block_id) x1 = layers.add([x1_1, x1_2], name='normal_add_1_%s' % block_id) with backend.name_scope('block_2'): x2_1 = _separable_conv_block( p, filters, (5, 5), block_id='normal_left2_%s' % block_id) x2_2 = _separable_conv_block( p, filters, (3, 3), block_id='normal_right2_%s' % block_id) x2 = layers.add([x2_1, x2_2], name='normal_add_2_%s' % block_id) with backend.name_scope('block_3'): x3 = layers.AveragePooling2D( (3, 3), strides=(1, 1), padding='same', name='normal_left3_%s' % (block_id))(h) x3 = layers.add([x3, p], name='normal_add_3_%s' % block_id) with backend.name_scope('block_4'): x4_1 = layers.AveragePooling2D( (3, 3), strides=(1, 1), padding='same', name='normal_left4_%s' % (block_id))(p) x4_2 = layers.AveragePooling2D( (3, 3), strides=(1, 1), padding='same', name='normal_right4_%s' % (block_id))(p) x4 = layers.add([x4_1, x4_2], name='normal_add_4_%s' % block_id) with backend.name_scope('block_5'): x5 = _separable_conv_block(h, filters, block_id='normal_left5_%s' % block_id) x5 = layers.add([x5, h], name='normal_add_5_%s' % block_id) x = layers.concatenate([p, x1, x2, x3, x4, x5], axis=channel_dim, name='normal_concat_%s' % block_id) return x, ip def _reduction_a_cell(ip, p, filters, block_id=None): '''Adds a Reduction cell for NASNet-A (Fig. 4 in the paper). # Arguments ip: Input tensor `x` p: Input tensor `p` filters: Number of output filters block_id: String block_id # Returns A Keras tensor ''' channel_dim = 1 if backend.image_data_format() == 'channels_first' else -1 with backend.name_scope('reduction_A_block_%s' % block_id): p = _adjust_block(p, ip, filters, block_id) h = layers.Activation('relu')(ip) h = layers.Conv2D( filters, (1, 1), strides=(1, 1), padding='same', name='reduction_conv_1_%s' % block_id, use_bias=False, kernel_initializer='he_normal')(h) h = layers.BatchNormalization( axis=channel_dim, momentum=0.9997, epsilon=1e-3, name='reduction_bn_1_%s' % block_id)(h) h3 = layers.ZeroPadding2D( padding=correct_pad(backend, h, 3), name='reduction_pad_1_%s' % block_id)(h) with backend.name_scope('block_1'): x1_1 = _separable_conv_block( h, filters, (5, 5), strides=(2, 2), block_id='reduction_left1_%s' % block_id) x1_2 = _separable_conv_block( p, filters, (7, 7), strides=(2, 2), block_id='reduction_right1_%s' % block_id) x1 = layers.add([x1_1, x1_2], name='reduction_add_1_%s' % block_id) with backend.name_scope('block_2'): x2_1 = layers.MaxPooling2D( (3, 3), strides=(2, 2), padding='valid', name='reduction_left2_%s' % block_id)(h3) x2_2 = _separable_conv_block( p, filters, (7, 7), strides=(2, 2), block_id='reduction_right2_%s' % block_id) x2 = layers.add([x2_1, x2_2], name='reduction_add_2_%s' % block_id) with backend.name_scope('block_3'): x3_1 = layers.AveragePooling2D( (3, 3), strides=(2, 2), padding='valid', name='reduction_left3_%s' % block_id)(h3) x3_2 = _separable_conv_block( p, filters, (5, 5), strides=(2, 2), block_id='reduction_right3_%s' % block_id) x3 = layers.add([x3_1, x3_2], name='reduction_add3_%s' % block_id) with backend.name_scope('block_4'): x4 = layers.AveragePooling2D( (3, 3), strides=(1, 1), padding='same', name='reduction_left4_%s' % block_id)(x1) x4 = layers.add([x2, x4]) with backend.name_scope('block_5'): x5_1 = _separable_conv_block( x1, filters, (3, 3), block_id='reduction_left4_%s' % block_id) x5_2 = layers.MaxPooling2D( (3, 3), strides=(2, 2), padding='valid', name='reduction_right5_%s' % block_id)(h3) x5 = layers.add([x5_1, x5_2], name='reduction_add4_%s' % block_id) x = layers.concatenate( [x2, x3, x4, x5], axis=channel_dim, name='reduction_concat_%s' % block_id) return x, ip def preprocess_input(x, **kwargs): """Preprocesses a numpy array encoding a batch of images. # Arguments x: a 4D numpy array consists of RGB values within [0, 255]. # Returns Preprocessed array. """ return imagenet_utils.preprocess_input(x, mode='tf', **kwargs)
keras-applications/keras_applications/nasnet.py/0
{ "file_path": "keras-applications/keras_applications/nasnet.py", "repo_id": "keras-applications", "token_count": 15038 }
11
<!-- Please make sure you've read and understood our contributing guidelines; https://github.com/keras-team/keras-contrib/blob/master/CONTRIBUTING.md --> **- What I did** **- How I did it** **- How you can verify it** <!-- You need a good justification for not including tests if your pull request is a bug fix or adds a new feature to Keras-contrib. --> --- This pull request fixes #issue_number_here
keras-contrib/PULL_REQUEST_TEMPLATE.md/0
{ "file_path": "keras-contrib/PULL_REQUEST_TEMPLATE.md", "repo_id": "keras-contrib", "token_count": 129 }
12
<div role="search"> <form id ="rtd-search-form" class="wy-form" action="{{ base_url }}/search.html" method="get"> <input type="text" name="q" placeholder="Search docs" title="Type search term here" /> </form> </div>
keras-contrib/contrib_docs/theme/searchbox.html/0
{ "file_path": "keras-contrib/contrib_docs/theme/searchbox.html", "repo_id": "keras-contrib", "token_count": 79 }
13
from keras import backend as K def squash(x, axis=-1): """ Squash activation function (generally used in Capsule layers). """ s_squared_norm = K.sum(K.square(x), axis, keepdims=True) + K.epsilon() scale = K.sqrt(s_squared_norm) / (0.5 + s_squared_norm) return scale * x
keras-contrib/keras_contrib/activations/squash.py/0
{ "file_path": "keras-contrib/keras_contrib/activations/squash.py", "repo_id": "keras-contrib", "token_count": 121 }
14
from __future__ import absolute_import from .clip import Clip # Aliases. clip = Clip
keras-contrib/keras_contrib/constraints/__init__.py/0
{ "file_path": "keras-contrib/keras_contrib/constraints/__init__.py", "repo_id": "keras-contrib", "token_count": 27 }
15
# -*- coding: utf-8 -*- from __future__ import absolute_import from functools import partial from keras import backend as K from keras_contrib import backend as KC from keras import activations from keras import initializers from keras import regularizers from keras import constraints from keras.layers import Layer from keras.layers import InputSpec from keras_contrib.utils.conv_utils import conv_output_length from keras_contrib.utils.conv_utils import normalize_data_format from keras_contrib.utils.test_utils import to_tuple import numpy as np class CosineConvolution2D(Layer): """Cosine Normalized Convolution operator for filtering windows of two-dimensional inputs. # Examples ```python # apply a 3x3 convolution with 64 output filters on a 256x256 image: model = Sequential() model.add(CosineConvolution2D(64, 3, 3, padding='same', input_shape=(3, 256, 256))) # now model.output_shape == (None, 64, 256, 256) # add a 3x3 convolution on top, with 32 output filters: model.add(CosineConvolution2D(32, 3, 3, padding='same')) # now model.output_shape == (None, 32, 256, 256) ``` # Arguments filters: Number of convolution filters to use. kernel_size: kernel_size: An integer or tuple/list of 2 integers, specifying the dimensions of the convolution window. init: name of initialization function for the weights of the layer (see [initializers](https://keras.io/initializers)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. activation: name of activation function to use (see [activations](https://keras.io/activations)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). weights: list of numpy arrays to set as initial weights. padding: 'valid', 'same' or 'full' ('full' requires the Theano backend). strides: tuple of length 2. Factor by which to strides output. Also called strides elsewhere. kernel_regularizer: instance of [WeightRegularizer]( https://keras.io/regularizers) (eg. L1 or L2 regularization), applied to the main weights matrix. bias_regularizer: instance of [WeightRegularizer]( https://keras.io/regularizers), applied to the use_bias. activity_regularizer: instance of [ActivityRegularizer]( https://keras.io/regularizers), applied to the network output. kernel_constraint: instance of the [constraints]( https://keras.io/constraints) module (eg. maxnorm, nonneg), applied to the main weights matrix. bias_constraint: instance of the [constraints]( https://keras.io/constraints) module, applied to the use_bias. data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 3. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `'channels_last'`. use_bias: whether to include a use_bias (i.e. make the layer affine rather than linear). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. # Output shape 4D tensor with shape: `(samples, filters, nekernel_rows, nekernel_cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, nekernel_rows, nekernel_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. # References - [Cosine Normalization: Using Cosine Similarity Instead of Dot Product in Neural Networks](https://arxiv.org/pdf/1702.05870.pdf) """ def __init__(self, filters, kernel_size, kernel_initializer='glorot_uniform', activation=None, weights=None, padding='valid', strides=(1, 1), data_format=None, kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, use_bias=True, **kwargs): if data_format is None: data_format = K.image_data_format() if padding not in {'valid', 'same', 'full'}: raise ValueError('Invalid border mode for CosineConvolution2D:', padding) self.filters = filters self.kernel_size = kernel_size self.nb_row, self.nb_col = self.kernel_size self.kernel_initializer = initializers.get(kernel_initializer) self.activation = activations.get(activation) self.padding = padding self.strides = tuple(strides) self.data_format = normalize_data_format(data_format) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.use_bias = use_bias self.input_spec = [InputSpec(ndim=4)] self.initial_weights = weights super(CosineConvolution2D, self).__init__(**kwargs) def build(self, input_shape): input_shape = to_tuple(input_shape) if self.data_format == 'channels_first': stack_size = input_shape[1] self.kernel_shape = (self.filters, stack_size, self.nb_row, self.nb_col) self.kernel_norm_shape = (1, stack_size, self.nb_row, self.nb_col) elif self.data_format == 'channels_last': stack_size = input_shape[3] self.kernel_shape = (self.nb_row, self.nb_col, stack_size, self.filters) self.kernel_norm_shape = (self.nb_row, self.nb_col, stack_size, 1) else: raise ValueError('Invalid data_format:', self.data_format) self.W = self.add_weight(shape=self.kernel_shape, initializer=partial(self.kernel_initializer), name='{}_W'.format(self.name), regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) kernel_norm_name = '{}_kernel_norm'.format(self.name) self.kernel_norm = K.variable(np.ones(self.kernel_norm_shape), name=kernel_norm_name) if self.use_bias: self.b = self.add_weight(shape=(self.filters,), initializer='zero', name='{}_b'.format(self.name), regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.b = None if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights self.built = True def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.data_format == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise ValueError('Invalid data_format:', self.data_format) rows = conv_output_length(rows, self.nb_row, self.padding, self.strides[0]) cols = conv_output_length(cols, self.nb_col, self.padding, self.strides[1]) if self.data_format == 'channels_first': return input_shape[0], self.filters, rows, cols elif self.data_format == 'channels_last': return input_shape[0], rows, cols, self.filters def call(self, x, mask=None): b, xb = 0., 0. if self.data_format == 'channels_first': kernel_sum_axes = [1, 2, 3] if self.use_bias: b = K.reshape(self.b, (self.filters, 1, 1, 1)) xb = 1. elif self.data_format == 'channels_last': kernel_sum_axes = [0, 1, 2] if self.use_bias: b = K.reshape(self.b, (1, 1, 1, self.filters)) xb = 1. tmp = K.sum(K.square(self.W), axis=kernel_sum_axes, keepdims=True) Wnorm = K.sqrt(tmp + K.square(b) + K.epsilon()) tmp = KC.conv2d(K.square(x), self.kernel_norm, strides=self.strides, padding=self.padding, data_format=self.data_format, filter_shape=self.kernel_norm_shape) xnorm = K.sqrt(tmp + xb + K.epsilon()) W = self.W / Wnorm output = KC.conv2d(x, W, strides=self.strides, padding=self.padding, data_format=self.data_format, filter_shape=self.kernel_shape) if K.backend() == 'theano': xnorm = K.pattern_broadcast(xnorm, [False, True, False, False]) output /= xnorm if self.use_bias: b /= Wnorm if self.data_format == 'channels_first': b = K.reshape(b, (1, self.filters, 1, 1)) elif self.data_format == 'channels_last': b = K.reshape(b, (1, 1, 1, self.filters)) else: raise ValueError('Invalid data_format:', self.data_format) b /= xnorm output += b output = self.activation(output) return output def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'activation': activations.serialize(self.activation), 'padding': self.padding, 'strides': self.strides, 'data_format': self.data_format, 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'use_bias': self.use_bias} base_config = super(CosineConvolution2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) CosineConv2D = CosineConvolution2D
keras-contrib/keras_contrib/layers/convolutional/cosineconvolution2d.py/0
{ "file_path": "keras-contrib/keras_contrib/layers/convolutional/cosineconvolution2d.py", "repo_id": "keras-contrib", "token_count": 5211 }
16
from keras import backend as K from keras.optimizers import Optimizer class Padam(Optimizer): """Partially adaptive momentum estimation optimizer. # Arguments lr: float >= 0. Learning rate. beta_1: float, 0 < beta < 1. Generally close to 1. beta_2: float, 0 < beta < 1. Generally close to 1. epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`. decay: float >= 0. Learning rate decay over each update. amsgrad: boolean. Whether to apply the AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and Beyond". partial: float, 0 <= partial <= 0.5 . Parameter controlling partial momentum adaption. For `partial=0`, this optimizer behaves like SGD, for `partial=0.5` it behaves like AMSGrad. # References - [Closing the Generalization Gap of Adaptive Gradient Methods in Training Deep Neural Networks](https://arxiv.org/pdf/1806.06763.pdf) """ def __init__(self, lr=1e-1, beta_1=0.9, beta_2=0.999, epsilon=1e-8, decay=0., amsgrad=False, partial=1. / 8., **kwargs): if partial < 0 or partial > 0.5: raise ValueError( "Padam: 'partial' must be a positive float with a maximum " "value of `0.5`, since higher values will cause divergence " "during training." ) super(Padam, self).__init__(**kwargs) with K.name_scope(self.__class__.__name__): self.iterations = K.variable(0, dtype='int64', name='iterations') self.lr = K.variable(lr, name='lr') self.beta_1 = K.variable(beta_1, name='beta_1') self.beta_2 = K.variable(beta_2, name='beta_2') self.decay = K.variable(decay, name='decay') if epsilon is None: epsilon = K.epsilon() self.epsilon = epsilon self.partial = partial self.initial_decay = decay self.amsgrad = amsgrad def get_updates(self, loss, params): grads = self.get_gradients(loss, params) self.updates = [K.update_add(self.iterations, 1)] lr = self.lr if self.initial_decay > 0: lr = lr * (1. / (1. + self.decay * K.cast(self.iterations, K.dtype(self.decay)))) t = K.cast(self.iterations, K.floatx()) + 1 lr_t = lr * (K.sqrt(1. - K.pow(self.beta_2, t)) / (1. - K.pow(self.beta_1, t))) ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] if self.amsgrad: vhats = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params] else: vhats = [K.zeros(1) for _ in params] self.weights = [self.iterations] + ms + vs + vhats for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats): m_t = (self.beta_1 * m) + (1. - self.beta_1) * g v_t = (self.beta_2 * v) + (1. - self.beta_2) * K.square(g) if self.amsgrad: vhat_t = K.maximum(vhat, v_t) denom = (K.sqrt(vhat_t) + self.epsilon) self.updates.append(K.update(vhat, vhat_t)) else: denom = (K.sqrt(v_t) + self.epsilon) self.updates.append(K.update(m, m_t)) self.updates.append(K.update(v, v_t)) # Partial momentum adaption. new_p = p - (lr_t * (m_t / (denom ** (self.partial * 2)))) # Apply constraints. if getattr(p, 'constraint', None) is not None: new_p = p.constraint(new_p) self.updates.append(K.update(p, new_p)) return self.updates def get_config(self): config = {'lr': float(K.get_value(self.lr)), 'beta_1': float(K.get_value(self.beta_1)), 'beta_2': float(K.get_value(self.beta_2)), 'decay': float(K.get_value(self.decay)), 'epsilon': self.epsilon, 'amsgrad': self.amsgrad, 'partial': self.partial} base_config = super(Padam, self).get_config() return dict(list(base_config.items()) + list(config.items()))
keras-contrib/keras_contrib/optimizers/padam.py/0
{ "file_path": "keras-contrib/keras_contrib/optimizers/padam.py", "repo_id": "keras-contrib", "token_count": 2198 }
17
import pytest from keras import backend as K @pytest.fixture(autouse=True) def clear_session_after_test(): """Test wrapper to clean up after TensorFlow and CNTK tests. This wrapper runs for all the tests in the keras test suite. """ yield if K.backend() == 'tensorflow' or K.backend() == 'cntk': K.clear_session()
keras-contrib/tests/conftest.py/0
{ "file_path": "keras-contrib/tests/conftest.py", "repo_id": "keras-contrib", "token_count": 126 }
18
import numpy as np import pytest from keras import backend as K from keras import regularizers from keras.layers import Input from keras.models import Sequential, Model from numpy.testing import assert_allclose from keras_contrib.layers import GroupNormalization from keras_contrib.utils.test_utils import layer_test input_1 = np.arange(10) input_2 = np.zeros(10) input_3 = np.ones(10) input_shapes = [np.ones((10, 10)), np.ones((10, 10, 10))] def test_basic_groupnorm(): layer_test(GroupNormalization, kwargs={'groups': 2, 'epsilon': 0.1, 'gamma_regularizer': regularizers.l2(0.01), 'beta_regularizer': regularizers.l2(0.01)}, input_shape=(3, 4, 2)) layer_test(GroupNormalization, kwargs={'groups': 2, 'epsilon': 0.1, 'axis': 1}, input_shape=(3, 4, 2)) layer_test(GroupNormalization, kwargs={'groups': 2, 'gamma_initializer': 'ones', 'beta_initializer': 'ones'}, input_shape=(3, 4, 2, 4)) if K.backend() != 'theano': layer_test(GroupNormalization, kwargs={'groups': 2, 'axis': 1, 'scale': False, 'center': False}, input_shape=(3, 4, 2, 4)) def test_groupnorm_correctness_1d(): model = Sequential() norm = GroupNormalization(input_shape=(10,), groups=2) model.add(norm) model.compile(loss='mse', optimizer='rmsprop') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10)) model.fit(x, x, epochs=5, verbose=0) out = model.predict(x) out -= K.eval(norm.beta) out /= K.eval(norm.gamma) assert_allclose(out.mean(), 0.0, atol=1e-1) assert_allclose(out.std(), 1.0, atol=1e-1) def test_groupnorm_correctness_2d(): model = Sequential() norm = GroupNormalization(axis=1, input_shape=(10, 6), groups=2) model.add(norm) model.compile(loss='mse', optimizer='rmsprop') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10, 6)) model.fit(x, x, epochs=5, verbose=0) out = model.predict(x) out -= np.reshape(K.eval(norm.beta), (1, 10, 1)) out /= np.reshape(K.eval(norm.gamma), (1, 10, 1)) assert_allclose(out.mean(axis=(0, 2)), 0.0, atol=1.1e-1) assert_allclose(out.std(axis=(0, 2)), 1.0, atol=1.1e-1) def test_groupnorm_correctness_2d_different_groups(): norm1 = GroupNormalization(axis=1, input_shape=(10, 6), groups=2) norm2 = GroupNormalization(axis=1, input_shape=(10, 6), groups=1) norm3 = GroupNormalization(axis=1, input_shape=(10, 6), groups=10) model = Sequential() model.add(norm1) model.compile(loss='mse', optimizer='rmsprop') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10, 6)) model.fit(x, x, epochs=5, verbose=0) out = model.predict(x) out -= np.reshape(K.eval(norm1.beta), (1, 10, 1)) out /= np.reshape(K.eval(norm1.gamma), (1, 10, 1)) assert_allclose(out.mean(axis=(0, 2)), 0.0, atol=1.1e-1) assert_allclose(out.std(axis=(0, 2)), 1.0, atol=1.1e-1) model = Sequential() model.add(norm2) model.compile(loss='mse', optimizer='rmsprop') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10, 6)) model.fit(x, x, epochs=5, verbose=0) out = model.predict(x) out -= np.reshape(K.eval(norm2.beta), (1, 10, 1)) out /= np.reshape(K.eval(norm2.gamma), (1, 10, 1)) assert_allclose(out.mean(axis=(0, 2)), 0.0, atol=1.1e-1) assert_allclose(out.std(axis=(0, 2)), 1.0, atol=1.1e-1) model = Sequential() model.add(norm3) model.compile(loss='mse', optimizer='rmsprop') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10, 6)) model.fit(x, x, epochs=5, verbose=0) out = model.predict(x) out -= np.reshape(K.eval(norm3.beta), (1, 10, 1)) out /= np.reshape(K.eval(norm3.gamma), (1, 10, 1)) assert_allclose(out.mean(axis=(0, 2)), 0.0, atol=1.1e-1) assert_allclose(out.std(axis=(0, 2)), 1.0, atol=1.1e-1) def test_groupnorm_mode_twice(): # This is a regression test for issue #4881 with the old # batch normalization functions in the Theano backend. model = Sequential() model.add(GroupNormalization(input_shape=(10, 5, 5), axis=1, groups=2)) model.add(GroupNormalization(input_shape=(10, 5, 5), axis=1, groups=2)) model.compile(loss='mse', optimizer='sgd') x = np.random.normal(loc=5.0, scale=10.0, size=(20, 10, 5, 5)) model.fit(x, x, epochs=1, verbose=0) model.predict(x) def test_groupnorm_convnet(): model = Sequential() norm = GroupNormalization(axis=1, input_shape=(3, 4, 4), groups=3) model.add(norm) model.compile(loss='mse', optimizer='sgd') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4)) model.fit(x, x, epochs=4, verbose=0) out = model.predict(x) out -= np.reshape(K.eval(norm.beta), (1, 3, 1, 1)) out /= np.reshape(K.eval(norm.gamma), (1, 3, 1, 1)) assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1) assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1) @pytest.mark.skipif((K.backend() == 'theano'), reason='Bug with theano backend') def test_groupnorm_convnet_no_center_no_scale(): model = Sequential() norm = GroupNormalization(axis=-1, center=False, scale=False, input_shape=(3, 4, 4), groups=2) model.add(norm) model.compile(loss='mse', optimizer='sgd') # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4)) model.fit(x, x, epochs=4, verbose=0) out = model.predict(x) assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1) assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1) def test_shared_groupnorm(): '''Test that a GN layer can be shared across different data streams. ''' # Test single layer reuse bn = GroupNormalization(input_shape=(10,), groups=2) x1 = Input(shape=(10,)) bn(x1) x2 = Input(shape=(10,)) y2 = bn(x2) x = np.random.normal(loc=5.0, scale=10.0, size=(2, 10)) model = Model(x2, y2) assert len(model.updates) == 0 model.compile('sgd', 'mse') model.train_on_batch(x, x) # Test model-level reuse x3 = Input(shape=(10,)) y3 = model(x3) new_model = Model(x3, y3) assert len(model.updates) == 0 new_model.compile('sgd', 'mse') new_model.train_on_batch(x, x) def test_that_trainable_disables_updates(): val_a = np.random.random((10, 4)) val_out = np.random.random((10, 4)) a = Input(shape=(4,)) layer = GroupNormalization(input_shape=(4,), groups=2) b = layer(a) model = Model(a, b) model.trainable = False assert len(model.updates) == 0 model.compile('sgd', 'mse') assert len(model.updates) == 0 x1 = model.predict(val_a) model.train_on_batch(val_a, val_out) x2 = model.predict(val_a) assert_allclose(x1, x2, atol=1e-7) model.trainable = True model.compile('sgd', 'mse') assert len(model.updates) == 0 model.train_on_batch(val_a, val_out) x2 = model.predict(val_a) assert np.abs(np.sum(x1 - x2)) > 1e-5 layer.trainable = False model.compile('sgd', 'mse') assert len(model.updates) == 0 x1 = model.predict(val_a) model.train_on_batch(val_a, val_out) x2 = model.predict(val_a) assert_allclose(x1, x2, atol=1e-7) if __name__ == '__main__': pytest.main([__file__])
keras-contrib/tests/keras_contrib/layers/normalization/test_groupnormalization.py/0
{ "file_path": "keras-contrib/tests/keras_contrib/layers/normalization/test_groupnormalization.py", "repo_id": "keras-contrib", "token_count": 3920 }
19
import os import pytest from github import Github try: import pathlib except ImportError: import pathlib2 as pathlib path_to_keras_contrib = pathlib.Path(__file__).resolve().parents[2] path_to_codeowners = path_to_keras_contrib / 'CODEOWNERS' authenticated = True try: github_client = Github(os.environ['GITHUB_TOKEN']) except KeyError: try: github_client = Github(os.environ['GITHUB_USER'], os.environ['GITHUB_PASSWORD']) except KeyError: authenticated = False def parse_codeowners(): map_path_owner = [] for line in open(path_to_codeowners, 'r'): line = line.strip() if line.startswith('#') or line == '': continue x = line.split(' ') path = path_to_keras_contrib / x[0] owner = x[-1] map_path_owner.append((path, owner)) return map_path_owner def test_codeowners_file_exist(): for path, _ in parse_codeowners(): assert path.exists() @pytest.mark.skipif(not authenticated, reason='It should be possible to run the test without' 'authentication, but we might get our request refused' 'by github. To be deterministic, we\'ll disable it.') def test_codeowners_user_exist(): for _, user in parse_codeowners(): assert user[0] == '@' assert github_client.get_user(user[1:]) directories_to_test = [ 'examples', 'keras_contrib/activations', 'keras_contrib/applications', 'keras_contrib/callbacks', 'keras_contrib/constraints', 'keras_contrib/datasets', 'keras_contrib/initializers', 'keras_contrib/layers', 'keras_contrib/losses', 'keras_contrib/metrics', 'keras_contrib/optimizers', 'keras_contrib/preprocessing', 'keras_contrib/regularizers', 'keras_contrib/wrappers' ] directories_to_test = [path_to_keras_contrib / x for x in directories_to_test] # TODO: remove those files or find them owners. exclude = [ 'examples/cifar10_clr.py', 'examples/cifar10_densenet.py', 'examples/cifar10_nasnet.py', 'examples/cifar10_resnet.py', 'examples/cifar10_ror.py', 'examples/cifar10_wide_resnet.py', 'examples/conll2000_chunking_crf.py', 'examples/improved_wgan.py', 'examples/jaccard_loss.py', 'keras_contrib/callbacks/cyclical_learning_rate.py', 'keras_contrib/callbacks/dead_relu_detector.py', 'keras_contrib/applications/resnet.py', 'keras_contrib/constraints/clip.py', 'keras_contrib/datasets/coco.py', 'keras_contrib/datasets/conll2000.py', 'keras_contrib/datasets/pascal_voc.py', 'keras_contrib/initializers/convaware.py', 'keras_contrib/losses/crf_losses.py', 'keras_contrib/losses/dssim.py', 'keras_contrib/losses/jaccard.py', 'keras_contrib/layers/advanced_activations/pelu.py', 'keras_contrib/layers/advanced_activations/srelu.py', 'keras_contrib/layers/convolutional/cosineconvolution2d.py', 'keras_contrib/layers/core.py', 'keras_contrib/layers/crf.py', 'keras_contrib/layers/normalization/instancenormalization.py', 'keras_contrib/optimizers/ftml.py', 'keras_contrib/optimizers/lars.py', 'keras_contrib/metrics/crf_accuracies.py', ] exclude = [path_to_keras_contrib / x for x in exclude] @pytest.mark.parametrize('directory', directories_to_test) def test_all_files_have_owners(directory): files_with_owners = [x[0] for x in parse_codeowners()] for root, dirs, files in os.walk(directory): for name in files: file_path = pathlib.Path(root) / name if file_path.suffix != '.py': continue if file_path.name == '__init__.py': continue if file_path in exclude: continue assert file_path in files_with_owners if __name__ == '__main__': pytest.main([__file__])
keras-contrib/tests/tooling/test_codeowners.py/0
{ "file_path": "keras-contrib/tests/tooling/test_codeowners.py", "repo_id": "keras-contrib", "token_count": 1779 }
20
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
keras-core/LICENSE/0
{ "file_path": "keras-core/LICENSE", "repo_id": "keras-core", "token_count": 3167 }
21
# To run this demo, you will need to spin up a "TPU VM" on Google Cloud. # Please follow instructions here: https://cloud.google.com/tpu/docs/run-calculation-jax # Force a JAX backend import os, pprint, collections os.environ["KERAS_BACKEND"] = "jax" pp = pprint.PrettyPrinter() import jax import jax.numpy as jnp import tensorflow as tf # just for tf.data import keras_core as keras # Keras multi-backend import numpy as np from tqdm import tqdm from jax.experimental import mesh_utils from jax.sharding import Mesh from jax.sharding import NamedSharding from jax.sharding import PartitionSpec as P """ Dataset Classic MNIST, loaded using tf.data """ BATCH_SIZE = 192 (x_train, train_labels), ( x_eval, eval_labels, ) = keras.datasets.mnist.load_data() x_train = np.expand_dims(x_train, axis=-1).astype( np.float32 ) # from 28x28 to 28x28 x 1 color channel (B&W) x_eval = np.expand_dims(x_eval, axis=-1).astype(np.float32) train_data = tf.data.Dataset.from_tensor_slices((x_train, train_labels)) train_data = train_data.shuffle(5000, reshuffle_each_iteration=True) train_data = train_data.batch(BATCH_SIZE, drop_remainder=True) train_data = train_data.repeat() eval_data = tf.data.Dataset.from_tensor_slices((x_eval, eval_labels)) eval_data = eval_data.batch(10000) # everything as one batch STEPS_PER_EPOCH = len(train_labels) // BATCH_SIZE """ Keras model Simple but non-trivial model with: * Batch Normalization (non-trainable state updated during trainig, different training-time and inference behavior) * Dropout (randomness, different training time and inference behavior) """ # Keras "sequential" model building style def make_backbone(): return keras.Sequential( [ keras.layers.Rescaling( 1.0 / 255.0 ), # input images are in the range [0, 255] keras.layers.Conv2D( filters=12, kernel_size=3, padding="same", use_bias=False ), keras.layers.BatchNormalization(scale=False, center=True), keras.layers.Activation("relu"), keras.layers.Conv2D( filters=24, kernel_size=6, padding="same", use_bias=False, strides=2, ), keras.layers.BatchNormalization(scale=False, center=True), keras.layers.Activation("relu"), keras.layers.Conv2D( filters=32, kernel_size=6, padding="same", use_bias=False, strides=2, name="large_k", ), keras.layers.BatchNormalization(scale=False, center=True), keras.layers.Activation("relu"), ], name="backbone", ) def make_model(): input = keras.Input(shape=[28, 28, 1]) y = make_backbone()(input) y = keras.layers.Flatten()(y) y = keras.layers.Dense(200, activation="relu")(y) y = keras.layers.Dropout(0.4)(y) y = keras.layers.Dense(10, activation="softmax")(y) model = keras.Model(inputs=input, outputs=y) return model """ JAX-native distribution with a Keras model For now, you have to write a custom training loop for this Note: The features required by jax.sharding are not supported by the Colab TPU runtime at this time, but are available on Cloud TPU VMs and Kaggle TPU VMs. """ if len(jax.local_devices()) < 8: raise Exception("This part requires 8 devices to run") else: print("\nIdentified local devices:") pp.pprint(jax.local_devices()) # ----------------- Keras --------------------- # instantiate the model model = make_model() # learning rate lr = keras.optimizers.schedules.ExponentialDecay(0.01, STEPS_PER_EPOCH, 0.6) # optimizer optimizer = keras.optimizers.Adam(lr) # initialize all state with .build() (one_batch, one_batch_labels) = next(iter(train_data)) model.build(one_batch) optimizer.build(model.trainable_variables) """ Distribution settings * Sharding the data on the batch axis * Replicating all model variables Note: this implements standard "data parallel" distributed training * Just for show, sharding the largest convolutional kernel along the "channels" axis 4-ways and replicating 2-ways Note: this does not reflect a best practice but is intended to show that you can split a very large kernel across multiple devices if you have to """ print( "\nMostly data-parallel distribution. " "Data is sharded across devices while the model is replicated. " "For demo purposes, we split the largest kernel 4-ways " "(and replicate 2-ways since we have 8 devices)." ) # ------------------ Jax ---------------------- devices = mesh_utils.create_device_mesh((8,)) # data will be split along the batch axis data_mesh = Mesh(devices, axis_names=("batch",)) # naming axes of the mesh # naming axes of the sharded partition data_sharding = NamedSharding( data_mesh, P( "batch", ), ) # all variables will be replicated on all devices var_mesh = Mesh(devices, axis_names=("_")) # in NamedSharding, axes that are not mentioned are replicated (all axes here) var_replication = NamedSharding(var_mesh, P()) # for the demo, we will split the largest kernel 4-ways (and replicate 2-ways since we have 8 devices) large_kernel_mesh = Mesh( devices.reshape((-1, 4)), axis_names=(None, "out_chan") ) # naming axes of the mesh large_kernel_sharding = NamedSharding( large_kernel_mesh, P(None, None, None, "out_chan") ) # naming axes of the sharded partition # ----------------- Keras --------------------- # Use Keras APIs to find the variable of a specific layer (we will be sharding this one in a special way) # In a Conv2D or Dense layer, the variables are 'kernel' and 'bias' special_layer_var = model.get_layer("backbone").get_layer("large_k").kernel # ------------------ Jax ---------------------- # - accessing variables in Keras lists model.trainable_variables, # - model.non_trainable_variables and optimizer.variables # Apply the distribution settings to the model variables non_trainable_variables = jax.device_put( model.non_trainable_variables, var_replication ) optimizer_variables = jax.device_put(optimizer.variables, var_replication) # this is what you would do replicate all trainable variables: # trainable_variables = jax.device_put(model.trainable_variables, var_replication) # For the demo, we split the largest kernel 4-ways instead of replicating it. # We still replicate all other trainable variables as in standard "data-parallel" # distributed training. print_once = True trainable_variables = model.trainable_variables for i, v in enumerate(trainable_variables): if v is special_layer_var: # Apply distribution settings: sharding sharded_v = jax.device_put(v, large_kernel_sharding) trainable_variables[i] = sharded_v print("Sharding of convolutional", v.name, v.shape) jax.debug.visualize_array_sharding( jnp.reshape(sharded_v, [-1, v.shape[-1]]) ) else: # Apply distribution settings: replication replicated_v = jax.device_put(v, var_replication) trainable_variables[i] = replicated_v if print_once: print_once = False print( "\nSharding of all other model variables (they are replicated)" ) jax.debug.visualize_array_sharding( jnp.reshape(replicated_v, [-1, v.shape[-1]]) ) # collect state in a handy named tuple TrainingState = collections.namedtuple( "TrainingState", ["trainable_variables", "non_trainable_variables", "optimizer_variables"], ) device_train_state = TrainingState( trainable_variables=trainable_variables, non_trainable_variables=non_trainable_variables, optimizer_variables=optimizer_variables, ) # display data sharding x, y = next(iter(train_data)) sharded_x = jax.device_put(x.numpy(), data_sharding) print("Data sharding") jax.debug.visualize_array_sharding(jnp.reshape(sharded_x, [-1, 28 * 28])) # ------------------ Jax ---------------------- # - Using Keras-provided stateless APIs # - model.stateless_call # - optimizer.stateless_apply # These functions also work on other backends. # define loss loss = keras.losses.SparseCategoricalCrossentropy() # This is the loss function that will be differentiated. # Keras provides a pure functional forward pass: model.stateless_call def compute_loss(trainable_variables, non_trainable_variables, x, y): y_pred, updated_non_trainable_variables = model.stateless_call( trainable_variables, non_trainable_variables, x ) loss_value = loss(y, y_pred) return loss_value, updated_non_trainable_variables # function to compute gradients compute_gradients = jax.value_and_grad(compute_loss, has_aux=True) # Trainig step: Keras provides a pure functional optimizer.stateless_apply @jax.jit def train_step(train_state, x, y): (loss_value, non_trainable_variables), grads = compute_gradients( train_state.trainable_variables, train_state.non_trainable_variables, x, y, ) trainable_variables, optimizer_variables = optimizer.stateless_apply( train_state.optimizer_variables, grads, train_state.trainable_variables ) return loss_value, TrainingState( trainable_variables, non_trainable_variables, optimizer_variables ) # training loop EPOCHS = 5 print("\nTrainig:") data_iter = iter(train_data) for epoch in range(EPOCHS): for i in tqdm(range(STEPS_PER_EPOCH)): x, y = next(data_iter) sharded_x = jax.device_put(x.numpy(), data_sharding) loss_value, device_train_state = train_step( device_train_state, sharded_x, y.numpy() ) print("Epoch", epoch, "loss:", loss_value) # The output of the model is still sharded. Sharding follows the data. data, labels = next(iter(eval_data)) sharded_data = jax.device_put(data.numpy(), data_sharding) @jax.jit def predict(data): predictions, updated_non_trainable_variables = model.stateless_call( device_train_state.trainable_variables, device_train_state.non_trainable_variables, data, ) return predictions predictions = predict(sharded_data) print("\nModel output sharding follows data sharding:") jax.debug.visualize_array_sharding(predictions) # Post-processing model state update to write them back into the model update = lambda variable, value: variable.assign(value) jax.tree_map( update, model.trainable_variables, device_train_state.trainable_variables ) jax.tree_map( update, model.non_trainable_variables, device_train_state.non_trainable_variables, ) jax.tree_map( update, optimizer.variables, device_train_state.optimizer_variables ) # check that the model has the new state by running an eval # known issue: the optimizer should not be required here model.compile( loss=keras.losses.SparseCategoricalCrossentropy(), metrics=[keras.metrics.SparseCategoricalAccuracy()], ) print("\nUpdating model and running an eval:") loss, accuracy = model.evaluate(eval_data) print("The model achieved an evaluation accuracy of:", accuracy)
keras-core/examples/demo_jax_distributed.py/0
{ "file_path": "keras-core/examples/demo_jax_distributed.py", "repo_id": "keras-core", "token_count": 4232 }
22
""" Title: Speaker Recognition Author: [Fadi Badine](https://twitter.com/fadibadine) Converted to Keras Core by: [Fadi Badine](https://twitter.com/fadibadine) Date created: 14/06/2020 Last modified: 19/07/2023 Description: Classify speakers using Fast Fourier Transform (FFT) and a 1D Convnet. Accelerator: GPU """ """ ## Introduction This example demonstrates how to create a model to classify speakers from the frequency domain representation of speech recordings, obtained via Fast Fourier Transform (FFT). It shows the following: - How to use `tf.data` to load, preprocess and feed audio streams into a model - How to create a 1D convolutional network with residual connections for audio classification. Our process: - We prepare a dataset of speech samples from different speakers, with the speaker as label. - We add background noise to these samples to augment our data. - We take the FFT of these samples. - We train a 1D convnet to predict the correct speaker given a noisy FFT speech sample. Note: - This example should be run with TensorFlow 2.3 or higher, or `tf-nightly`. - The noise samples in the dataset need to be resampled to a sampling rate of 16000 Hz before using the code in this example. In order to do this, you will need to have installed `ffmpg`. """ """ ## Setup """ import os os.environ["KERAS_BACKEND"] = "tensorflow" import shutil import numpy as np import tensorflow as tf import keras_core as keras from pathlib import Path from IPython.display import display, Audio # Get the data from https://www.kaggle.com/kongaevans/speaker-recognition-dataset/download # and save it to the 'Downloads' folder in your HOME directory DATASET_ROOT = os.path.join( os.path.expanduser("~"), "Downloads/16000_pcm_speeches" ) # The folders in which we will put the audio samples and the noise samples AUDIO_SUBFOLDER = "audio" NOISE_SUBFOLDER = "noise" DATASET_AUDIO_PATH = os.path.join(DATASET_ROOT, AUDIO_SUBFOLDER) DATASET_NOISE_PATH = os.path.join(DATASET_ROOT, NOISE_SUBFOLDER) # Percentage of samples to use for validation VALID_SPLIT = 0.1 # Seed to use when shuffling the dataset and the noise SHUFFLE_SEED = 43 # The sampling rate to use. # This is the one used in all the audio samples. # We will resample all the noise to this sampling rate. # This will also be the output size of the audio wave samples # (since all samples are of 1 second long) SAMPLING_RATE = 16000 # The factor to multiply the noise with according to: # noisy_sample = sample + noise * prop * scale # where prop = sample_amplitude / noise_amplitude SCALE = 0.5 BATCH_SIZE = 128 EPOCHS = 1 """ ## Data preparation The dataset is composed of 7 folders, divided into 2 groups: - Speech samples, with 5 folders for 5 different speakers. Each folder contains 1500 audio files, each 1 second long and sampled at 16000 Hz. - Background noise samples, with 2 folders and a total of 6 files. These files are longer than 1 second (and originally not sampled at 16000 Hz, but we will resample them to 16000 Hz). We will use those 6 files to create 354 1-second-long noise samples to be used for training. Let's sort these 2 categories into 2 folders: - An `audio` folder which will contain all the per-speaker speech sample folders - A `noise` folder which will contain all the noise samples """ """ Before sorting the audio and noise categories into 2 folders, we have the following directory structure: ``` main_directory/ ...speaker_a/ ...speaker_b/ ...speaker_c/ ...speaker_d/ ...speaker_e/ ...other/ ..._background_noise_/ ``` After sorting, we end up with the following structure: ``` main_directory/ ...audio/ ......speaker_a/ ......speaker_b/ ......speaker_c/ ......speaker_d/ ......speaker_e/ ...noise/ ......other/ ......_background_noise_/ ``` """ # If folder `audio`, does not exist, create it, otherwise do nothing if os.path.exists(DATASET_AUDIO_PATH) is False: os.makedirs(DATASET_AUDIO_PATH) # If folder `noise`, does not exist, create it, otherwise do nothing if os.path.exists(DATASET_NOISE_PATH) is False: os.makedirs(DATASET_NOISE_PATH) for folder in os.listdir(DATASET_ROOT): if os.path.isdir(os.path.join(DATASET_ROOT, folder)): if folder in [AUDIO_SUBFOLDER, NOISE_SUBFOLDER]: # If folder is `audio` or `noise`, do nothing continue elif folder in ["other", "_background_noise_"]: # If folder is one of the folders that contains noise samples, # move it to the `noise` folder shutil.move( os.path.join(DATASET_ROOT, folder), os.path.join(DATASET_NOISE_PATH, folder), ) else: # Otherwise, it should be a speaker folder, then move it to # `audio` folder shutil.move( os.path.join(DATASET_ROOT, folder), os.path.join(DATASET_AUDIO_PATH, folder), ) """ ## Noise preparation In this section: - We load all noise samples (which should have been resampled to 16000) - We split those noise samples to chunks of 16000 samples which correspond to 1 second duration each """ # Get the list of all noise files noise_paths = [] for subdir in os.listdir(DATASET_NOISE_PATH): subdir_path = Path(DATASET_NOISE_PATH) / subdir if os.path.isdir(subdir_path): noise_paths += [ os.path.join(subdir_path, filepath) for filepath in os.listdir(subdir_path) if filepath.endswith(".wav") ] print( "Found {} files belonging to {} directories".format( len(noise_paths), len(os.listdir(DATASET_NOISE_PATH)) ) ) """ Resample all noise samples to 16000 Hz """ command = ( "for dir in `ls -1 " + DATASET_NOISE_PATH + "`; do " "for file in `ls -1 " + DATASET_NOISE_PATH + "/$dir/*.wav`; do " "sample_rate=`ffprobe -hide_banner -loglevel panic -show_streams " "$file | grep sample_rate | cut -f2 -d=`; " "if [ $sample_rate -ne 16000 ]; then " "ffmpeg -hide_banner -loglevel panic -y " "-i $file -ar 16000 temp.wav; " "mv temp.wav $file; " "fi; done; done" ) os.system(command) # Split noise into chunks of 16,000 steps each def load_noise_sample(path): sample, sampling_rate = tf.audio.decode_wav( tf.io.read_file(path), desired_channels=1 ) if sampling_rate == SAMPLING_RATE: # Number of slices of 16000 each that can be generated from the noise sample slices = int(sample.shape[0] / SAMPLING_RATE) sample = tf.split(sample[: slices * SAMPLING_RATE], slices) return sample else: print("Sampling rate for {} is incorrect. Ignoring it".format(path)) return None noises = [] for path in noise_paths: sample = load_noise_sample(path) if sample: noises.extend(sample) noises = tf.stack(noises) print( "{} noise files were split into {} noise samples where each is {} sec. long".format( len(noise_paths), noises.shape[0], noises.shape[1] // SAMPLING_RATE ) ) """ ## Dataset generation """ def paths_and_labels_to_dataset(audio_paths, labels): """Constructs a dataset of audios and labels.""" path_ds = tf.data.Dataset.from_tensor_slices(audio_paths) audio_ds = path_ds.map( lambda x: path_to_audio(x), num_parallel_calls=tf.data.AUTOTUNE ) label_ds = tf.data.Dataset.from_tensor_slices(labels) return tf.data.Dataset.zip((audio_ds, label_ds)) def path_to_audio(path): """Reads and decodes an audio file.""" audio = tf.io.read_file(path) audio, _ = tf.audio.decode_wav(audio, 1, SAMPLING_RATE) return audio def add_noise(audio, noises=None, scale=0.5): if noises is not None: # Create a random tensor of the same size as audio ranging from # 0 to the number of noise stream samples that we have. tf_rnd = tf.random.uniform( (tf.shape(audio)[0],), 0, noises.shape[0], dtype=tf.int32 ) noise = tf.gather(noises, tf_rnd, axis=0) # Get the amplitude proportion between the audio and the noise prop = tf.math.reduce_max(audio, axis=1) / tf.math.reduce_max( noise, axis=1 ) prop = tf.repeat( tf.expand_dims(prop, axis=1), tf.shape(audio)[1], axis=1 ) # Adding the rescaled noise to audio audio = audio + noise * prop * scale return audio def audio_to_fft(audio): # Since tf.signal.fft applies FFT on the innermost dimension, # we need to squeeze the dimensions and then expand them again # after FFT audio = tf.squeeze(audio, axis=-1) fft = tf.signal.fft( tf.cast(tf.complex(real=audio, imag=tf.zeros_like(audio)), tf.complex64) ) fft = tf.expand_dims(fft, axis=-1) # Return the absolute value of the first half of the FFT # which represents the positive frequencies return tf.math.abs(fft[:, : (audio.shape[1] // 2), :]) # Get the list of audio file paths along with their corresponding labels class_names = os.listdir(DATASET_AUDIO_PATH) print( "Our class names: {}".format( class_names, ) ) audio_paths = [] labels = [] for label, name in enumerate(class_names): print( "Processing speaker {}".format( name, ) ) dir_path = Path(DATASET_AUDIO_PATH) / name speaker_sample_paths = [ os.path.join(dir_path, filepath) for filepath in os.listdir(dir_path) if filepath.endswith(".wav") ] audio_paths += speaker_sample_paths labels += [label] * len(speaker_sample_paths) print( "Found {} files belonging to {} classes.".format( len(audio_paths), len(class_names) ) ) # Shuffle rng = np.random.RandomState(SHUFFLE_SEED) rng.shuffle(audio_paths) rng = np.random.RandomState(SHUFFLE_SEED) rng.shuffle(labels) # Split into training and validation num_val_samples = int(VALID_SPLIT * len(audio_paths)) print("Using {} files for training.".format(len(audio_paths) - num_val_samples)) train_audio_paths = audio_paths[:-num_val_samples] train_labels = labels[:-num_val_samples] print("Using {} files for validation.".format(num_val_samples)) valid_audio_paths = audio_paths[-num_val_samples:] valid_labels = labels[-num_val_samples:] # Create 2 datasets, one for training and the other for validation train_ds = paths_and_labels_to_dataset(train_audio_paths, train_labels) train_ds = train_ds.shuffle( buffer_size=BATCH_SIZE * 8, seed=SHUFFLE_SEED ).batch(BATCH_SIZE) valid_ds = paths_and_labels_to_dataset(valid_audio_paths, valid_labels) valid_ds = valid_ds.shuffle(buffer_size=32 * 8, seed=SHUFFLE_SEED).batch(32) # Add noise to the training set train_ds = train_ds.map( lambda x, y: (add_noise(x, noises, scale=SCALE), y), num_parallel_calls=tf.data.AUTOTUNE, ) # Transform audio wave to the frequency domain using `audio_to_fft` train_ds = train_ds.map( lambda x, y: (audio_to_fft(x), y), num_parallel_calls=tf.data.AUTOTUNE ) train_ds = train_ds.prefetch(tf.data.AUTOTUNE) valid_ds = valid_ds.map( lambda x, y: (audio_to_fft(x), y), num_parallel_calls=tf.data.AUTOTUNE ) valid_ds = valid_ds.prefetch(tf.data.AUTOTUNE) """ ## Model Definition """ def residual_block(x, filters, conv_num=3, activation="relu"): # Shortcut s = keras.layers.Conv1D(filters, 1, padding="same")(x) for i in range(conv_num - 1): x = keras.layers.Conv1D(filters, 3, padding="same")(x) x = keras.layers.Activation(activation)(x) x = keras.layers.Conv1D(filters, 3, padding="same")(x) x = keras.layers.Add()([x, s]) x = keras.layers.Activation(activation)(x) return keras.layers.MaxPool1D(pool_size=2, strides=2)(x) def build_model(input_shape, num_classes): inputs = keras.layers.Input(shape=input_shape, name="input") x = residual_block(inputs, 16, 2) x = residual_block(x, 32, 2) x = residual_block(x, 64, 3) x = residual_block(x, 128, 3) x = residual_block(x, 128, 3) x = keras.layers.AveragePooling1D(pool_size=3, strides=3)(x) x = keras.layers.Flatten()(x) x = keras.layers.Dense(256, activation="relu")(x) x = keras.layers.Dense(128, activation="relu")(x) outputs = keras.layers.Dense( num_classes, activation="softmax", name="output" )(x) return keras.models.Model(inputs=inputs, outputs=outputs) model = build_model((SAMPLING_RATE // 2, 1), len(class_names)) model.summary() # Compile the model using Adam's default learning rate model.compile( optimizer="Adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) # Add callbacks: # 'EarlyStopping' to stop training when the model is not enhancing anymore # 'ModelCheckPoint' to always keep the model that has the best val_accuracy model_save_filename = "model.keras" earlystopping_cb = keras.callbacks.EarlyStopping( patience=10, restore_best_weights=True ) mdlcheckpoint_cb = keras.callbacks.ModelCheckpoint( model_save_filename, monitor="val_accuracy", save_best_only=True ) """ ## Training """ history = model.fit( train_ds, epochs=EPOCHS, validation_data=valid_ds, callbacks=[earlystopping_cb, mdlcheckpoint_cb], ) """ ## Evaluation """ print(model.evaluate(valid_ds)) """ We get ~ 98% validation accuracy. """ """ ## Demonstration Let's take some samples and: - Predict the speaker - Compare the prediction with the real speaker - Listen to the audio to see that despite the samples being noisy, the model is still pretty accurate """ SAMPLES_TO_DISPLAY = 10 test_ds = paths_and_labels_to_dataset(valid_audio_paths, valid_labels) test_ds = test_ds.shuffle(buffer_size=BATCH_SIZE * 8, seed=SHUFFLE_SEED).batch( BATCH_SIZE ) test_ds = test_ds.map( lambda x, y: (add_noise(x, noises, scale=SCALE), y), num_parallel_calls=tf.data.AUTOTUNE, ) for audios, labels in test_ds.take(1): # Get the signal FFT ffts = audio_to_fft(audios) # Predict y_pred = model.predict(ffts) # Take random samples rnd = np.random.randint(0, BATCH_SIZE, SAMPLES_TO_DISPLAY) audios = audios.numpy()[rnd, :, :] labels = labels.numpy()[rnd] y_pred = np.argmax(y_pred, axis=-1)[rnd] for index in range(SAMPLES_TO_DISPLAY): # For every sample, print the true and predicted label # as well as run the voice with the noise print( "Speaker:\33{} {}\33[0m\tPredicted:\33{} {}\33[0m".format( "[92m" if labels[index] == y_pred[index] else "[91m", class_names[labels[index]], "[92m" if labels[index] == y_pred[index] else "[91m", class_names[y_pred[index]], ) ) display(Audio(audios[index, :, :].squeeze(), rate=SAMPLING_RATE))
keras-core/examples/keras_io/tensorflow/audio/speaker_recognition_using_cnn.py/0
{ "file_path": "keras-core/examples/keras_io/tensorflow/audio/speaker_recognition_using_cnn.py", "repo_id": "keras-core", "token_count": 5817 }
23
""" Title: Trainer pattern Author: [nkovela1](https://nkovela1.github.io/) Date created: 2022/09/19 Last modified: 2022/09/26 Description: Guide on how to share a custom training step across multiple Keras models. Accelerator: GPU """ """ ## Introduction This example shows how to create a custom training step using the "Trainer pattern", which can then be shared across multiple Keras models. This pattern overrides the `train_step()` method of the `keras.Model` class, allowing for training loops beyond plain supervised learning. The Trainer pattern can also easily be adapted to more complex models with larger custom training steps, such as [this end-to-end GAN model](https://keras.io/guides/customizing_what_happens_in_fit/#wrapping-up-an-endtoend-gan-example), by putting the custom training step in the Trainer class definition. """ """ ## Setup """ import tensorflow as tf import keras_core as keras # Load MNIST dataset and standardize the data mnist = keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 """ ## Define the Trainer class A custom training and evaluation step can be created by overriding the `train_step()` and `test_step()` method of a `Model` subclass: """ class MyTrainer(keras.Model): def __init__(self, model): super().__init__() self.model = model # Create loss and metrics here. self.loss_fn = keras.losses.SparseCategoricalCrossentropy() self.accuracy_metric = keras.metrics.SparseCategoricalAccuracy() @property def metrics(self): # List metrics here. return [self.accuracy_metric] def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self.model(x, training=True) # Forward pass # Compute loss value loss = self.loss_fn(y, y_pred) # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) # Update metrics for metric in self.metrics: metric.update_state(y, y_pred) # Return a dict mapping metric names to current value. return {m.name: m.result() for m in self.metrics} def test_step(self, data): x, y = data # Inference step y_pred = self.model(x, training=False) # Update metrics for metric in self.metrics: metric.update_state(y, y_pred) return {m.name: m.result() for m in self.metrics} def call(self, x): # Equivalent to `call()` of the wrapped keras.Model x = self.model(x) return x """ ## Define multiple models to share the custom training step Let's define two different models that can share our Trainer class and its custom `train_step()`: """ # A model defined using Sequential API model_a = keras.models.Sequential( [ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(256, activation="relu"), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation="softmax"), ] ) # A model defined using Functional API func_input = keras.Input(shape=(28, 28, 1)) x = keras.layers.Flatten(input_shape=(28, 28))(func_input) x = keras.layers.Dense(512, activation="relu")(x) x = keras.layers.Dropout(0.4)(x) func_output = keras.layers.Dense(10, activation="softmax")(x) model_b = keras.Model(func_input, func_output) """ ## Create Trainer class objects from the models """ trainer_1 = MyTrainer(model_a) trainer_2 = MyTrainer(model_b) """ ## Compile and fit the models to the MNIST dataset """ trainer_1.compile(optimizer=keras.optimizers.SGD()) trainer_1.fit( x_train, y_train, epochs=5, batch_size=64, validation_data=(x_test, y_test) ) trainer_2.compile(optimizer=keras.optimizers.Adam()) trainer_2.fit( x_train, y_train, epochs=5, batch_size=64, validation_data=(x_test, y_test) )
keras-core/examples/keras_io/tensorflow/keras_recipes/trainer_pattern.py/0
{ "file_path": "keras-core/examples/keras_io/tensorflow/keras_recipes/trainer_pattern.py", "repo_id": "keras-core", "token_count": 1560 }
24
""" Title: Distilling Vision Transformers Author: [Sayak Paul](https://twitter.com/RisingSayak) Date created: 2022/04/05 Last modified: 2023/09/16 Description: Distillation of Vision Transformers through attention. Accelerator: GPU """ """ ## Introduction In the original *Vision Transformers* (ViT) paper ([Dosovitskiy et al.](https://arxiv.org/abs/2010.11929)), the authors concluded that to perform on par with Convolutional Neural Networks (CNNs), ViTs need to be pre-trained on larger datasets. The larger the better. This is mainly due to the lack of inductive biases in the ViT architecture -- unlike CNNs, they don't have layers that exploit locality. In a follow-up paper ([Steiner et al.](https://arxiv.org/abs/2106.10270)), the authors show that it is possible to substantially improve the performance of ViTs with stronger regularization and longer training. Many groups have proposed different ways to deal with the problem of data-intensiveness of ViT training. One such way was shown in the *Data-efficient image Transformers*, (DeiT) paper ([Touvron et al.](https://arxiv.org/abs/2012.12877)). The authors introduced a distillation technique that is specific to transformer-based vision models. DeiT is among the first works to show that it's possible to train ViTs well without using larger datasets. In this example, we implement the distillation recipe proposed in DeiT. This requires us to slightly tweak the original ViT architecture and write a custom training loop to implement the distillation recipe. To comfortably navigate through this example, you'll be expected to know how a ViT and knowledge distillation work. The following are good resources in case you needed a refresher: * [ViT on keras.io](https://keras.io/examples/vision/image_classification_with_vision_transformer) * [Knowledge distillation on keras.io](https://keras.io/examples/vision/knowledge_distillation/) """ """ ## Imports """ import os os.environ["KERAS_BACKEND"] = "tensorflow" import tensorflow as tf import tensorflow_datasets as tfds import keras_core as keras from keras_core import layers tfds.disable_progress_bar() keras.utils.set_random_seed(42) """ ## Constants """ # Model MODEL_TYPE = "deit_distilled_tiny_patch16_224" RESOLUTION = 224 PATCH_SIZE = 16 NUM_PATCHES = (RESOLUTION // PATCH_SIZE) ** 2 LAYER_NORM_EPS = 1e-6 PROJECTION_DIM = 192 NUM_HEADS = 3 NUM_LAYERS = 12 MLP_UNITS = [ PROJECTION_DIM * 4, PROJECTION_DIM, ] DROPOUT_RATE = 0.0 DROP_PATH_RATE = 0.1 # Training NUM_EPOCHS = 20 BASE_LR = 0.0005 WEIGHT_DECAY = 0.0001 # Data BATCH_SIZE = 256 AUTO = tf.data.AUTOTUNE NUM_CLASSES = 5 """ You probably noticed that `DROPOUT_RATE` has been set 0.0. Dropout has been used in the implementation to keep it complete. For smaller models (like the one used in this example), you don't need it, but for bigger models, using dropout helps. """ """ ## Load the `tf_flowers` dataset and prepare preprocessing utilities The authors use an array of different augmentation techniques, including MixUp ([Zhang et al.](https://arxiv.org/abs/1710.09412)), RandAugment ([Cubuk et al.](https://arxiv.org/abs/1909.13719)), and so on. However, to keep the example simple to work through, we'll discard them. """ def preprocess_dataset(is_training=True): def fn(image, label): if is_training: # Resize to a bigger spatial resolution and take the random # crops. image = tf.image.resize(image, (RESOLUTION + 20, RESOLUTION + 20)) image = tf.image.random_crop(image, (RESOLUTION, RESOLUTION, 3)) image = tf.image.random_flip_left_right(image) else: image = tf.image.resize(image, (RESOLUTION, RESOLUTION)) label = tf.one_hot(label, depth=NUM_CLASSES) return image, label return fn def prepare_dataset(dataset, is_training=True): if is_training: dataset = dataset.shuffle(BATCH_SIZE * 10) dataset = dataset.map( preprocess_dataset(is_training), num_parallel_calls=AUTO ) return dataset.batch(BATCH_SIZE).prefetch(AUTO) train_dataset, val_dataset = tfds.load( "tf_flowers", split=["train[:90%]", "train[90%:]"], as_supervised=True ) num_train = train_dataset.cardinality() num_val = val_dataset.cardinality() print(f"Number of training examples: {num_train}") print(f"Number of validation examples: {num_val}") train_dataset = prepare_dataset(train_dataset, is_training=True) val_dataset = prepare_dataset(val_dataset, is_training=False) """ ## Implementing the DeiT variants of ViT Since DeiT is an extension of ViT it'd make sense to first implement ViT and then extend it to support DeiT's components. First, we'll implement a layer for Stochastic Depth ([Huang et al.](https://arxiv.org/abs/1603.09382)) which is used in DeiT for regularization. """ # Referred from: github.com:rwightman/pytorch-image-models. class StochasticDepth(layers.Layer): def __init__(self, drop_prop, **kwargs): super().__init__(**kwargs) self.drop_prob = drop_prop def call(self, x, training=True): if training: keep_prob = 1 - self.drop_prob shape = (tf.shape(x)[0],) + (1,) * (len(x.shape) - 1) random_tensor = keep_prob + tf.random.uniform(shape, 0, 1) random_tensor = tf.floor(random_tensor) return (x / keep_prob) * random_tensor return x """ Now, we'll implement the MLP and Transformer blocks. """ def mlp(x, dropout_rate: float, hidden_units): """FFN for a Transformer block.""" # Iterate over the hidden units and # add Dense => Dropout. for idx, units in enumerate(hidden_units): x = layers.Dense( units, activation=tf.nn.gelu if idx == 0 else None, )(x) x = layers.Dropout(dropout_rate)(x) return x def transformer(drop_prob: float, name: str) -> keras.Model: """Transformer block with pre-norm.""" num_patches = ( NUM_PATCHES + 2 if "distilled" in MODEL_TYPE else NUM_PATCHES + 1 ) encoded_patches = layers.Input((num_patches, PROJECTION_DIM)) # Layer normalization 1. x1 = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(encoded_patches) # Multi Head Self Attention layer 1. attention_output = layers.MultiHeadAttention( num_heads=NUM_HEADS, key_dim=PROJECTION_DIM, dropout=DROPOUT_RATE, )(x1, x1) attention_output = ( StochasticDepth(drop_prob)(attention_output) if drop_prob else attention_output ) # Skip connection 1. x2 = layers.Add()([attention_output, encoded_patches]) # Layer normalization 2. x3 = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(x2) # MLP layer 1. x4 = mlp(x3, hidden_units=MLP_UNITS, dropout_rate=DROPOUT_RATE) x4 = StochasticDepth(drop_prob)(x4) if drop_prob else x4 # Skip connection 2. outputs = layers.Add()([x2, x4]) return keras.Model(encoded_patches, outputs, name=name) """ We'll now implement a `ViTClassifier` class building on top of the components we just developed. Here we'll be following the original pooling strategy used in the ViT paper -- use a class token and use the feature representations corresponding to it for classification. """ class ViTClassifier(keras.Model): """Vision Transformer base class.""" def __init__(self, **kwargs): super().__init__(**kwargs) # Patchify + linear projection + reshaping. self.projection = keras.Sequential( [ layers.Conv2D( filters=PROJECTION_DIM, kernel_size=(PATCH_SIZE, PATCH_SIZE), strides=(PATCH_SIZE, PATCH_SIZE), padding="VALID", name="conv_projection", ), layers.Reshape( target_shape=(NUM_PATCHES, PROJECTION_DIM), name="flatten_projection", ), ], name="projection", ) # Positional embedding. init_shape = ( 1, NUM_PATCHES + 1, PROJECTION_DIM, ) self.positional_embedding = tf.Variable( tf.zeros(init_shape), name="pos_embedding" ) # Transformer blocks. dpr = [x for x in tf.linspace(0.0, DROP_PATH_RATE, NUM_LAYERS)] self.transformer_blocks = [ transformer(drop_prob=dpr[i], name=f"transformer_block_{i}") for i in range(NUM_LAYERS) ] # CLS token. initial_value = tf.zeros((1, 1, PROJECTION_DIM)) self.cls_token = tf.Variable( initial_value=initial_value, trainable=True, name="cls" ) # Other layers. self.dropout = layers.Dropout(DROPOUT_RATE) self.layer_norm = layers.LayerNormalization(epsilon=LAYER_NORM_EPS) self.head = layers.Dense( NUM_CLASSES, name="classification_head", ) def call(self, inputs): n = tf.shape(inputs)[0] # Create patches and project the patches. projected_patches = self.projection(inputs) # Append class token if needed. cls_token = tf.tile(self.cls_token, (n, 1, 1)) cls_token = tf.cast(cls_token, projected_patches.dtype) projected_patches = tf.concat([cls_token, projected_patches], axis=1) # Add positional embeddings to the projected patches. encoded_patches = ( self.positional_embedding + projected_patches ) # (B, number_patches, projection_dim) encoded_patches = self.dropout(encoded_patches) # Iterate over the number of layers and stack up blocks of # Transformer. for transformer_module in self.transformer_blocks: # Add a Transformer block. encoded_patches = transformer_module(encoded_patches) # Final layer normalization. representation = self.layer_norm(encoded_patches) # Pool representation. encoded_patches = representation[:, 0] # Classification head. output = self.head(encoded_patches) return output """ This class can be used standalone as ViT and is end-to-end trainable. Just remove the `distilled` phrase in `MODEL_TYPE` and it should work with `vit_tiny = ViTClassifier()`. Let's now extend it to DeiT. The following figure presents the schematic of DeiT (taken from the DeiT paper): ![](https://i.imgur.com/5lmg2Xs.png) Apart from the class token, DeiT has another token for distillation. During distillation, the logits corresponding to the class token are compared to the true labels, and the logits corresponding to the distillation token are compared to the teacher's predictions. """ class ViTDistilled(ViTClassifier): def __init__(self, regular_training=False, **kwargs): super().__init__(**kwargs) self.num_tokens = 2 self.regular_training = regular_training # CLS and distillation tokens, positional embedding. init_value = tf.zeros((1, 1, PROJECTION_DIM)) self.dist_token = tf.Variable(init_value, name="dist_token") self.positional_embedding = tf.Variable( tf.zeros( ( 1, NUM_PATCHES + self.num_tokens, PROJECTION_DIM, ) ), name="pos_embedding", ) # Head layers. self.head = layers.Dense( NUM_CLASSES, name="classification_head", ) self.head_dist = layers.Dense( NUM_CLASSES, name="distillation_head", ) def call(self, inputs, training=False): n = tf.shape(inputs)[0] # Create patches and project the patches. projected_patches = self.projection(inputs) # Append the tokens. cls_token = tf.tile(self.cls_token, (n, 1, 1)) dist_token = tf.tile(self.dist_token, (n, 1, 1)) cls_token = tf.cast(cls_token, projected_patches.dtype) dist_token = tf.cast(dist_token, projected_patches.dtype) projected_patches = tf.concat( [cls_token, dist_token, projected_patches], axis=1 ) # Add positional embeddings to the projected patches. encoded_patches = ( self.positional_embedding + projected_patches ) # (B, number_patches, projection_dim) encoded_patches = self.dropout(encoded_patches) # Iterate over the number of layers and stack up blocks of # Transformer. for transformer_module in self.transformer_blocks: # Add a Transformer block. encoded_patches = transformer_module(encoded_patches) # Final layer normalization. representation = self.layer_norm(encoded_patches) # Classification heads. x, x_dist = ( self.head(representation[:, 0]), self.head_dist(representation[:, 1]), ) if not training or self.regular_training: # During standard train / finetune, inference average the classifier # predictions. return (x + x_dist) / 2 elif training: # Only return separate classification predictions when training in distilled # mode. return x, x_dist """ Let's verify if the `ViTDistilled` class can be initialized and called as expected. """ deit_tiny_distilled = ViTDistilled() dummy_inputs = tf.ones((2, 224, 224, 3)) outputs = deit_tiny_distilled(dummy_inputs, training=False) print(f"output_shape: {outputs.shape}") """ ## Implementing the trainer Unlike what happens in standard knowledge distillation ([Hinton et al.](https://arxiv.org/abs/1503.02531)), where a temperature-scaled softmax is used as well as KL divergence, DeiT authors use the following loss function: ![](https://i.imgur.com/bXdxsBq.png) Here, * CE is cross-entropy * `psi` is the softmax function * Z_s denotes student predictions * y denotes true labels * y_t denotes teacher predictions """ class DeiT(keras.Model): # Reference: # https://keras.io/examples/vision/knowledge_distillation/ def __init__(self, student, teacher, **kwargs): super().__init__(**kwargs) self.student = student self.teacher = teacher self.student_loss_tracker = keras.metrics.Mean(name="student_loss") self.distillation_loss_tracker = keras.metrics.Mean( name="distillation_loss" ) self.accuracy = keras.metrics.CategoricalAccuracy(name="accuracy") @property def metrics(self): return [ self.accuracy, self.student_loss_tracker, self.distillation_loss_tracker, ] def compile( self, optimizer, student_loss_fn, distillation_loss_fn, run_eagerly=False, jit_compile=False, ): super().compile( optimizer=optimizer, run_eagerly=run_eagerly, jit_compile=jit_compile, ) self.student_loss_fn = student_loss_fn self.distillation_loss_fn = distillation_loss_fn def train_step(self, data): # Unpack data. x, y = data # Forward pass of teacher teacher_predictions = self.teacher(x)["dense"] teacher_predictions = tf.nn.softmax(teacher_predictions, axis=-1) with tf.GradientTape() as tape: # Forward pass of student. cls_predictions, dist_predictions = self.student( x / 255.0, training=True ) # Compute losses. student_loss = self.student_loss_fn(y, cls_predictions) distillation_loss = self.distillation_loss_fn( teacher_predictions, dist_predictions ) loss = (student_loss + distillation_loss) / 2 # Compute gradients. trainable_vars = self.student.trainable_variables gradients = tape.gradient(loss, trainable_vars) # Update weights. self.optimizer.apply_gradients(zip(gradients, trainable_vars)) # Update the metrics configured in `compile()`. student_predictions = (cls_predictions + dist_predictions) / 2 self.student_loss_tracker.update_state(student_loss) self.distillation_loss_tracker.update_state(distillation_loss) self.accuracy.update_state(y, student_predictions) # Return a dict of performance. return {m.name: m.result() for m in self.metrics} def test_step(self, data): # Unpack the data. x, y = data # Compute predictions. y_prediction = self.student(x / 255.0) # Calculate the loss. student_loss = self.student_loss_fn(y, y_prediction) # Update the metrics. self.student_loss_tracker.update_state(student_loss) self.accuracy.update_state(y, y_prediction) # Return a dict of performance. results = {m.name: m.result() for m in self.metrics} return results def call(self, inputs): return self.student(inputs / 255.0) """ ## Load the teacher model This model is based on the BiT family of ResNets ([Kolesnikov et al.](https://arxiv.org/abs/1912.11370)) fine-tuned on the `tf_flowers` dataset. You can refer to [this notebook](https://github.com/sayakpaul/deit-tf/blob/main/notebooks/bit-teacher.ipynb) to know how the training was performed. The teacher model has about 212 Million parameters which is about **40x more** than the student. """ """shell wget -q https://github.com/sayakpaul/deit-tf/releases/download/v0.1.0/bit_teacher_flowers.zip unzip -q bit_teacher_flowers.zip """ bit_teacher_flowers = keras.layers.TFSMLayer( filepath="bit_teacher_flowers", call_endpoint="serving_default", ) """ ## Training through distillation """ deit_tiny = ViTDistilled() deit_distiller = DeiT(student=deit_tiny, teacher=bit_teacher_flowers) lr_scaled = (BASE_LR / 512) * BATCH_SIZE deit_distiller.compile( optimizer=keras.optimizers.AdamW( weight_decay=WEIGHT_DECAY, learning_rate=lr_scaled ), student_loss_fn=keras.losses.CategoricalCrossentropy( from_logits=True, label_smoothing=0.1 ), distillation_loss_fn=keras.losses.CategoricalCrossentropy(from_logits=True), ) _ = deit_distiller.fit( train_dataset, validation_data=val_dataset, epochs=NUM_EPOCHS ) """ If we had trained the same model (the `ViTClassifier`) from scratch with the exact same hyperparameters, the model would have scored about 59% accuracy. You can adapt the following code to reproduce this result: ``` vit_tiny = ViTClassifier() inputs = keras.Input((RESOLUTION, RESOLUTION, 3)) x = keras.layers.Rescaling(scale=1./255)(inputs) outputs = deit_tiny(x) model = keras.Model(inputs, outputs) model.compile(...) model.fit(...) ``` """ """ ## Notes * Through the use of distillation, we're effectively transferring the inductive biases of a CNN-based teacher model. * Interestingly enough, this distillation strategy works better with a CNN as the teacher model rather than a Transformer as shown in the paper. * The use of regularization to train DeiT models is very important. * ViT models are initialized with a combination of different initializers including truncated normal, random normal, Glorot uniform, etc. If you're looking for end-to-end reproduction of the original results, don't forget to initialize the ViTs well. * If you want to explore the pre-trained DeiT models in TensorFlow and Keras with code for fine-tuning, [check out these models on TF-Hub](https://tfhub.dev/sayakpaul/collections/deit/1). ## Acknowledgements * Ross Wightman for keeping [`timm`](https://github.com/rwightman/pytorch-image-models) updated with readable implementations. I referred to the implementations of ViT and DeiT a lot during implementing them in TensorFlow. * [Aritra Roy Gosthipaty](https://github.com/ariG23498) who implemented some portions of the `ViTClassifier` in another project. * [Google Developers Experts](https://developers.google.com/programs/experts/) program for supporting me with GCP credits which were used to run experiments for this example. """
keras-core/examples/keras_io/tensorflow/vision/deit.py/0
{ "file_path": "keras-core/examples/keras_io/tensorflow/vision/deit.py", "repo_id": "keras-core", "token_count": 8170 }
25
""" Title: Visualizing what convnets learn Author: [fchollet](https://twitter.com/fchollet) Date created: 2020/05/29 Last modified: 2020/05/29 Description: Displaying the visual patterns that convnet filters respond to. Accelerator: GPU """ """ ## Introduction In this example, we look into what sort of visual patterns image classification models learn. We'll be using the `ResNet50V2` model, trained on the ImageNet dataset. Our process is simple: we will create input images that maximize the activation of specific filters in a target layer (picked somewhere in the middle of the model: layer `conv3_block4_out`). Such images represent a visualization of the pattern that the filter responds to. """ """ ## Setup """ import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras_core as keras import numpy as np import tensorflow as tf # The dimensions of our input image img_width = 180 img_height = 180 # Our target layer: we will visualize the filters from this layer. # See `model.summary()` for list of layer names, if you want to change this. layer_name = "conv3_block4_out" """ ## Build a feature extraction model """ # Build a ResNet50V2 model loaded with pre-trained ImageNet weights model = keras.applications.ResNet50V2(weights="imagenet", include_top=False) # Set up a model that returns the activation values for our target layer layer = model.get_layer(name=layer_name) feature_extractor = keras.Model(inputs=model.inputs, outputs=layer.output) """ ## Set up the gradient ascent process The "loss" we will maximize is simply the mean of the activation of a specific filter in our target layer. To avoid border effects, we exclude border pixels. """ def compute_loss(input_image, filter_index): activation = feature_extractor(input_image) # We avoid border artifacts by only involving non-border pixels in the loss. filter_activation = activation[:, 2:-2, 2:-2, filter_index] return tf.reduce_mean(filter_activation) """ Our gradient ascent function simply computes the gradients of the loss above with regard to the input image, and update the update image so as to move it towards a state that will activate the target filter more strongly. """ @tf.function def gradient_ascent_step(img, filter_index, learning_rate): with tf.GradientTape() as tape: tape.watch(img) loss = compute_loss(img, filter_index) # Compute gradients. grads = tape.gradient(loss, img) # Normalize gradients. grads = tf.math.l2_normalize(grads) img += learning_rate * grads return loss, img """ ## Set up the end-to-end filter visualization loop Our process is as follow: - Start from a random image that is close to "all gray" (i.e. visually netural) - Repeatedly apply the gradient ascent step function defined above - Convert the resulting input image back to a displayable form, by normalizing it, center-cropping it, and restricting it to the [0, 255] range. """ def initialize_image(): # We start from a gray image with some random noise img = tf.random.uniform((1, img_width, img_height, 3)) # ResNet50V2 expects inputs in the range [-1, +1]. # Here we scale our random inputs to [-0.125, +0.125] return (img - 0.5) * 0.25 def visualize_filter(filter_index): # We run gradient ascent for 20 steps iterations = 30 learning_rate = 10.0 img = initialize_image() for iteration in range(iterations): loss, img = gradient_ascent_step(img, filter_index, learning_rate) # Decode the resulting input image img = deprocess_image(img[0].numpy()) return loss, img def deprocess_image(img): # Normalize array: center on 0., ensure variance is 0.15 img -= img.mean() img /= img.std() + 1e-5 img *= 0.15 # Center crop img = img[25:-25, 25:-25, :] # Clip to [0, 1] img += 0.5 img = np.clip(img, 0, 1) # Convert to RGB array img *= 255 img = np.clip(img, 0, 255).astype("uint8") return img """ Let's try it out with filter 0 in the target layer: """ from IPython.display import Image, display loss, img = visualize_filter(0) keras.utils.save_img("0.png", img) """ This is what an input that maximizes the response of filter 0 in the target layer would look like: """ display(Image("0.png")) """ ## Visualize the first 64 filters in the target layer Now, let's make a 8x8 grid of the first 64 filters in the target layer to get of feel for the range of different visual patterns that the model has learned. """ # Compute image inputs that maximize per-filter activations # for the first 64 filters of our target layer all_imgs = [] for filter_index in range(64): print("Processing filter %d" % (filter_index,)) loss, img = visualize_filter(filter_index) all_imgs.append(img) # Build a black picture with enough space for # our 8 x 8 filters of size 128 x 128, with a 5px margin in between margin = 5 n = 8 cropped_width = img_width - 25 * 2 cropped_height = img_height - 25 * 2 width = n * cropped_width + (n - 1) * margin height = n * cropped_height + (n - 1) * margin stitched_filters = np.zeros((width, height, 3)) # Fill the picture with our saved filters for i in range(n): for j in range(n): img = all_imgs[i * n + j] stitched_filters[ (cropped_width + margin) * i : (cropped_width + margin) * i + cropped_width, (cropped_height + margin) * j : (cropped_height + margin) * j + cropped_height, :, ] = img keras.utils.save_img("stiched_filters.png", stitched_filters) from IPython.display import Image, display display(Image("stiched_filters.png")) """ Image classification models see the world by decomposing their inputs over a "vector basis" of texture filters such as these. See also [this old blog post](https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html) for analysis and interpretation. Example available on HuggingFace. [![Generic badge](https://img.shields.io/badge/🤗%20Spaces-What%20Convnets%20Learn-black.svg)](https://huggingface.co/spaces/keras-io/what-convnets-learn) """
keras-core/examples/keras_io/tensorflow/vision/visualizing_what_convnets_learn.py/0
{ "file_path": "keras-core/examples/keras_io/tensorflow/vision/visualizing_what_convnets_learn.py", "repo_id": "keras-core", "token_count": 2013 }
26
""" Title: Learning to Resize in Computer Vision Author: [Sayak Paul](https://twitter.com/RisingSayak) Date created: 2021/04/30 Last modified: 2023/07/26 Description: How to optimally learn representations of images for a given resolution. Accelerator: GPU """ """ It is a common belief that if we constrain vision models to perceive things as humans do, their performance can be improved. For example, in [this work](https://arxiv.org/abs/1811.12231), Geirhos et al. showed that the vision models pre-trained on the ImageNet-1k dataset are biased towards texture, whereas human beings mostly use the shape descriptor to develop a common perception. But does this belief always apply, especially when it comes to improving the performance of vision models? It turns out it may not always be the case. When training vision models, it is common to resize images to a lower dimension ((224 x 224), (299 x 299), etc.) to allow mini-batch learning and also to keep up the compute limitations. We generally make use of image resizing methods like **bilinear interpolation** for this step and the resized images do not lose much of their perceptual character to the human eyes. In [Learning to Resize Images for Computer Vision Tasks](https://arxiv.org/abs/2103.09950v1), Talebi et al. show that if we try to optimize the perceptual quality of the images for the vision models rather than the human eyes, their performance can further be improved. They investigate the following question: **For a given image resolution and a model, how to best resize the given images?** As shown in the paper, this idea helps to consistently improve the performance of the common vision models (pre-trained on ImageNet-1k) like DenseNet-121, ResNet-50, MobileNetV2, and EfficientNets. In this example, we will implement the learnable image resizing module as proposed in the paper and demonstrate that on the [Cats and Dogs dataset](https://www.microsoft.com/en-us/download/details.aspx?id=54765) using the [DenseNet-121](https://arxiv.org/abs/1608.06993) architecture. """ """ ## Setup """ from keras_core import layers import keras_core as keras from keras_core import ops from tensorflow import data as tf_data from tensorflow import image as tf_image from tensorflow import one_hot as tf_one_hot import tensorflow_datasets as tfds tfds.disable_progress_bar() import matplotlib.pyplot as plt import numpy as np """ ## Define hyperparameters """ """ In order to facilitate mini-batch learning, we need to have a fixed shape for the images inside a given batch. This is why an initial resizing is required. We first resize all the images to (300 x 300) shape and then learn their optimal representation for the (150 x 150) resolution. """ INP_SIZE = (300, 300) TARGET_SIZE = (150, 150) INTERPOLATION = "bilinear" AUTO = tf_data.AUTOTUNE BATCH_SIZE = 50 EPOCHS = 5 """ In this example, we will use the bilinear interpolation but the learnable image resizer module is not dependent on any specific interpolation method. We can also use others, such as bicubic. """ """ ## Load and prepare the dataset For this example, we will only use 40% of the total training dataset. """ train_ds, validation_ds = tfds.load( "cats_vs_dogs", # Reserve 10% for validation split=["train[:40%]", "train[40%:50%]"], as_supervised=True, ) def preprocess_dataset(image, label): image = tf_image.resize(image, (INP_SIZE[0], INP_SIZE[1])) label = tf_one_hot(label, depth=2) return (image, label) train_ds = ( train_ds.shuffle(BATCH_SIZE * 100) .map(preprocess_dataset, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) validation_ds = ( validation_ds.map(preprocess_dataset, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) """ ## Define the learnable resizer utilities The figure below (courtesy: [Learning to Resize Images for Computer Vision Tasks](https://arxiv.org/abs/2103.09950v1)) presents the structure of the learnable resizing module: ![](https://i.ibb.co/gJYtSs0/image.png) """ def conv_block( x, filters, kernel_size, strides, activation=layers.LeakyReLU(0.2) ): x = layers.Conv2D( filters, kernel_size, strides, padding="same", use_bias=False )(x) x = layers.BatchNormalization()(x) if activation: x = activation(x) return x def res_block(x): inputs = x x = conv_block(x, 16, 3, 1) x = conv_block(x, 16, 3, 1, activation=None) return layers.Add()([inputs, x]) def get_learnable_resizer( filters=16, num_res_blocks=1, interpolation=INTERPOLATION ): inputs = layers.Input(shape=[None, None, 3]) # First, perform naive resizing. naive_resize = layers.Resizing(*TARGET_SIZE, interpolation=interpolation)( inputs ) # First convolution block without batch normalization. x = layers.Conv2D( filters=filters, kernel_size=7, strides=1, padding="same" )(inputs) x = layers.LeakyReLU(0.2)(x) # Second convolution block with batch normalization. x = layers.Conv2D( filters=filters, kernel_size=1, strides=1, padding="same" )(x) x = layers.LeakyReLU(0.2)(x) x = layers.BatchNormalization()(x) # Intermediate resizing as a bottleneck. bottleneck = layers.Resizing(*TARGET_SIZE, interpolation=interpolation)(x) # Residual passes. for _ in range(num_res_blocks): x = res_block(bottleneck) # Projection. x = layers.Conv2D( filters=filters, kernel_size=3, strides=1, padding="same", use_bias=False, )(x) x = layers.BatchNormalization()(x) # Skip connection. x = layers.Add()([bottleneck, x]) # Final resized image. x = layers.Conv2D(filters=3, kernel_size=7, strides=1, padding="same")(x) final_resize = layers.Add()([naive_resize, x]) return keras.Model(inputs, final_resize, name="learnable_resizer") learnable_resizer = get_learnable_resizer() """ ## Visualize the outputs of the learnable resizing module Here, we visualize how the resized images would look like after being passed through the random weights of the resizer. """ sample_images, _ = next(iter(train_ds)) get_np = lambda image: ops.convert_to_numpy( ops.squeeze(image) ) # Helper to convert image from any backend to numpy plt.figure(figsize=(16, 10)) for i, image in enumerate(sample_images[:6]): image = image / 255 ax = plt.subplot(3, 4, 2 * i + 1) plt.title("Input Image") plt.imshow(image.numpy().squeeze()) plt.axis("off") ax = plt.subplot(3, 4, 2 * i + 2) resized_image = learnable_resizer(image[None, ...]) plt.title("Resized Image") plt.imshow(get_np(resized_image)) plt.axis("off") """ ## Model building utility """ def get_model(): backbone = keras.applications.DenseNet121( weights=None, include_top=True, classes=2, input_shape=((TARGET_SIZE[0], TARGET_SIZE[1], 3)), ) backbone.trainable = True inputs = layers.Input((INP_SIZE[0], INP_SIZE[1], 3)) x = layers.Rescaling(scale=1.0 / 255)(inputs) x = learnable_resizer(x) outputs = backbone(x) return keras.Model(inputs, outputs) """ The structure of the learnable image resizer module allows for flexible integrations with different vision models. """ """ ## Compile and train our model with learnable resizer """ model = get_model() model.compile( loss=keras.losses.CategoricalCrossentropy(label_smoothing=0.1), optimizer="sgd", metrics=["accuracy"], ) model.fit(train_ds, validation_data=validation_ds, epochs=EPOCHS) """ ## Visualize the outputs of the trained visualizer """ plt.figure(figsize=(16, 10)) for i, image in enumerate(sample_images[:6]): image = image / 255 ax = plt.subplot(3, 4, 2 * i + 1) plt.title("Input Image") plt.imshow(image.numpy().squeeze()) plt.axis("off") ax = plt.subplot(3, 4, 2 * i + 2) resized_image = learnable_resizer(image[None, ...]) plt.title("Resized Image") plt.imshow(get_np(resized_image) / 10) plt.axis("off") """ The plot shows that the visuals of the images have improved with training. The following table shows the benefits of using the resizing module in comparison to using the bilinear interpolation: | Model | Number of parameters (Million) | Top-1 accuracy | |:-------------------------: |:-------------------------------: |:--------------: | | With the learnable resizer | 7.051717 | 67.67% | | Without the learnable resizer | 7.039554 | 60.19% | For more details, you can check out [this repository](https://github.com/sayakpaul/Learnable-Image-Resizing). Note the above-reported models were trained for 10 epochs on 90% of the training set of Cats and Dogs unlike this example. Also, note that the increase in the number of parameters due to the resizing module is very negligible. To ensure that the improvement in the performance is not due to stochasticity, the models were trained using the same initial random weights. Now, a question worth asking here is - _isn't the improved accuracy simply a consequence of adding more layers (the resizer is a mini network after all) to the model, compared to the baseline?_ To show that it is not the case, the authors conduct the following experiment: * Take a pre-trained model trained some size, say (224 x 224). * Now, first, use it to infer predictions on images resized to a lower resolution. Record the performance. * For the second experiment, plug in the resizer module at the top of the pre-trained model and warm-start the training. Record the performance. Now, the authors argue that using the second option is better because it helps the model learn how to adjust the representations better with respect to the given resolution. Since the results purely are empirical, a few more experiments such as analyzing the cross-channel interaction would have been even better. It is worth noting that elements like [Squeeze and Excitation (SE) blocks](https://arxiv.org/abs/1709.01507), [Global Context (GC) blocks](https://arxiv.org/pdf/1904.11492) also add a few parameters to an existing network but they are known to help a network process information in systematic ways to improve the overall performance. """ """ ## Notes * To impose shape bias inside the vision models, Geirhos et al. trained them with a combination of natural and stylized images. It might be interesting to investigate if this learnable resizing module could achieve something similar as the outputs seem to discard the texture information. * The resizer module can handle arbitrary resolutions and aspect ratios which is very important for tasks like object detection and segmentation. * There is another closely related topic on ***adaptive image resizing*** that attempts to resize images/feature maps adaptively during training. [EfficientV2](https://arxiv.org/pdf/2104.00298) uses this idea. """
keras-core/examples/keras_io/vision/learnable_resizer.py/0
{ "file_path": "keras-core/examples/keras_io/vision/learnable_resizer.py", "repo_id": "keras-core", "token_count": 3701 }
27
import numpy as np from keras_core import activations from keras_core import backend from keras_core import testing def _ref_softmax(values): m = np.max(values) e = np.exp(values - m) return e / np.sum(e) def _ref_softplus(x): return np.log(np.ones_like(x) + np.exp(x)) def _ref_log_softmax(values): max_val = np.max(values) # for numerical stability stabilized_values = values - max_val log_sum_exp = np.log(np.sum(np.exp(stabilized_values))) return stabilized_values - log_sum_exp def _ref_leaky_relu(x, alpha=0.2): return x if x > 0 else alpha * x def _ref_relu6(x): return min(max(0, x), 6) def _ref_silu(x): return x / (1 + np.exp(-x)) def _ref_hard_sigmoid(x): x = (x / 6.0) + 0.5 z = 0.0 if x <= 0 else (1.0 if x >= 1 else x) return z def _ref_sigmoid(x): if x >= 0: return 1 / (1 + np.exp(-x)) else: z = np.exp(x) return z / (1 + z) def _ref_softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) class ActivationsTest(testing.TestCase): def test_softmax(self): x = np.random.random((2, 5)) result = activations.softmax(x[np.newaxis, :])[0] expected = _ref_softmax(x[0]) self.assertAllClose(result[0], expected, rtol=1e-05) def test_softmax_2d_axis_0(self): x = np.random.random((2, 5)) result = activations.softmax(x[np.newaxis, :], axis=1)[0] expected = np.zeros((2, 5)) for i in range(5): expected[:, i] = _ref_softmax(x[:, i]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_3d_axis_tuple(self): x = np.random.random((2, 3, 5)) result = activations.softmax(x, axis=(1, 2)) expected = np.zeros((2, 3, 5)) for i in range(2): expected[i, :, :] = _ref_softmax(x[i, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_1d(self): x = np.random.random(5) result = activations.softmax(x) expected = _ref_softmax(x) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_higher_dim(self): x = np.random.random((2, 3, 4, 5)) result = activations.softmax(x, axis=(2, 3)) expected = np.zeros((2, 3, 4, 5)) for i in range(2): for j in range(3): expected[i, j, :, :] = _ref_softmax(x[i, j, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_higher_dim_multiple_axes(self): x = np.random.random((2, 3, 4, 5, 6)) result = activations.softmax(x, axis=(2, 3, 4)) expected = np.zeros((2, 3, 4, 5, 6)) for i in range(2): for j in range(3): expected[i, j, :, :, :] = _ref_softmax(x[i, j, :, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_negative_axis(self): x = np.random.random((2, 5)) result = activations.softmax(x, axis=-1) expected = np.zeros((2, 5)) for i in range(2): expected[i, :] = _ref_softmax(x[i, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_temporal_softmax(self): x = np.random.random((2, 2, 3)) * 10 result = activations.softmax(x[np.newaxis, :])[0] expected = _ref_softmax(x[0, 0]) self.assertAllClose(result[0, 0], expected, rtol=1e-05) def test_log_softmax_2d_axis_0(self): x = np.random.random((2, 5)) result = activations.log_softmax(x[np.newaxis, :], axis=1)[0] expected = np.zeros((2, 5)) for i in range(5): expected[:, i] = _ref_log_softmax(x[:, i]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_3d_axis_tuple(self): x = np.random.random((2, 3, 5)) result = activations.log_softmax(x, axis=(1, 2)) expected = np.zeros((2, 3, 5)) for i in range(2): expected[i, :, :] = _ref_log_softmax(x[i, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_1d(self): x = np.random.random(5) result = activations.log_softmax(x) expected = _ref_log_softmax(x) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_higher_dim(self): x = np.random.random((2, 3, 4, 5)) result = activations.log_softmax(x, axis=(2, 3)) expected = np.zeros((2, 3, 4, 5)) for i in range(2): for j in range(3): expected[i, j, :, :] = _ref_log_softmax(x[i, j, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_higher_dim_multiple_axes(self): x = np.random.random((2, 3, 4, 5, 6)) result = activations.log_softmax(x, axis=(2, 3, 4)) expected = np.zeros((2, 3, 4, 5, 6)) for i in range(2): for j in range(3): expected[i, j, :, :, :] = _ref_log_softmax(x[i, j, :, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_negative_axis(self): x = np.random.random((2, 5)) result = activations.log_softmax(x, axis=-1) expected = np.zeros((2, 5)) for i in range(2): expected[i, :] = _ref_log_softmax(x[i, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_temporal_log_softmax(self): x = np.random.random((2, 2, 3)) * 10 result = activations.log_softmax(x[np.newaxis, :])[0] expected = _ref_log_softmax(x[0, 0]) self.assertAllClose(result[0, 0], expected, rtol=1e-05) def test_selu(self): alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 positive_values = np.array([[1, 2]], dtype=backend.floatx()) result = activations.selu(positive_values[np.newaxis, :])[0] self.assertAllClose(result, positive_values * scale, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=backend.floatx()) result = activations.selu(negative_values[np.newaxis, :])[0] true_result = (np.exp(negative_values) - 1) * scale * alpha self.assertAllClose(result, true_result) def test_softplus(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.softplus(x[np.newaxis, :])[0] expected = np.vectorize(_ref_softplus)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.softplus(x_1d) expected_1d = np.vectorize(_ref_softplus)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.softplus(x_3d) expected_3d = np.vectorize(_ref_softplus)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.softplus(x_zero) expected_zero = np.vectorize(_ref_softplus)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.softplus(x_large_positive) expected_large_positive = np.vectorize(_ref_softplus)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.softplus(x_large_negative) expected_large_negative = np.vectorize(_ref_softplus)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_softsign(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.softsign(x[np.newaxis, :])[0] expected = np.vectorize(_ref_softsign)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.softsign(x_1d) expected_1d = np.vectorize(_ref_softsign)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.softsign(x_3d) expected_3d = np.vectorize(_ref_softsign)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.softsign(x_zero) expected_zero = np.vectorize(_ref_softsign)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.softsign(x_large_positive) expected_large_positive = np.vectorize(_ref_softsign)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.softsign(x_large_negative) expected_large_negative = np.vectorize(_ref_softsign)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.sigmoid(x_1d) expected_1d = np.vectorize(_ref_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.sigmoid(x_3d) expected_3d = np.vectorize(_ref_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.sigmoid(x_zero) expected_zero = np.vectorize(_ref_sigmoid)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.sigmoid(x_large_positive) expected_large_positive = np.vectorize(_ref_sigmoid)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.sigmoid(x_large_negative) expected_large_negative = np.vectorize(_ref_sigmoid)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_hard_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.hard_sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_hard_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.hard_sigmoid(x_1d) expected_1d = np.vectorize(_ref_hard_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.hard_sigmoid(x_3d) expected_3d = np.vectorize(_ref_hard_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values much larger than 1 x_positive_above_1 = np.random.uniform( 5, 10, (2, 5) ) # Adjusted this range result_positive_above_1 = activations.hard_sigmoid(x_positive_above_1) expected_positive_above_1 = np.ones((2, 5)) self.assertAllClose( result_positive_above_1, expected_positive_above_1, rtol=1e-05 ) def test_relu_negative_slope(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only negative_slope result_negative_slope = activations.relu(x, negative_slope=0.5) expected_negative_slope = np.array([-5.0, -2.5, 0.0, 5.0, 10.0]) self.assertAllClose( result_negative_slope, expected_negative_slope, rtol=1e-05 ) def test_relu_max_value(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only max_value result_max_value = activations.relu(x, max_value=5.0) expected_max_value = np.array([0.0, 0.0, 0.0, 5.0, 5.0]) self.assertAllClose(result_max_value, expected_max_value, rtol=1e-05) def test_relu_threshold(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only threshold result_threshold = activations.relu(x, threshold=5.0) expected_threshold = np.array([-0.0, -0.0, 0.0, 0.0, 10.0]) self.assertAllClose(result_threshold, expected_threshold, rtol=1e-05) def test_relu_combined_threshold_and_max_value(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with threshold and max_value result_combined = activations.relu(x, threshold=5.0, max_value=5.0) expected_combined = np.array([0.0, 0.0, 0.0, 0.0, 5.0]) self.assertAllClose(result_combined, expected_combined, rtol=1e-05) def test_relu_combined_all_parameters(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with negative_slope, max_value, and threshold result_combined = activations.relu( x, negative_slope=0.5, max_value=5.0, threshold=5.0 ) expected_combined = np.array([-7.5, -5.0, -2.5, 0.0, 5.0]) self.assertAllClose(result_combined, expected_combined, rtol=1e-05) def test_relu_to_trigger_relu6(self): x = np.array([-10, -5, 0.0, 5, 10, 12]) result_relu6 = activations.relu(x, max_value=6.0) expected_relu6 = np.array([0.0, 0.0, 0.0, 5.0, 6.0, 6.0]) self.assertAllClose(result_relu6, expected_relu6, rtol=1e-05) def test_relu_to_trigger_leaky(self): x = np.array([-10, -5, 0.0, 5, 10]) result_leaky = activations.relu(x, negative_slope=0.5) expected_leaky = np.array([-5.0, -2.5, 0.0, 5.0, 10.0]) self.assertAllClose(result_leaky, expected_leaky, rtol=1e-05) def test_relu(self): # Basic test for positive values positive_values = np.random.uniform(0.1, 10, (2, 5)) result = activations.relu(positive_values[np.newaxis, :])[0] self.assertAllClose(result, positive_values, rtol=1e-05) # Basic test for negative values negative_values = np.random.uniform(-10, -0.1, (2, 5)) result = activations.relu(negative_values[np.newaxis, :])[0] expected = np.zeros((2, 5)) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.relu(x_1d) expected_1d = np.maximum(0, x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.relu(x_3d) expected_3d = np.maximum(0, x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.relu(x_zero) expected_zero = np.maximum(0, x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(1e4, 1e5, (2, 5)) result_large_positive = activations.relu(x_large_positive) self.assertAllClose(result_large_positive, x_large_positive, rtol=1e-05) # Test large negative values x_large_negative = np.random.uniform(-1e5, -1e4, (2, 5)) result_large_negative = activations.relu(x_large_negative) expected_large_negative = np.zeros((2, 5)) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_leaky_relu(self): leaky_relu_vectorized = np.vectorize(_ref_leaky_relu) # Test for negative_slope = 0.01 # Test positive values positive_values = np.random.random((2, 5)) result = activations.leaky_relu( positive_values[np.newaxis, :], negative_slope=0.01 )[0] expected = leaky_relu_vectorized(positive_values, alpha=0.01) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.leaky_relu( negative_values[np.newaxis, :], negative_slope=0.01 )[0] expected = leaky_relu_vectorized(negative_values, alpha=0.01) self.assertAllClose(result, expected, rtol=1e-05) # Test for negative_slope = 0.3 # Test positive values positive_values = np.random.random((2, 5)) result = activations.leaky_relu( positive_values[np.newaxis, :], negative_slope=0.3 )[0] expected = leaky_relu_vectorized(positive_values, alpha=0.3) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.leaky_relu( negative_values[np.newaxis, :], negative_slope=0.3 )[0] expected = leaky_relu_vectorized(negative_values, alpha=0.3) self.assertAllClose(result, expected, rtol=1e-05) def test_relu6(self): relu6_vectorized = np.vectorize(_ref_relu6) # Test positive values less than 6 positive_values = np.random.uniform(0, 5.9, (2, 5)) result = activations.relu6(positive_values[np.newaxis, :])[0] expected = relu6_vectorized(positive_values) self.assertAllClose(result, expected, rtol=1e-05) # Test positive values greater than 6 positive_values_above_6 = np.random.uniform(6.1, 10, (2, 5)) result = activations.relu6(positive_values_above_6[np.newaxis, :])[0] expected = relu6_vectorized(positive_values_above_6) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.relu6(negative_values[np.newaxis, :])[0] expected = relu6_vectorized(negative_values) self.assertAllClose(result, expected, rtol=1e-05) def test_silu(self): silu_vectorized = np.vectorize(_ref_silu) # Test positive values positive_values = np.random.uniform(0, 5.9, (2, 5)) result = activations.silu(positive_values[np.newaxis, :])[0] expected = silu_vectorized(positive_values) self.assertAllClose(result, expected, rtol=1e-05) # Test values around zero (to ensure sigmoid behaves correctly) around_zero_values = np.random.uniform(-1, 1, (2, 5)) result = activations.silu(around_zero_values[np.newaxis, :])[0] expected = silu_vectorized(around_zero_values) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-5.9, 0, (2, 5)) result = activations.silu(negative_values[np.newaxis, :])[0] expected = silu_vectorized(negative_values) self.assertAllClose(result, expected, rtol=1e-05) def test_gelu(self): def gelu(x, approximate=False): if approximate: return ( 0.5 * x * ( 1.0 + np.tanh( np.sqrt(2.0 / np.pi) * (x + 0.044715 * np.power(x, 3)) ) ) ) else: from scipy.stats import norm return x * norm.cdf(x) x = np.random.random((2, 5)) result = activations.gelu(x[np.newaxis, :])[0] expected = gelu(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.random((2, 5)) result = activations.gelu(x[np.newaxis, :], approximate=True)[0] expected = gelu(x, True) self.assertAllClose(result, expected, rtol=1e-05) def test_elu(self): x = np.random.random((2, 5)) result = activations.elu(x[np.newaxis, :])[0] self.assertAllClose(result, x, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=backend.floatx()) result = activations.elu(negative_values[np.newaxis, :])[0] true_result = np.exp(negative_values) - 1 self.assertAllClose(result, true_result) def test_tanh(self): # Basic test for the tanh activation function x = np.random.random((2, 5)) result = activations.tanh(x[np.newaxis, :])[0] expected = np.tanh(x) self.assertAllClose(result, expected, rtol=1e-05) # Basic test for the tanh activation function x = np.random.uniform(-10, 10, (2, 5)) result = activations.tanh(x[np.newaxis, :])[0] expected = np.tanh(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.tanh(x_1d) expected_1d = np.tanh(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.tanh(x_3d) expected_3d = np.tanh(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.tanh(x_positive) expected_positive = np.tanh(x_positive) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.tanh(x_negative) expected_negative = np.tanh(x_negative) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.tanh(x_zero) expected_zero = np.tanh(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.tanh(x_large) expected_large = np.tanh(x_large) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_exponential(self): # Basic test for the exponential activation function x = np.random.random((2, 5)) result = activations.exponential(x[np.newaxis, :])[0] expected = np.exp(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.uniform(-10, 10, (2, 5)) result = activations.exponential(x[np.newaxis, :])[0] expected = np.exp(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.exponential(x_1d) expected_1d = np.exp(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.exponential(x_3d) expected_3d = np.exp(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.exponential(x_positive) expected_positive = np.exp(x_positive) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.exponential(x_negative) expected_negative = np.exp(x_negative) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.exponential(x_zero) expected_zero = np.exp(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.exponential(x_large) expected_large = np.exp(x_large) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_mish(self): # Basic test for the mish activation function x = np.random.random((2, 5)) result = activations.mish(x[np.newaxis, :])[0] expected = x * np.tanh(_ref_softplus(x)) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.uniform(-10, 10, (2, 5)) result = activations.mish(x[np.newaxis, :])[0] expected = x * np.tanh(_ref_softplus(x)) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.mish(x_1d) expected_1d = x_1d * np.tanh(_ref_softplus(x_1d)) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.mish(x_3d) expected_3d = x_3d * np.tanh(_ref_softplus(x_3d)) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.mish(x_positive) expected_positive = x_positive * np.tanh(_ref_softplus(x_positive)) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.mish(x_negative) expected_negative = x_negative * np.tanh(_ref_softplus(x_negative)) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.mish(x_zero) expected_zero = x_zero * np.tanh(_ref_softplus(x_zero)) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.mish(x_large) expected_large = x_large * np.tanh(_ref_softplus(x_large)) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_linear(self): x = np.random.random((10, 5)) self.assertAllClose(x, activations.linear(x)) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) self.assertAllClose(x_1d, activations.linear(x_1d)) # Test with 2D array x = np.random.uniform(-10, 10, (10, 5)) self.assertAllClose(x, activations.linear(x)) # Test with 3D array x_3d = np.random.uniform(-10, 10, (5, 5, 5)) self.assertAllClose(x_3d, activations.linear(x_3d)) # Test with float32 data type x_float32 = np.random.uniform(-10, 10, (10, 5)).astype(np.float32) self.assertAllClose(x_float32, activations.linear(x_float32)) # Test with int32 data type x_int32 = np.random.randint(-10, 10, (10, 5)).astype(np.int32) self.assertAllClose(x_int32, activations.linear(x_int32)) def test_get_method(self): obj = activations.get("relu") self.assertEqual(obj, activations.relu) obj = activations.get(None) self.assertEqual(obj, activations.linear) with self.assertRaises(ValueError): activations.get("typo")
keras-core/keras_core/activations/activations_test.py/0
{ "file_path": "keras-core/keras_core/activations/activations_test.py", "repo_id": "keras-core", "token_count": 14039 }
28
from keras_core import backend from keras_core import layers from keras_core.api_export import keras_core_export from keras_core.applications import imagenet_utils from keras_core.models import Functional from keras_core.ops import operation_utils from keras_core.utils import file_utils BASE_WEIGHTS_PATH = ( "https://storage.googleapis.com/tensorflow/keras-applications/resnet/" ) WEIGHTS_HASHES = { "resnet50": ( "2cb95161c43110f7111970584f804107", "4d473c1dd8becc155b73f8504c6f6626", ), "resnet101": ( "f1aeb4b969a6efcfb50fad2f0c20cfc5", "88cf7a10940856eca736dc7b7e228a21", ), "resnet152": ( "100835be76be38e30d865e96f2aaae62", "ee4c566cf9a93f14d82f913c2dc6dd0c", ), "resnet50v2": ( "3ef43a0b657b3be2300d5770ece849e0", "fac2f116257151a9d068a22e544a4917", ), "resnet101v2": ( "6343647c601c52e1368623803854d971", "c0ed64b8031c3730f411d2eb4eea35b5", ), "resnet152v2": ( "a49b44d1979771252814e80f8ec446f9", "ed17cf2e0169df9d443503ef94b23b33", ), "resnext50": ( "67a5b30d522ed92f75a1f16eef299d1a", "62527c363bdd9ec598bed41947b379fc", ), "resnext101": ( "34fb605428fcc7aa4d62f44404c11509", "0f678c91647380debd923963594981b3", ), } def ResNet( stack_fn, preact, use_bias, model_name="resnet", include_top=True, weights="imagenet", input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation="softmax", ): """Instantiates the ResNet, ResNetV2, and ResNeXt architecture. Args: stack_fn: A function that returns output tensor for the stacked residual blocks. preact: Whether to use pre-activation or not. `True` for ResNetV2, `False` for ResNet and ResNeXt. use_bias: Whether to use biases for convolutional layers or not. `True` for ResNet and ResNetV2, `False` for ResNeXt. model_name: Name of the model. include_top: Whether to include the fully-connected layer at the top of the network. weights: One of `None` (random initialization), `"imagenet"` (pre-training on ImageNet), or the path to the weights file to be loaded. input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: Optional shape tuple, only to be specified if `include_top` is `False` (otherwise the input shape has to be `(224, 224, 3)` (with `channels_last` data format) or `(3, 224, 224)` (with `"channels_first"` data format). It should have exactly 3 inputs channels. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of the last convolutional layer. - `avg` means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor. - `max` means that global max pooling will be applied. classes: optional number of classes to classify images into, only to be specified if `include_top` is `True`, and if no `weights` argument is specified. classifier_activation: A `str` or callable. The activation function to use on the "top" layer. Ignored unless `include_top=True`. Set `classifier_activation=None` to return the logits of the "top" layer. When loading pretrained weights, `classifier_activation` can only be `None` or `"softmax"`. Returns: A Model instance. """ if not (weights in {"imagenet", None} or file_utils.exists(weights)): raise ValueError( "The `weights` argument should be either " "`None` (random initialization), 'imagenet' " "(pre-training on ImageNet), " "or the path to the weights file to be loaded. Received: " f"weights={weights}" ) if weights == "imagenet" and include_top and classes != 1000: raise ValueError( "If using `weights='imagenet'` with `include_top=True`, " "`classes` should be 1000. " f"Received classes={classes}" ) # Determine proper input shape input_shape = imagenet_utils.obtain_input_shape( input_shape, default_size=224, min_size=32, data_format=backend.image_data_format(), require_flatten=include_top, weights=weights, ) if input_tensor is None: img_input = layers.Input(shape=input_shape) else: if not backend.is_keras_tensor(input_tensor): img_input = layers.Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor if backend.image_data_format() == "channels_last": bn_axis = 3 else: bn_axis = 1 x = layers.ZeroPadding2D(padding=((3, 3), (3, 3)), name="conv1_pad")( img_input ) x = layers.Conv2D(64, 7, strides=2, use_bias=use_bias, name="conv1_conv")(x) if not preact: x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name="conv1_bn" )(x) x = layers.Activation("relu", name="conv1_relu")(x) x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)), name="pool1_pad")(x) x = layers.MaxPooling2D(3, strides=2, name="pool1_pool")(x) x = stack_fn(x) if preact: x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name="post_bn" )(x) x = layers.Activation("relu", name="post_relu")(x) if include_top: x = layers.GlobalAveragePooling2D(name="avg_pool")(x) # Validate activation for the classifier layer imagenet_utils.validate_activation(classifier_activation, weights) x = layers.Dense( classes, activation=classifier_activation, name="predictions" )(x) else: if pooling == "avg": x = layers.GlobalAveragePooling2D(name="avg_pool")(x) elif pooling == "max": x = layers.GlobalMaxPooling2D(name="max_pool")(x) # Ensure that the model takes into account # any potential predecessors of `input_tensor`. if input_tensor is not None: inputs = operation_utils.get_source_inputs(input_tensor) else: inputs = img_input # Create model. model = Functional(inputs, x, name=model_name) # Load weights. if (weights == "imagenet") and (model_name in WEIGHTS_HASHES): if include_top: file_name = model_name + "_weights_tf_dim_ordering_tf_kernels.h5" file_hash = WEIGHTS_HASHES[model_name][0] else: file_name = ( model_name + "_weights_tf_dim_ordering_tf_kernels_notop.h5" ) file_hash = WEIGHTS_HASHES[model_name][1] weights_path = file_utils.get_file( file_name, BASE_WEIGHTS_PATH + file_name, cache_subdir="models", file_hash=file_hash, ) model.load_weights(weights_path) elif weights is not None: model.load_weights(weights) return model def residual_block_v1( x, filters, kernel_size=3, stride=1, conv_shortcut=True, name=None ): """A residual block for ResNet*_v1. Args: x: Input tensor. filters: No of filters in the bottleneck layer. kernel_size: Kernel size of the bottleneck layer. Defaults to `3`. stride: Stride of the first layer. Defaults to `1`. conv_shortcut: Use convolution shortcut if `True`, otherwise use identity shortcut. Defaults to `True` name(optional): Name of the block Returns: Output tensor for the residual block. """ if backend.image_data_format() == "channels_last": bn_axis = 3 else: bn_axis = 1 if conv_shortcut: shortcut = layers.Conv2D( 4 * filters, 1, strides=stride, name=name + "_0_conv" )(x) shortcut = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_0_bn" )(shortcut) else: shortcut = x x = layers.Conv2D(filters, 1, strides=stride, name=name + "_1_conv")(x) x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_1_bn" )(x) x = layers.Activation("relu", name=name + "_1_relu")(x) x = layers.Conv2D( filters, kernel_size, padding="SAME", name=name + "_2_conv" )(x) x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_2_bn" )(x) x = layers.Activation("relu", name=name + "_2_relu")(x) x = layers.Conv2D(4 * filters, 1, name=name + "_3_conv")(x) x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_3_bn" )(x) x = layers.Add(name=name + "_add")([shortcut, x]) x = layers.Activation("relu", name=name + "_out")(x) return x def stack_residual_blocks_v1(x, filters, blocks, stride1=2, name=None): """A set of stacked residual blocks. Args: x: Input tensor. filters: Number of filters in the bottleneck layer in a block. blocks: Number of blocks in the stacked blocks. stride1: Stride of the first layer in the first block. Defaults to `2`. name: Stack label. Returns: Output tensor for the stacked blocks. """ x = residual_block_v1(x, filters, stride=stride1, name=name + "_block1") for i in range(2, blocks + 1): x = residual_block_v1( x, filters, conv_shortcut=False, name=name + "_block" + str(i) ) return x def residual_block_v2( x, filters, kernel_size=3, stride=1, conv_shortcut=False, name=None ): """A residual block for ResNet*_v2. Args: x: Input tensor. filters: No of filters in the bottleneck layer. kernel_size: Kernel size of the bottleneck layer. Defaults to `3`. stride: Stride of the first layer. Defaults to `1`. conv_shortcut: Use convolution shortcut if `True`, otherwise use identity shortcut. Defaults to `True` name(optional): Name of the block Returns: Output tensor for the residual block. """ if backend.image_data_format() == "channels_last": bn_axis = 3 else: bn_axis = 1 preact = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_preact_bn" )(x) preact = layers.Activation("relu", name=name + "_preact_relu")(preact) if conv_shortcut: shortcut = layers.Conv2D( 4 * filters, 1, strides=stride, name=name + "_0_conv" )(preact) else: shortcut = ( layers.MaxPooling2D(1, strides=stride)(x) if stride > 1 else x ) x = layers.Conv2D( filters, 1, strides=1, use_bias=False, name=name + "_1_conv" )(preact) x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_1_bn" )(x) x = layers.Activation("relu", name=name + "_1_relu")(x) x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)), name=name + "_2_pad")(x) x = layers.Conv2D( filters, kernel_size, strides=stride, use_bias=False, name=name + "_2_conv", )(x) x = layers.BatchNormalization( axis=bn_axis, epsilon=1.001e-5, name=name + "_2_bn" )(x) x = layers.Activation("relu", name=name + "_2_relu")(x) x = layers.Conv2D(4 * filters, 1, name=name + "_3_conv")(x) x = layers.Add(name=name + "_out")([shortcut, x]) return x def stack_residual_blocks_v2(x, filters, blocks, stride1=2, name=None): """A set of stacked residual blocks. Args: x: Input tensor. filters: Number of filters in the bottleneck layer in a block. blocks: Number of blocks in the stacked blocks. stride1: Stride of the first layer in the first block. Defaults to `2`. name: Stack label. Returns: Output tensor for the stacked blocks. """ x = residual_block_v2(x, filters, conv_shortcut=True, name=name + "_block1") for i in range(2, blocks): x = residual_block_v2(x, filters, name=name + "_block" + str(i)) x = residual_block_v2( x, filters, stride=stride1, name=name + "_block" + str(blocks) ) return x @keras_core_export( [ "keras_core.applications.resnet50.ResNet50", "keras_core.applications.resnet.ResNet50", "keras_core.applications.ResNet50", ] ) def ResNet50( include_top=True, weights="imagenet", input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation="softmax", ): """Instantiates the ResNet50 architecture.""" def stack_fn(x): x = stack_residual_blocks_v1(x, 64, 3, stride1=1, name="conv2") x = stack_residual_blocks_v1(x, 128, 4, name="conv3") x = stack_residual_blocks_v1(x, 256, 6, name="conv4") return stack_residual_blocks_v1(x, 512, 3, name="conv5") return ResNet( stack_fn, False, True, "resnet50", include_top, weights, input_tensor, input_shape, pooling, classes, classifier_activation=classifier_activation, ) @keras_core_export( [ "keras_core.applications.resnet.ResNet101", "keras_core.applications.ResNet101", ] ) def ResNet101( include_top=True, weights="imagenet", input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation="softmax", ): """Instantiates the ResNet101 architecture.""" def stack_fn(x): x = stack_residual_blocks_v1(x, 64, 3, stride1=1, name="conv2") x = stack_residual_blocks_v1(x, 128, 4, name="conv3") x = stack_residual_blocks_v1(x, 256, 23, name="conv4") return stack_residual_blocks_v1(x, 512, 3, name="conv5") return ResNet( stack_fn, False, True, "resnet101", include_top, weights, input_tensor, input_shape, pooling, classes, classifier_activation=classifier_activation, ) @keras_core_export( [ "keras_core.applications.resnet.ResNet152", "keras_core.applications.ResNet152", ] ) def ResNet152( include_top=True, weights="imagenet", input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation="softmax", ): """Instantiates the ResNet152 architecture.""" def stack_fn(x): x = stack_residual_blocks_v1(x, 64, 3, stride1=1, name="conv2") x = stack_residual_blocks_v1(x, 128, 8, name="conv3") x = stack_residual_blocks_v1(x, 256, 36, name="conv4") return stack_residual_blocks_v1(x, 512, 3, name="conv5") return ResNet( stack_fn, False, True, "resnet152", include_top, weights, input_tensor, input_shape, pooling, classes, classifier_activation=classifier_activation, ) @keras_core_export( [ "keras_core.applications.resnet50.preprocess_input", "keras_core.applications.resnet.preprocess_input", ] ) def preprocess_input(x, data_format=None): return imagenet_utils.preprocess_input( x, data_format=data_format, mode="caffe" ) @keras_core_export( [ "keras_core.applications.resnet50.decode_predictions", "keras_core.applications.resnet.decode_predictions", ] ) def decode_predictions(preds, top=5): return imagenet_utils.decode_predictions(preds, top=top) preprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format( mode="", ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_CAFFE, error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC, ) decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__ DOC = """ Reference: - [Deep Residual Learning for Image Recognition]( https://arxiv.org/abs/1512.03385) (CVPR 2015) For image classification use cases, see [this page for detailed examples]( https://keras.io/api/applications/#usage-examples-for-image-classification-models). For transfer learning use cases, make sure to read the [guide to transfer learning & fine-tuning]( https://keras.io/guides/transfer_learning/). Note: each Keras Application expects a specific kind of input preprocessing. For ResNet, call `keras_core.applications.resnet.preprocess_input` on your inputs before passing them to the model. `resnet.preprocess_input` will convert the input images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling. Args: include_top: whether to include the fully-connected layer at the top of the network. weights: one of `None` (random initialization), `"imagenet"` (pre-training on ImageNet), or the path to the weights file to be loaded. input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is `False` (otherwise the input shape has to be `(224, 224, 3)` (with `"channels_last"` data format) or `(3, 224, 224)` (with `"channels_first"` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. `(200, 200, 3)` would be one valid value. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of the last convolutional block. - `avg` means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor. - `max` means that global max pooling will be applied. classes: optional number of classes to classify images into, only to be specified if `include_top` is `True`, and if no `weights` argument is specified. classifier_activation: A `str` or callable. The activation function to use on the "top" layer. Ignored unless `include_top=True`. Set `classifier_activation=None` to return the logits of the "top" layer. When loading pretrained weights, `classifier_activation` can only be `None` or `"softmax"`. Returns: A Model instance. """ setattr(ResNet50, "__doc__", ResNet50.__doc__ + DOC) setattr(ResNet101, "__doc__", ResNet101.__doc__ + DOC) setattr(ResNet152, "__doc__", ResNet152.__doc__ + DOC)
keras-core/keras_core/applications/resnet.py/0
{ "file_path": "keras-core/keras_core/applications/resnet.py", "repo_id": "keras-core", "token_count": 8540 }
29
from keras_core.api_export import keras_core_export from keras_core.backend.common import global_state @keras_core_export("keras_core.StatelessScope") class StatelessScope: def __init__( self, state_mapping=None, collect_losses=False, initialize_variables=True, ): from keras_core import backend from keras_core.backend.common.variables import KerasVariable self.collect_losses = collect_losses self.initialize_variables = initialize_variables self.losses = [] self.state_mapping = {} state_mapping = state_mapping or {} for k, v in state_mapping: if not isinstance(k, KerasVariable): raise ValueError( "Invalid reference variable in VariableSwapScope: " "all keys in argument `mapping` must be KerasVariable " f"instances. Received instead: {k}" ) v = backend.convert_to_tensor(v, dtype=k.dtype) if k.shape != v.shape: raise ValueError( "Invalid variable value in VariableSwapScope: " "all values in argument `mapping` must be tensors with " "a shape that matches the corresponding variable shape. " f"For variable {k}, received invalid value {v} with shape " f"{v.shape}." ) self.state_mapping[id(k)] = v def __enter__(self): self.original_scope = get_stateless_scope() global_state.set_global_attribute("stateless_scope", self) return self def add_loss(self, loss): self.losses.append(loss) def add_update(self, update): variable, value = update self.state_mapping[id(variable)] = value def get_current_value(self, variable): return self.state_mapping.get(id(variable), None) def __exit__(self, *args, **kwargs): global_state.set_global_attribute( "stateless_scope", self.original_scope ) if self.original_scope is None and self.initialize_variables: # We're back in eager scope; # if any variables were created within the stateless # scope, we initialize them here. from keras_core.backend.common.variables import ( initialize_all_variables, ) initialize_all_variables() def in_stateless_scope(): return global_state.get_global_attribute("stateless_scope") is not None def get_stateless_scope(): return global_state.get_global_attribute("stateless_scope")
keras-core/keras_core/backend/common/stateless_scope.py/0
{ "file_path": "keras-core/keras_core/backend/common/stateless_scope.py", "repo_id": "keras-core", "token_count": 1190 }
30
from functools import partial import jax import numpy as np import tree from keras_core import backend from keras_core import callbacks as callbacks_module from keras_core import ops from keras_core import optimizers as optimizers_module from keras_core.backend import distribution_lib as jax_distribution_lib from keras_core.distribution import distribution_lib from keras_core.trainers import trainer as base_trainer from keras_core.trainers.data_adapters import data_adapter_utils from keras_core.trainers.epoch_iterator import EpochIterator from keras_core.utils import traceback_utils class JAXTrainer(base_trainer.Trainer): def __init__(self): super().__init__() self.train_function = None self.test_function = None self.predict_function = None def compute_loss_and_updates( self, trainable_variables, non_trainable_variables, x, y, sample_weight, training=False, optimizer_variables=None, ): """This method is stateless and is intended for use with jax.grad.""" kwargs = {} if self._call_has_training_arg: kwargs["training"] = training y_pred, non_trainable_variables, losses = self.stateless_call( trainable_variables, non_trainable_variables, x, return_losses=True, **kwargs, ) trainable_mapping = zip(self.trainable_variables, trainable_variables) with backend.StatelessScope(state_mapping=trainable_mapping): # Note that this is needed for the regularization loss, which need # the latest value of train/non-trainable variables. loss = self.compute_loss( x, y, y_pred, sample_weight, allow_empty=True ) if losses: loss += ops.sum(losses) unscaled_loss = loss if training and self.optimizer is not None: # Scale loss with a StatelessScope, to use an update scale variable. mapping = list(zip(self.optimizer.variables, optimizer_variables)) with backend.StatelessScope(state_mapping=mapping): loss = self.optimizer.scale_loss(loss) return loss, (unscaled_loss, y_pred, non_trainable_variables) def _eager_build(self, data_batch): model_unbuilt = not all(layer.built for layer in self._flatten_layers()) compile_metrics_unbuilt = ( self._compile_metrics is not None and not self._compile_metrics.built ) if model_unbuilt or compile_metrics_unbuilt: def _convert_data_to_spec(d): if d is None: return None return backend.KerasTensor(d.shape, d.dtype) data_spec = tree.map_structure(_convert_data_to_spec, data_batch) ( x_spec, y_spec, sample_weight_spec, ) = data_adapter_utils.unpack_x_y_sample_weight(data_spec) # Note that this __call__ run the forward path and trigger variable # creation. y_pred_spec = backend.compute_output_spec(self.__call__, x_spec) if compile_metrics_unbuilt: # This will trigger the metric variable creation. backend.compute_output_spec( self.compute_metrics, x_spec, y_spec, y_pred_spec, sample_weight=sample_weight_spec, ) if self.optimizer is not None and not self.optimizer.built: # Build optimizer self.optimizer.build(self.trainable_variables) def train_step(self, state, data): ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) = state x, y, sample_weight = data_adapter_utils.unpack_x_y_sample_weight(data) grad_fn = jax.value_and_grad( self.compute_loss_and_updates, has_aux=True ) (loss, aux), grads = grad_fn( trainable_variables, non_trainable_variables, x, y, sample_weight, training=True, optimizer_variables=optimizer_variables, ) (unscaled_loss, y_pred, non_trainable_variables) = aux ( trainable_variables, optimizer_variables, ) = self.optimizer.stateless_apply( optimizer_variables, grads, trainable_variables ) with backend.StatelessScope( state_mapping=[ (ref_v, v) for ref_v, v in zip(self.metrics_variables, metrics_variables) ] ) as scope: self._loss_tracker.update_state(unscaled_loss) logs = self.compute_metrics(x, y, y_pred, sample_weight) new_metrics_variables = [] for ref_v in self.metrics_variables: new_v = scope.get_current_value(ref_v) if new_v is None: new_v = ref_v.value new_metrics_variables.append(new_v) metrics_variables = new_metrics_variables state = self._enforce_jax_state_sharding( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) return logs, state def test_step(self, state, data): ( trainable_variables, non_trainable_variables, metrics_variables, ) = state x, y, sample_weight = data_adapter_utils.unpack_x_y_sample_weight(data) loss, aux = self.compute_loss_and_updates( trainable_variables, non_trainable_variables, x, y, sample_weight, training=False, ) (unscaled_loss, y_pred, non_trainable_variables) = aux with backend.StatelessScope( state_mapping=[ (ref_v, v) for ref_v, v in zip(self.metrics_variables, metrics_variables) ] ) as scope: self._loss_tracker.update_state(unscaled_loss) logs = self.compute_metrics(x, y, y_pred, sample_weight) new_metrics_variables = [] for ref_v in self.metrics_variables: new_v = scope.get_current_value(ref_v) if new_v is None: new_v = ref_v.value new_metrics_variables.append(new_v) metrics_variables = new_metrics_variables ( trainable_variables, non_trainable_variables, _, metrics_variables, ) = self._enforce_jax_state_sharding( trainable_variables=trainable_variables, non_trainable_variables=non_trainable_variables, optimizer_variables=None, metrics_variables=metrics_variables, ) state = ( trainable_variables, non_trainable_variables, metrics_variables, ) return logs, state def predict_step(self, state, data): trainable_variables, non_trainable_variables = state kwargs = {} if self._call_has_training_arg: kwargs["training"] = False x, _, _ = data_adapter_utils.unpack_x_y_sample_weight(data) outputs, non_trainable_variables = self.stateless_call( trainable_variables, non_trainable_variables, x, **kwargs ) ( trainable_variables, non_trainable_variables, _, _, ) = self._enforce_jax_state_sharding( trainable_variables=trainable_variables, non_trainable_variables=non_trainable_variables, optimizer_variables=None, metrics_variables=None, ) return outputs, (trainable_variables, non_trainable_variables) def make_train_function(self, force=False): if self.train_function is not None and not force: return self.train_function def one_train_step(state, data): data = data[0] return self.train_step(state, data) def multi_train_steps(state, data): for single_step_data in data: logs, state = one_train_step(state, [single_step_data]) return logs, state if self.steps_per_execution > 1: train_step = multi_train_steps else: train_step = one_train_step if not self.run_eagerly and self.jit_compile: # Note that we mark the state and data to be donated to jax, # so that jax will reuse the memory buffer for outputs. # This will reduce the memory usage of the training function by # half. @partial(jax.jit, donate_argnames="state") def compiled_train_step(state, data): return train_step(state, data) self.train_function = compiled_train_step else: self.train_function = train_step def make_test_function(self, force=False): if self.test_function is not None and not force: return self.test_function def one_test_step(state, data): data = data[0] return self.test_step(state, data) def multi_test_steps(state, data): for single_step_data in data: logs, state = one_test_step(state, [single_step_data]) return logs, state if self.steps_per_execution > 1: test_step = multi_test_steps else: test_step = one_test_step if not self.run_eagerly and self.jit_compile: # Note that we mark the state and data to be donated to jax, # so that jax will reuse the memory buffer for outputs. # This will reduce the memory usage of the training function by # half. @partial(jax.jit, donate_argnames="state") def compiled_test_step(state, data): return test_step(state, data) self.test_function = compiled_test_step else: self.test_function = test_step def make_predict_function(self, force=False): if self.predict_function is not None and not force: return self.predict_function def one_predict_step(state, data): data = data[0] return self.predict_step(state, data) def multi_predict_steps(state, data): outputs, state = one_predict_step(state, data[:1]) for single_step_data in data[1:]: step_outputs, state = one_predict_step( state, [single_step_data], ) outputs = tree.map_structure( lambda t1, t2: jax.numpy.concatenate([t1, t2]), outputs, step_outputs, ) return outputs, state if self.steps_per_execution > 1: predict_step = multi_predict_steps else: predict_step = one_predict_step if not self.run_eagerly and self.jit_compile: @jax.jit def compiled_predict_step(state, data): return predict_step(state, data) self.predict_function = compiled_predict_step else: self.predict_function = predict_step @traceback_utils.filter_traceback def fit( self, x=None, y=None, batch_size=None, epochs=1, verbose="auto", callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1, ): self._assert_compile_called("fit") # TODO: respect compiled trainable state if validation_split and validation_data is None: # Create the validation data using the training data. Only supported # for TF/numpy/jax arrays. ( x, y, sample_weight, ), validation_data = data_adapter_utils.train_validation_split( (x, y, sample_weight), validation_split=validation_split ) if validation_data: ( val_x, val_y, val_sample_weight, ) = data_adapter_utils.unpack_x_y_sample_weight(validation_data) # Create an iterator that yields batches for one epoch. epoch_iterator = EpochIterator( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps_per_epoch, shuffle=shuffle, class_weight=class_weight, steps_per_execution=self.steps_per_execution, ) needs_building = ( not all(layer.built for layer in self._flatten_layers()) or not self.optimizer.built or ( self._compile_metrics is not None and not self._compile_metrics.built ) ) if needs_building: # Build the model on one batch of data. for _, data in epoch_iterator.enumerate_epoch(return_type="np"): data_batch = data[0] self._eager_build(data_batch) break # Container that configures and calls callbacks. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, verbose=verbose, epochs=epochs, steps=epoch_iterator.num_batches, model=self, ) self._record_training_state_sharding_spec() self.make_train_function() self.stop_training = False callbacks.on_train_begin() for epoch in range(initial_epoch, epochs): self.reset_metrics() callbacks.on_epoch_begin(epoch) trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] optimizer_variables = [v.value for v in self.optimizer.variables] metrics_variables = [v.value for v in self.metrics_variables] self._purge_model_variables() for step, data in epoch_iterator.enumerate_epoch(return_type="np"): # Callbacks callbacks.on_train_batch_begin(step) # Train step state = ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) data = self._distribute_data(data) logs, state = self.train_function(state, data) ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) = state # Setting _jax_state enables callbacks to force a state sync # if they need to. self._jax_state = { "trainable_variables": trainable_variables, "non_trainable_variables": non_trainable_variables, "optimizer_variables": optimizer_variables, "metrics_variables": metrics_variables, } # Callbacks callbacks.on_train_batch_end(step, self._pythonify_logs(logs)) if self.stop_training: break # Reattach state to model variables. # NOTE: doing this after each step would be a big performance # bottleneck. self.jax_state_sync() # Override with model metrics instead of last step logs epoch_logs = self.get_metrics_result() # Run validation. if validation_data and self._should_eval(epoch, validation_freq): # Create EpochIterator for evaluation and cache it. if getattr(self, "_eval_epoch_iterator", None) is None: self._eval_epoch_iterator = EpochIterator( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps_per_execution=self.steps_per_execution, steps_per_epoch=validation_steps, shuffle=False, ) val_logs = self.evaluate( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps=validation_steps, callbacks=callbacks, return_dict=True, _use_cached_eval_dataset=True, ) val_logs = { "val_" + name: val for name, val in val_logs.items() } epoch_logs.update(val_logs) callbacks.on_epoch_end(epoch, epoch_logs) training_logs = epoch_logs if self.stop_training: break if ( isinstance(self.optimizer, optimizers_module.Optimizer) and epochs > 0 ): self.optimizer.finalize_variable_values(self.trainable_weights) # If _eval_epoch_iterator exists, delete it after all epochs are done. if getattr(self, "_eval_epoch_iterator", None) is not None: del self._eval_epoch_iterator callbacks.on_train_end(logs=training_logs) self._jax_state = None return self.history @traceback_utils.filter_traceback def evaluate( self, x=None, y=None, batch_size=None, verbose="auto", sample_weight=None, steps=None, callbacks=None, return_dict=False, **kwargs, ): self._assert_compile_called("evaluate") # TODO: respect compiled trainable state use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False) if kwargs: raise ValueError(f"Arguments not recognized: {kwargs}") if use_cached_eval_dataset: epoch_iterator = self._eval_epoch_iterator else: # Create an iterator that yields batches of input/target data. epoch_iterator = EpochIterator( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps, shuffle=False, steps_per_execution=self.steps_per_execution, ) needs_building = not all( layer.built for layer in self._flatten_layers() ) or ( self._compile_metrics is not None and not self._compile_metrics.built ) if needs_building: # Build the model on one batch of data. for _, data in epoch_iterator.enumerate_epoch(return_type="np"): data_batch = data[0] self._eager_build(data_batch) break # Container that configures and calls callbacks. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, verbose=verbose, epochs=1, steps=epoch_iterator.num_batches, model=self, ) self._record_training_state_sharding_spec() self.make_test_function() callbacks.on_test_begin() logs = None self.reset_metrics() trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] metrics_variables = [v.value for v in self.metrics_variables] self._purge_model_variables(optimizer_variables=False) for step, data in epoch_iterator.enumerate_epoch(return_type="np"): callbacks.on_test_batch_begin(step) state = ( trainable_variables, non_trainable_variables, metrics_variables, ) data = self._distribute_data(data) logs, state = self.test_function(state, data) ( trainable_variables, non_trainable_variables, metrics_variables, ) = state # Setting _jax_state enables callbacks to force a state sync # if they need to. self._jax_state = { # I wouldn't recommend modifying non-trainable model state # during evaluate(), but it's allowed. "trainable_variables": trainable_variables, "non_trainable_variables": non_trainable_variables, "metrics_variables": metrics_variables, } callbacks.on_test_batch_end(step, self._pythonify_logs(logs)) # Reattach state back to model. self.jax_state_sync() logs = self.get_metrics_result() callbacks.on_test_end(logs) self._jax_state = None if return_dict: return logs return self._flatten_metrics_in_order(logs) @traceback_utils.filter_traceback def predict( self, x, batch_size=None, verbose="auto", steps=None, callbacks=None ): # Create an iterator that yields batches of input data. epoch_iterator = EpochIterator( x=x, batch_size=batch_size, steps_per_epoch=steps, shuffle=False, steps_per_execution=self.steps_per_execution, ) if not all(layer.built for layer in self._flatten_layers()): # Build the model on one batch of data. for _, data in epoch_iterator.enumerate_epoch(return_type="np"): # Build model x, _, _ = data_adapter_utils.unpack_x_y_sample_weight(data[0]) with backend.StatelessScope(): self(x) break # Container that configures and calls callbacks. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, verbose=verbose, epochs=1, steps=epoch_iterator.num_batches, model=self, ) self._record_training_state_sharding_spec() self.make_predict_function() callbacks.on_predict_begin() def append_to_outputs(batch_outputs, outputs): if outputs is None: outputs = tree.map_structure( lambda batch_output: [batch_output], batch_outputs, ) else: tree.map_structure_up_to( batch_outputs, lambda output, batch_output: output.append(batch_output), outputs, batch_outputs, ) return outputs trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] state = (trainable_variables, non_trainable_variables) outputs = None for step, x in epoch_iterator.enumerate_epoch(return_type="np"): callbacks.on_predict_batch_begin(step) x = self._distribute_data(x) batch_outputs, state = self.predict_function(state, x) outputs = append_to_outputs(batch_outputs, outputs) callbacks.on_predict_batch_end(step, {"outputs": batch_outputs}) callbacks.on_predict_end() return tree.map_structure_up_to(batch_outputs, np.concatenate, outputs) def train_on_batch( self, x, y=None, sample_weight=None, class_weight=None, return_dict=False, ): self._assert_compile_called("train_on_batch") if class_weight is not None: if sample_weight is not None: raise ValueError( "Arguments `sample_weight` and `class_weight` " "cannot be specified at the same time. " f"Received: sample_weight={sample_weight}, " f"class_weight={class_weight}" ) sample_weight = data_adapter_utils.class_weight_to_sample_weights( y, class_weight ) data = (x, y, sample_weight) data = self._distribute_data(data) # Maybe build model self._eager_build(data) self._record_training_state_sharding_spec() self.make_train_function() # Train step trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] optimizer_variables = [v.value for v in self.optimizer.variables] metrics_variables = [v.value for v in self.metrics_variables] state = ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) logs, state = self.train_function(state, [data]) # State sync ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) = state self._jax_state = { "trainable_variables": trainable_variables, "non_trainable_variables": non_trainable_variables, "optimizer_variables": optimizer_variables, "metrics_variables": metrics_variables, } self.jax_state_sync() # Format return values logs = tree.map_structure(lambda x: np.array(x), logs) if return_dict: return logs return self._flatten_metrics_in_order(logs) def test_on_batch( self, x, y=None, sample_weight=None, return_dict=False, ): self._assert_compile_called("test_on_batch") data = (x, y, sample_weight) data = self._distribute_data(data) # Maybe build model self._eager_build(data) self._record_training_state_sharding_spec() self.make_test_function() # Test step trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] metrics_variables = [v.value for v in self.metrics_variables] state = ( trainable_variables, non_trainable_variables, metrics_variables, ) logs, state = self.test_function(state, [data]) # State sync trainable_variables, non_trainable_variables, metrics_variables = state self._jax_state = { "trainable_variables": trainable_variables, "non_trainable_variables": non_trainable_variables, "metrics_variables": metrics_variables, } self.jax_state_sync() # Format return values. logs = tree.map_structure(lambda x: np.array(x), logs) if return_dict: return logs return self._flatten_metrics_in_order(logs) def predict_on_batch(self, x): if not all(layer.built for layer in self._flatten_layers()): # Build model with backend.StatelessScope(): self(x) self._record_training_state_sharding_spec() self.make_predict_function() trainable_variables = [v.value for v in self.trainable_variables] non_trainable_variables = [ v.value for v in self.non_trainable_variables ] state = (trainable_variables, non_trainable_variables) batch_outputs, state = self.predict_function(state, [(x,)]) batch_outputs = tree.map_structure(lambda x: np.array(x), batch_outputs) return batch_outputs def jax_state_sync(self): if not getattr(self, "_jax_state", None): return trainable_variables = self._jax_state.get("trainable_variables", None) non_trainable_variables = self._jax_state.get( "non_trainable_variables", None ) optimizer_variables = self._jax_state.get("optimizer_variables", None) metrics_variables = self._jax_state.get("metrics_variables", None) if trainable_variables: for ref_v, v in zip(self.trainable_variables, trainable_variables): ref_v.assign(v) if non_trainable_variables: for ref_v, v in zip( self.non_trainable_variables, non_trainable_variables ): ref_v.assign(v) if optimizer_variables: for ref_v, v in zip(self.optimizer.variables, optimizer_variables): ref_v.assign(v) if metrics_variables: for ref_v, v in zip(self.metrics_variables, metrics_variables): ref_v.assign(v) def _distribute_data(self, data): distribution = distribution_lib.distribution() if distribution is not None: def distribute_single_value(d): layout = distribution.get_data_layout(d.shape) return jax_distribution_lib.distribute_value(d, layout) return jax.tree_util.tree_map(distribute_single_value, data) else: return data def _record_training_state_sharding_spec(self): self._trainable_variable_shardings = [ v.value.sharding for v in self.trainable_variables ] self._non_trainable_variable_shardings = [ v.value.sharding for v in self.non_trainable_variables ] if hasattr(self, "optimizer") and self.optimizer is not None: self._optimizer_variable_shardings = [ v.value.sharding for v in self.optimizer.variables ] else: self._optimizer_variable_shardings = [] self._metrics_variable_shardings = [ v.value.sharding for v in self.metrics_variables ] def _enforce_jax_state_sharding( self, trainable_variables=None, non_trainable_variables=None, optimizer_variables=None, metrics_variables=None, ): """Enforce the sharding spec constraint for all the training state. Since the output of the train/eval step will be used as inputs to next step, we need to ensure that they have the same sharding spec, so that jax.jit won't have to recompile the train/eval function. Note that this function will also rely on the recorded sharding spec for each of states. This function is expected to be called within the jitted train/eval function, especially around the end of the function. """ trainable_variables = trainable_variables or [] non_trainable_variables = non_trainable_variables or [] optimizer_variables = optimizer_variables or [] metrics_variables = metrics_variables or [] for i in range(len(trainable_variables)): trainable_variables[i] = jax.lax.with_sharding_constraint( trainable_variables[i], self._trainable_variable_shardings[i] ) for i in range(len(non_trainable_variables)): non_trainable_variables[i] = jax.lax.with_sharding_constraint( non_trainable_variables[i], self._non_trainable_variable_shardings[i], ) for i in range(len(optimizer_variables)): optimizer_variables[i] = jax.lax.with_sharding_constraint( optimizer_variables[i], self._optimizer_variable_shardings[i] ) for i in range(len(metrics_variables)): metrics_variables[i] = jax.lax.with_sharding_constraint( metrics_variables[i], self._metrics_variable_shardings[i] ) return ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) def _purge_model_variables( self, trainable_variables=True, non_trainable_variables=True, optimizer_variables=True, metric_variables=True, ): """Remove all the model variable for memory saving. During JAX training, since the training function are stateless, we have to pass in and get the model weights over and over, during which the copy of the weights that attached to the KerasVariable are still and occupying extra memory. We remove those variable to save memory (for better memory utilization) at the beginning of the epoch, and reattach the value back to variables at the end of the epoch, via `jax_state_sync()`. """ if trainable_variables: for v in self.trainable_variables: v._value = None if non_trainable_variables: for v in self.non_trainable_variables: v._value = None if optimizer_variables: for v in self.optimizer.variables: v._value = None if metric_variables: for v in self.metrics_variables: v._value = None
keras-core/keras_core/backend/jax/trainer.py/0
{ "file_path": "keras-core/keras_core/backend/jax/trainer.py", "repo_id": "keras-core", "token_count": 17214 }
31
import tensorflow as tf from keras_core.backend import standardize_dtype from keras_core.backend.tensorflow.core import convert_to_tensor def segment_sum(data, segment_ids, num_segments=None, sorted=False): if sorted: return tf.math.segment_sum(data, segment_ids) else: if num_segments is None: unique_segment_ids, _ = tf.unique(segment_ids) num_segments = tf.shape(unique_segment_ids)[0] return tf.math.unsorted_segment_sum(data, segment_ids, num_segments) def segment_max(data, segment_ids, num_segments=None, sorted=False): if sorted: return tf.math.segment_max(data, segment_ids) else: if num_segments is None: unique_segment_ids, _ = tf.unique(segment_ids) num_segments = tf.shape(unique_segment_ids)[0] return tf.math.unsorted_segment_max(data, segment_ids, num_segments) def top_k(x, k, sorted=True): return tf.math.top_k(x, k, sorted=sorted) def in_top_k(targets, predictions, k): return tf.math.in_top_k(targets, predictions, k) def logsumexp(x, axis=None, keepdims=False): return tf.math.reduce_logsumexp(x, axis=axis, keepdims=keepdims) def qr(x, mode="reduced"): if mode not in {"reduced", "complete"}: raise ValueError( "`mode` argument value not supported. " "Expected one of {'reduced', 'complete'}. " f"Received: mode={mode}" ) if mode == "reduced": return tf.linalg.qr(x) return tf.linalg.qr(x, full_matrices=True) def extract_sequences(x, sequence_length, sequence_stride): return tf.signal.frame( x, frame_length=sequence_length, frame_step=sequence_stride, axis=-1, pad_end=False, ) def _get_complex_tensor_from_tuple(x): if not isinstance(x, (tuple, list)) or len(x) != 2: raise ValueError( "Input `x` should be a tuple of two tensors - real and imaginary." f"Received: x={x}" ) # `convert_to_tensor` does not support passing complex tensors. We separate # the input out into real and imaginary and convert them separately. real, imag = x real = convert_to_tensor(real) imag = convert_to_tensor(imag) # Check shapes. if real.shape != imag.shape: raise ValueError( "Input `x` should be a tuple of two tensors - real and imaginary." "Both the real and imaginary parts should have the same shape. " f"Received: x[0].shape = {real.shape}, x[1].shape = {imag.shape}" ) # Ensure dtype is float. if not real.dtype.is_floating or not imag.dtype.is_floating: raise ValueError( "At least one tensor in input `x` is not of type float." f"Received: x={x}." ) complex_input = tf.dtypes.complex(real, imag) return complex_input def fft(x): complex_input = _get_complex_tensor_from_tuple(x) complex_output = tf.signal.fft(complex_input) return tf.math.real(complex_output), tf.math.imag(complex_output) def fft2(x): complex_input = _get_complex_tensor_from_tuple(x) complex_output = tf.signal.fft2d(complex_input) return tf.math.real(complex_output), tf.math.imag(complex_output) def rfft(x, fft_length=None): if fft_length is not None: fft_length = [fft_length] complex_output = tf.signal.rfft(x, fft_length=fft_length) return tf.math.real(complex_output), tf.math.imag(complex_output) def irfft(x, fft_length=None): complex_input = _get_complex_tensor_from_tuple(x) if fft_length is not None: fft_length = [fft_length] return tf.signal.irfft(complex_input, fft_length) def stft( x, sequence_length, sequence_stride, fft_length, window="hann", center=True ): if standardize_dtype(x.dtype) not in {"float32", "float64"}: raise TypeError( "Invalid input type. Expected `float32` or `float64`. " f"Received: input type={x.dtype}" ) if fft_length < sequence_length: raise ValueError( "`fft_length` must equal or larger than `sequence_length`. " f"Received: sequence_length={sequence_length}, " f"fft_length={fft_length}" ) if isinstance(window, str): if window not in {"hann", "hamming"}: raise ValueError( "If a string is passed to `window`, it must be one of " f'`"hann"`, `"hamming"`. Received: window={window}' ) x = convert_to_tensor(x) if center: pad_width = [(0, 0) for _ in range(len(x.shape))] pad_width[-1] = (fft_length // 2, fft_length // 2) x = tf.pad(x, pad_width, mode="reflect") l_pad = (fft_length - sequence_length) // 2 r_pad = fft_length - sequence_length - l_pad if window is not None: if isinstance(window, str): if window == "hann": win_array = tf.signal.hann_window( sequence_length, periodic=True, dtype=x.dtype ) else: win_array = tf.signal.hamming_window( sequence_length, periodic=True, dtype=x.dtype ) else: win_array = convert_to_tensor(window, dtype=x.dtype) if len(win_array.shape) != 1 or win_array.shape[-1] != sequence_length: raise ValueError( "The shape of `window` must be equal to [sequence_length]." f"Received: window shape={win_array.shape}" ) win_array = tf.pad(win_array, [[l_pad, r_pad]]) def win(frame_step, dtype): return win_array else: win = None result = tf.signal.stft( x, frame_length=(sequence_length + l_pad + r_pad), frame_step=sequence_stride, fft_length=fft_length, window_fn=win, ) return tf.math.real(result), tf.math.imag(result) def istft( x, sequence_length, sequence_stride, fft_length, length=None, window="hann", center=True, ): complex_input = _get_complex_tensor_from_tuple(x) dtype = tf.math.real(complex_input).dtype expected_output_len = fft_length + sequence_stride * ( tf.shape(complex_input)[-2] - 1 ) l_pad = (fft_length - sequence_length) // 2 r_pad = fft_length - sequence_length - l_pad if window is not None: if isinstance(window, str): if window == "hann": win_array = tf.signal.hann_window( sequence_length, periodic=True, dtype=dtype ) else: win_array = tf.signal.hamming_window( sequence_length, periodic=True, dtype=dtype ) else: win_array = convert_to_tensor(window, dtype=dtype) if len(win_array.shape) != 1 or win_array.shape[-1] != sequence_length: raise ValueError( "The shape of `window` must be equal to [sequence_length]." f"Received: window shape={win_array.shape}" ) win_array = tf.pad(win_array, [[l_pad, r_pad]]) win = tf.signal.inverse_stft_window_fn( sequence_stride, lambda frame_step, dtype: win_array ) else: win = None x = tf.signal.inverse_stft( complex_input, frame_length=(sequence_length + l_pad + r_pad), frame_step=sequence_stride, fft_length=fft_length, window_fn=win, ) start = 0 if center is False else fft_length // 2 if length is not None: end = start + length elif center is True: end = -(fft_length // 2) else: end = expected_output_len return x[..., start:end] def rsqrt(x): return tf.math.rsqrt(x)
keras-core/keras_core/backend/tensorflow/math.py/0
{ "file_path": "keras-core/keras_core/backend/tensorflow/math.py", "repo_id": "keras-core", "token_count": 3658 }
32
import math import torch from keras_core.backend import standardize_dtype from keras_core.backend.torch.core import convert_to_tensor from keras_core.backend.torch.core import get_device from keras_core.backend.torch.numpy import pad def segment_sum(data, segment_ids, num_segments=None, **kwargs): data = convert_to_tensor(data) segment_ids = convert_to_tensor(segment_ids) num_repeats = torch.prod( torch.tensor(data.shape[1:], device=get_device()) ).long() # To use `scatter_add` in torch, we need to replicate `segment_ids` into the # shape of `data`. segment_ids = ( segment_ids.repeat_interleave(num_repeats) .view(*data.shape) .type(torch.int64) ) num_segments = num_segments or len(torch.unique(segment_ids)) # .scatter_add does not support -1 in the indices. # Add all out-of-bound indices value to an extra dimension after # num_segments, which is removed before returning the result. # Replacing the out-of-bound indices. segment_ids = torch.where(segment_ids >= 0, segment_ids, num_segments) segment_ids = torch.where( segment_ids < num_segments, segment_ids, num_segments ) # Add one more dimension to the result shape with the "+1". shape = (num_segments + 1,) + tuple(data.shape[1:]) result = torch.zeros(*shape, device=get_device()).scatter_add( 0, segment_ids, data.float() ) # Removing the extra dimension. result = result[:-1, ...] return result.type(data.dtype) def segment_max(data, segment_ids, num_segments=None, **kwargs): data = convert_to_tensor(data) segment_ids = convert_to_tensor(segment_ids) num_repeats = torch.prod( torch.tensor(data.shape[1:], device=get_device()) ).long() # To use `scatter_reduce` in torch, we need to replicate `segment_ids` into # the shape of `data`. segment_ids = ( segment_ids.repeat_interleave(num_repeats) .view(*data.shape) .type(torch.int64) ) num_segments = num_segments or len(torch.unique(segment_ids)) # .scatter_reduce does not support -1 in the indices. # Add all out-of-bound indices value to an extra dimension after # num_segments, which is removed before returning the result. # Replacing the out-of-bound indices. segment_ids = torch.where(segment_ids >= 0, segment_ids, num_segments) segment_ids = torch.where( segment_ids < num_segments, segment_ids, num_segments ) # Add one more dimension to the result shape with the "+1". shape = (num_segments + 1,) + tuple(data.shape[1:]) result = torch.zeros(*shape, device=get_device()).scatter_reduce( 0, segment_ids, data.float(), "amax" ) # Removing the extra dimension. result = result[:-1, ...] return result.type(data.dtype) def top_k(x, k, sorted=True): x = convert_to_tensor(x) return torch.topk(x, k, sorted=sorted) def in_top_k(targets, predictions, k): targets = convert_to_tensor(targets).type(torch.int64) targets = targets[:, None] predictions = convert_to_tensor(predictions) topk_values = top_k(predictions, k).values targets_values = torch.take_along_dim(predictions, targets, dim=-1) mask = targets_values >= topk_values return torch.any(mask, axis=-1) def logsumexp(x, axis=None, keepdims=False): x = convert_to_tensor(x) if axis is None: max_x = torch.max(x) return torch.log(torch.sum(torch.exp(x - max_x))) + max_x max_x = torch.amax(x, dim=axis, keepdim=True) result = ( torch.log(torch.sum(torch.exp(x - max_x), dim=axis, keepdim=True)) + max_x ) return torch.squeeze(result, dim=axis) if not keepdims else result def qr(x, mode="reduced"): x = convert_to_tensor(x) if mode not in {"reduced", "complete"}: raise ValueError( "`mode` argument value not supported. " "Expected one of {'reduced', 'complete'}. " f"Received: mode={mode}" ) x = convert_to_tensor(x) return torch.linalg.qr(x, mode=mode) def extract_sequences(x, sequence_length, sequence_stride): x = convert_to_tensor(x) return torch.unfold_copy( x, dimension=-1, size=sequence_length, step=sequence_stride ) def _overlap_sequences(x, sequence_stride): # Ref: https://github.com/google/jax/blob/main/jax/_src/scipy/signal.py x = convert_to_tensor(x) *batch_shape, num_sequences, sequence_length = x.shape if sequence_stride > sequence_length: raise ValueError( "`sequence_stride` must equal or less than x.shape[-1]. " f"Received: sequence_stride={sequence_stride}, " f"x.shape[-1]={sequence_length}" ) if sequence_stride < (sequence_length / num_sequences): raise ValueError( "`sequence_stride` must equal or greater than " "x.shape[-1] / x.shape[-2]. " f"Received: sequence_stride={sequence_stride}, " f"x.shape[-1]={sequence_length}, x.shape[-2]={num_sequences}" ) flat_batchsize = math.prod(batch_shape) x = torch.reshape(x, (flat_batchsize, num_sequences, sequence_length)) output_size = sequence_stride * (num_sequences - 1) + sequence_length nstep_per_segment = 1 + (sequence_length - 1) // sequence_stride # Here, we use shorter notation for axes. # B: batch_size, N: num_sequences, S: nstep_per_segment, # T: sequence_length divided by S padded_segment_len = nstep_per_segment * sequence_stride x = torch.nn.functional.pad( x, (0, padded_segment_len - sequence_length, 0, 0, 0, 0) ) x = torch.reshape( x, (flat_batchsize, num_sequences, nstep_per_segment, sequence_stride) ) # For obtaining shifted signals, this routine reinterprets flattened array # with a shrinked axis. With appropriate truncation/ padding, this # operation pushes the last padded elements of the previous row to the head # of the current row. # See implementation of `overlap_and_add` in Tensorflow for details. x = torch.permute(x, (0, 2, 1, 3)) # x: (B, S, N, T) x = torch.nn.functional.pad(x, (0, 0, 0, num_sequences, 0, 0, 0, 0)) # x: (B, S, N*2, T) shrinked = x.shape[2] - 1 x = torch.reshape(x, (flat_batchsize, -1)) x = x[:, : (nstep_per_segment * shrinked * sequence_stride)] x = torch.reshape( x, (flat_batchsize, nstep_per_segment, shrinked * sequence_stride) ) # Finally, sum shifted segments, and truncate results to the output_size. x = torch.sum(x, dim=1)[:, :output_size] return torch.reshape(x, tuple(batch_shape) + (-1,)) def _get_complex_tensor_from_tuple(x): if not isinstance(x, (tuple, list)) or len(x) != 2: raise ValueError( "Input `x` should be a tuple of two tensors - real and imaginary." f"Received: x={x}" ) # `convert_to_tensor` does not support passing complex tensors. We separate # the input out into real and imaginary and convert them separately. real, imag = x real = convert_to_tensor(real) imag = convert_to_tensor(imag) # Check shape. if real.shape != imag.shape: raise ValueError( "Input `x` should be a tuple of two tensors - real and imaginary." "Both the real and imaginary parts should have the same shape. " f"Received: x[0].shape = {real.shape}, x[1].shape = {imag.shape}" ) # Ensure dtype is float. if not torch.is_floating_point(real) or not torch.is_floating_point(imag): raise ValueError( "At least one tensor in input `x` is not of type float." f"Received: x={x}." ) complex_input = torch.complex(real, imag) return complex_input def fft(x): complex_input = _get_complex_tensor_from_tuple(x) complex_output = torch.fft.fft(complex_input) return complex_output.real, complex_output.imag def fft2(x): complex_input = _get_complex_tensor_from_tuple(x) complex_output = torch.fft.fft2(complex_input) return complex_output.real, complex_output.imag def rfft(x, fft_length=None): x = convert_to_tensor(x) complex_output = torch.fft.rfft(x, n=fft_length, dim=-1, norm="backward") return complex_output.real, complex_output.imag def irfft(x, fft_length=None): complex_input = _get_complex_tensor_from_tuple(x) return torch.fft.irfft(complex_input, n=fft_length, dim=-1, norm="backward") def stft( x, sequence_length, sequence_stride, fft_length, window="hann", center=True ): if standardize_dtype(x.dtype) not in {"float32", "float64"}: raise TypeError( "Invalid input type. Expected `float32` or `float64`. " f"Received: input type={x.dtype}" ) if fft_length < sequence_length: raise ValueError( "`fft_length` must equal or larger than `sequence_length`. " f"Received: sequence_length={sequence_length}, " f"fft_length={fft_length}" ) if isinstance(window, str): if window not in {"hann", "hamming"}: raise ValueError( "If a string is passed to `window`, it must be one of " f'`"hann"`, `"hamming"`. Received: window={window}' ) x = convert_to_tensor(x) if window is not None: if isinstance(window, str): if window == "hann": win = torch.hann_window( sequence_length, periodic=True, dtype=x.dtype, device=get_device(), ) else: win = torch.hamming_window( sequence_length, periodic=True, dtype=x.dtype, device=get_device(), ) else: win = convert_to_tensor(window, dtype=x.dtype) if len(win.shape) != 1 or win.shape[-1] != sequence_length: raise ValueError( "The shape of `window` must be equal to [sequence_length]." f"Received: window shape={win.shape}" ) else: win = torch.ones((sequence_length,), dtype=x.dtype, device=get_device()) need_unpack = False *batch_shape, samples = x.shape if len(x.shape) > 2: need_unpack = True flat_batchsize = math.prod(batch_shape) x = torch.reshape(x, (flat_batchsize, samples)) x = torch.stft( x, n_fft=fft_length, hop_length=sequence_stride, win_length=sequence_length, window=win, center=center, return_complex=True, ) if need_unpack: fft_unique_bins, num_sequences = x.shape[-2:] x = torch.reshape(x, (*batch_shape, fft_unique_bins, num_sequences)) x = torch.swapaxes(x, -2, -1) return x.real, x.imag def istft( x, sequence_length, sequence_stride, fft_length, length=None, window="hann", center=True, ): complex_input = _get_complex_tensor_from_tuple(x) dtype = complex_input.real.dtype win = None if window is not None: if isinstance(window, str): if window == "hann": win = torch.hann_window( sequence_length, periodic=True, dtype=dtype, device=get_device(), ) else: win = torch.hamming_window( sequence_length, periodic=True, dtype=dtype, device=get_device(), ) else: win = convert_to_tensor(window, dtype=dtype) if len(win.shape) != 1 or win.shape[-1] != sequence_length: raise ValueError( "The shape of `window` must be equal to [sequence_length]." f"Received: window shape={win.shape}" ) if sequence_length == fft_length and center is True and win is not None: # can be falled back to torch.istft need_unpack = False *batch_shape, num_sequences, fft_unique_bins = complex_input.shape if len(complex_input.shape) > 3: need_unpack = True flat_batchsize = math.prod(batch_shape) complex_input = torch.reshape( complex_input, (flat_batchsize, num_sequences, fft_unique_bins) ) complex_input = torch.swapaxes(complex_input, -2, -1) x = torch.istft( complex_input, n_fft=fft_length, hop_length=sequence_stride, win_length=sequence_length, window=win, center=center, length=length, return_complex=False, ) if need_unpack: samples = x.shape[-1] x = torch.reshape(x, (*batch_shape, samples)) return x # custom implementation with irfft and _overlap_sequences # references: # torch: aten/src/ATen/native/SpectralOps.cpp # tf: tf.signal.inverse_stft_window_fn x = irfft(x, fft_length) expected_output_len = fft_length + sequence_stride * (x.shape[-2] - 1) if win is not None: l_pad = (fft_length - sequence_length) // 2 r_pad = fft_length - sequence_length - l_pad win = pad(win, [[l_pad, r_pad]], "constant") # square and sum _sequence_length = sequence_length + l_pad + r_pad denom = torch.square(win) overlaps = -(-_sequence_length // sequence_stride) denom = pad(denom, [(0, overlaps * sequence_stride - _sequence_length)]) denom = torch.reshape(denom, [overlaps, sequence_stride]) denom = torch.sum(denom, 0, keepdims=True) denom = torch.tile(denom, [overlaps, 1]) denom = torch.reshape(denom, [overlaps * sequence_stride]) win = torch.divide(win, denom[:_sequence_length]) x = torch.multiply(x, win) x = _overlap_sequences(x, sequence_stride) start = 0 if center is False else fft_length // 2 if length is not None: end = start + length elif center is True: end = -(fft_length // 2) else: end = expected_output_len return x[..., start:end] def rsqrt(x): x = convert_to_tensor(x) return torch.rsqrt(x)
keras-core/keras_core/backend/torch/math.py/0
{ "file_path": "keras-core/keras_core/backend/torch/math.py", "repo_id": "keras-core", "token_count": 6505 }
33
import torch import tree from keras_core.backend.torch.core import convert_to_tensor from keras_core.utils.nest import pack_sequence_as def rnn( step_function, inputs, initial_states, go_backwards=False, mask=None, constants=None, unroll=False, input_length=None, time_major=False, zero_output_for_mask=False, return_all_outputs=True, ): input_length = input_length or inputs.shape[1] def swap_batch_timestep(input_t): # Swap the batch and timestep dim for the incoming tensor. axes = list(range(len(input_t.shape))) axes[0], axes[1] = 1, 0 return torch.permute(input_t, axes) if not time_major: inputs = tree.map_structure(swap_batch_timestep, inputs) flattened_inputs = tree.flatten(inputs) time_steps = flattened_inputs[0].shape[0] time_steps_t = time_steps if mask is not None: if mask.dtype != torch.bool: mask = mask.type(torch.bool) if len(mask.shape) == 2: mask = torch.unsqueeze(mask, -1) if not time_major: mask = swap_batch_timestep(mask) if constants is None: constants = [] def _expand_mask(mask_t, input_t, fixed_dim=1): if tree.is_nested(mask_t): raise ValueError( f"mask_t is expected to be tensor, but got {mask_t}" ) if tree.is_nested(input_t): raise ValueError( f"input_t is expected to be tensor, but got {input_t}" ) rank_diff = len(input_t.shape) - len(mask_t.shape) for _ in range(rank_diff): mask_t = torch.unsqueeze(mask_t, -1) multiples = [1] * fixed_dim + list(input_t.shape[fixed_dim:]) return torch.tile(mask_t, multiples) if unroll: if not time_steps: raise ValueError("Unrolling requires a fixed number of timesteps.") states = tuple(initial_states) successive_states = [] successive_outputs = [] # Process the input tensors. The input tensor need to be split on the # time_step dim, and reverse if go_backwards is True. In the case of # nested input, the input is flattened and then transformed # individually. The result of this will be a tuple of lists, each of # the item in tuple is list of the tensor with shape (batch, feature) def _process_single_input_t(input_t): input_t = torch.unbind(input_t) # unstack for time_step dim if go_backwards: input_t = input_t[::-1] return input_t if tree.is_nested(inputs): processed_input = tree.map_structure( _process_single_input_t, inputs ) else: processed_input = (_process_single_input_t(inputs),) def _get_input_tensor(time): inp = [t_[time] for t_ in processed_input] return pack_sequence_as(inputs, inp) if mask is not None: mask_list = torch.unbind(mask) if go_backwards: mask_list = torch.flip(mask_list, dims=mask_list.shape) for i in range(time_steps): inp = _get_input_tensor(i) mask_t = mask_list[i] output, new_states = step_function( inp, tuple(states) + tuple(constants) ) tiled_mask_t = _expand_mask(mask_t, output) if not successive_outputs: prev_output = torch.zeros_like(output) else: prev_output = successive_outputs[-1] output = torch.where(tiled_mask_t, output, prev_output) flat_states = tree.flatten(states) flat_new_states = tree.flatten(new_states) tiled_mask_t = tuple( _expand_mask(mask_t, s) for s in flat_states ) flat_final_states = tuple( torch.where(m, s, ps) for m, s, ps in zip( tiled_mask_t, flat_new_states, flat_states ) ) states = pack_sequence_as(states, flat_final_states) if return_all_outputs: successive_outputs.append(output) successive_states.append(states) else: successive_outputs = [output] successive_states = [states] last_output = successive_outputs[-1] new_states = successive_states[-1] outputs = torch.stack(successive_outputs) if zero_output_for_mask: last_output = torch.where( _expand_mask(mask_list[-1], last_output), last_output, torch.zeros_like(last_output), ) outputs = torch.where( _expand_mask(mask, outputs, fixed_dim=2), outputs, torch.zeros_like(outputs), ) else: # mask is None for i in range(time_steps): inp = _get_input_tensor(i) output, states = step_function( inp, tuple(states) + tuple(constants) ) if return_all_outputs: successive_outputs.append(output) successive_states.append(states) else: successive_outputs = [output] successive_states = [states] last_output = successive_outputs[-1] new_states = successive_states[-1] outputs = torch.stack(successive_outputs) else: # Unroll == False states = tuple(initial_states) # Create input tensor array, if the inputs is nested tensors, then it # will be flattened first, and tensor array will be created one per # flattened tensor. input_ta = tuple( list(torch.unbind(input_)) if not go_backwards else list(torch.unbind(torch.flip(input_, [0]))) for input_ in flattened_inputs ) # Get the time(0) input and compute the output for that. input_time_zero = pack_sequence_as( inputs, [inp[0] for inp in flattened_inputs] ) # output_time_zero is used to determine the cell output shape. output_time_zero, _ = step_function( input_time_zero, tuple(initial_states) + tuple(constants) ) output_ta_size = time_steps_t if return_all_outputs else 1 output_ta = [] for out in tree.flatten(output_time_zero): out_list = list(out) if len(out) < output_ta_size: out_list.extend([[]] * (output_ta_size - len(out))) output_ta.append(out_list) time = torch.tensor(0, dtype=torch.int32) if input_length is None: max_iterations = time_steps_t else: if hasattr(input_length, "__len__"): input_length = convert_to_tensor(input_length) max_iterations = torch.max(input_length) else: max_iterations = input_length if mask is not None: if go_backwards: mask = torch.flip(mask, [0]) mask_ta = list(torch.unbind(mask)) def masking_fn(time): return mask_ta[time] def compute_masked_output(mask_t, flat_out, flat_mask): tiled_mask_t = tuple( _expand_mask(mask_t, o, fixed_dim=len(mask_t.shape)) for o in flat_out ) return tuple( torch.where(m, o, fm) for m, o, fm in zip(tiled_mask_t, flat_out, flat_mask) ) elif isinstance(input_length, torch.Tensor): if go_backwards: max_len = torch.max(input_length, dim=0) rev_input_length = torch.subtract(max_len - 1, input_length) def masking_fn(time): return torch.less(rev_input_length, time) else: def masking_fn(time): return torch.greater(input_length, time) def compute_masked_output(mask_t, flat_out, flat_mask): return tuple( torch.where(mask_t, o, zo) for (o, zo) in zip(flat_out, flat_mask) ) else: masking_fn = None if masking_fn is not None: # Mask for the T output will be base on the output of T - 1. In the # case T = 0, a zero filled tensor will be used. flat_zero_output = tuple( torch.zeros_like(o) for o in tree.flatten(output_time_zero) ) def _step(time, output_ta_t, prev_output, *states): """RNN step function. Args: time: Current timestep value. output_ta_t: TensorArray. prev_output: tuple of outputs from time - 1. *states: List of states. Returns: Tuple: `(time + 1, output_ta_t, output) + tuple(new_states)` """ current_input = tuple(ta[time] for ta in input_ta) # maybe set shape. current_input = pack_sequence_as(inputs, current_input) mask_t = masking_fn(time) output, new_states = step_function( current_input, tuple(states) + tuple(constants) ) # mask output flat_output = tree.flatten(output) flat_mask_output = ( flat_zero_output if zero_output_for_mask else tree.flatten(prev_output) ) flat_new_output = compute_masked_output( mask_t, flat_output, flat_mask_output ) # mask states flat_state = tree.flatten(states) flat_new_state = tree.flatten(new_states) flat_final_state = compute_masked_output( mask_t, flat_new_state, flat_state ) new_states = pack_sequence_as(new_states, flat_final_state) ta_index_to_write = time if return_all_outputs else 0 for ta, out in zip(output_ta_t, flat_new_output): ta[ta_index_to_write] = out return (time + 1, output_ta_t, tuple(flat_new_output)) + tuple( new_states ) it = 0 output_ta_t, new_states, prev_output = ( output_ta, states, flat_zero_output, ) while time < time_steps_t and it < max_iterations: final_outputs = _step( time, output_ta_t, prev_output, *new_states ) time, output_ta_t, prev_output = final_outputs[:3] new_states = final_outputs[3:] it += 1 else: def _step(time, output_ta_t, *states): """RNN step function. Args: time: Current timestep value. output_ta_t: TensorArray. *states: List of states. Returns: Tuple: `(time + 1,output_ta_t) + tuple(new_states)` """ current_input = tuple(ta[time] for ta in input_ta) current_input = pack_sequence_as(inputs, current_input) output, new_states = step_function( current_input, tuple(states) + tuple(constants) ) flat_new_state = tree.flatten(new_states) flat_output = tree.flatten(output) ta_index_to_write = time if return_all_outputs else 0 for ta, out in zip(output_ta_t, flat_output): ta[ta_index_to_write] = out new_states = pack_sequence_as(initial_states, flat_new_state) return (time + 1, output_ta_t) + tuple(new_states) it = 0 output_ta_t = output_ta new_states = states while time < time_steps_t and it < max_iterations: final_outputs = _step(time, output_ta_t, *new_states) time, output_ta_t = final_outputs[:2] new_states = final_outputs[2:] it += 1 def _stack(tensor_list): max_ndims = max([t.ndim for t in tensor_list]) max_list = [] for i, t in enumerate(tensor_list): if t.ndim == max_ndims: max_list.append(t) return torch.stack(max_list) output_ta = final_outputs[1] outputs = tuple(_stack(o) for o in output_ta) last_output = tuple(o[-1] for o in outputs) outputs = pack_sequence_as(output_time_zero, outputs) last_output = pack_sequence_as(output_time_zero, last_output) if not time_major: outputs = tree.map_structure(swap_batch_timestep, outputs) return last_output, outputs, new_states def cudnn_ok(*args, **kwargs): return False def lstm(*args, **kwargs): raise NotImplementedError def gru(*args, **kwargs): raise NotImplementedError
keras-core/keras_core/backend/torch/rnn.py/0
{ "file_path": "keras-core/keras_core/backend/torch/rnn.py", "repo_id": "keras-core", "token_count": 7245 }
34
import pytest from keras_core import callbacks from keras_core import layers from keras_core import optimizers from keras_core import testing from keras_core.models import Sequential from keras_core.testing import test_utils from keras_core.utils import io_utils from keras_core.utils import numerical_utils class LearningRateSchedulerTest(testing.TestCase): def setUp(self): (x_train, y_train), _ = test_utils.get_test_data( train_samples=10, test_samples=10, input_shape=(3,), num_classes=2, ) y_train = numerical_utils.to_categorical(y_train) model = Sequential([layers.Dense(5), layers.Dense(2)]) model.compile( loss="mse", optimizer="sgd", ) self.model = model self.x_train = x_train self.y_train = y_train @pytest.mark.requires_trainable_backend def test_updates_learning_rate(self): lr_scheduler = callbacks.LearningRateScheduler( lambda step: 1.0 / (2.0 + step), verbose=1 ) self.model.fit( self.x_train, self.y_train, callbacks=[lr_scheduler], epochs=1, ) self.assertEqual(self.model.optimizer.learning_rate.value, 0.5) @pytest.mark.requires_trainable_backend def test_verbose_logging(self): lr_scheduler = callbacks.LearningRateScheduler( lambda step: 1.0 / (1.0 + step), verbose=1 ) io_utils.disable_interactive_logging() io_utils.set_logging_verbosity("INFO") with self.assertLogs() as logs: self.model.fit( self.x_train, self.y_train, callbacks=[lr_scheduler], epochs=1, ) expected_log = "LearningRateScheduler setting learning rate to 1.0" self.assertTrue(any(expected_log in log for log in logs.output)) @pytest.mark.requires_trainable_backend def test_schedule_dependent_on_previous_learning_rate(self): lr_scheduler = callbacks.LearningRateScheduler(lambda step, lr: lr / 2) initial_lr = 0.03 self.model.compile( loss="mse", optimizer=optimizers.Adam(initial_lr), ) self.model.fit( self.x_train, self.y_train, callbacks=[lr_scheduler], epochs=2, ) self.assertEqual( self.model.optimizer.learning_rate.value, initial_lr / 4.0 ) @pytest.mark.requires_trainable_backend def test_throws_when_optimizer_has_schedule(self): lr_scheduler = callbacks.LearningRateScheduler(lambda step, lr: lr / 2) self.model.compile( loss="mse", optimizer=optimizers.Adam( optimizers.schedules.PolynomialDecay( initial_learning_rate=0.1, decay_steps=10 ) ), ) with self.assertRaisesRegex( TypeError, "This optimizer was created with a `LearningRateSchedule`", ): self.model.fit( self.x_train, self.y_train, callbacks=[lr_scheduler], epochs=2, ) @pytest.mark.requires_trainable_backend def test_learning_rate_in_history(self): lr_scheduler = callbacks.LearningRateScheduler(lambda step, lr: 0.5) history = self.model.fit( self.x_train, self.y_train, callbacks=[lr_scheduler], epochs=1, ) self.assertTrue("learning_rate" in history.history) self.assertEqual(type(history.history["learning_rate"][0]), float) self.assertEqual(history.history["learning_rate"][0], 0.5)
keras-core/keras_core/callbacks/learning_rate_scheduler_test.py/0
{ "file_path": "keras-core/keras_core/callbacks/learning_rate_scheduler_test.py", "repo_id": "keras-core", "token_count": 1916 }
35
from keras_core.api_export import keras_core_export @keras_core_export("keras_core.datasets.boston_housing.load_data") def load_data(path="boston_housing.npz", test_split=0.2, seed=113): raise NotImplementedError( "The Boston Housing dataset is no longer distributed with Keras. " "We recommend that you use instead the " "California Housing dataset, available via " "`keras_core.datasets.california_housing.load_data()`." )
keras-core/keras_core/datasets/boston_housing.py/0
{ "file_path": "keras-core/keras_core/datasets/boston_housing.py", "repo_id": "keras-core", "token_count": 175 }
36
from keras_core import ops from keras_core.api_export import keras_core_export from keras_core.backend import standardize_dtype from keras_core.initializers.initializer import Initializer @keras_core_export( ["keras_core.initializers.Constant", "keras_core.initializers.constant"] ) class Constant(Initializer): """Initializer that generates tensors with constant values. Only scalar values are allowed. The constant value provided must be convertible to the dtype requested when calling the initializer. Examples: >>> # Standalone usage: >>> initializer = Constant(10.) >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: >>> initializer = Constant(10.) >>> layer = Dense(3, kernel_initializer=initializer) Args: value: A Python scalar. """ def __init__(self, value=0.0): self.value = value def __call__(self, shape, dtype=None): dtype = standardize_dtype(dtype) return ops.cast(self.value, dtype=dtype) * ops.ones( shape=shape, dtype=dtype ) def get_config(self): return {"value": self.value} @keras_core_export( ["keras_core.initializers.Zeros", "keras_core.initializers.zeros"] ) class Zeros(Initializer): """Initializer that generates tensors initialized to 0. Examples: >>> # Standalone usage: >>> initializer = Zeros() >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: >>> initializer = Zeros() >>> layer = Dense(units=3, kernel_initializer=initializer) """ def __call__(self, shape, dtype=None): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. If not specified, `keras_core.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `keras_core.backend.set_floatx(float_dtype)`). """ dtype = standardize_dtype(dtype) return ops.zeros(shape, dtype=dtype) @keras_core_export( ["keras_core.initializers.Ones", "keras_core.initializers.ones"] ) class Ones(Initializer): """Initializer that generates tensors initialized to 1. Also available via the shortcut function `ones`. Examples: >>> # Standalone usage: >>> initializer = Ones() >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: >>> initializer = Ones() >>> layer = Dense(3, kernel_initializer=initializer) """ def __call__(self, shape, dtype=None): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. If not specified, `keras_core.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `keras_core.backend.set_floatx(float_dtype)`). """ dtype = standardize_dtype(dtype) return ops.ones(shape, dtype=dtype) @keras_core_export( [ "keras_core.initializers.IdentityInitializer", "keras_core.initializers.Identity", "keras_core.initializers.identity", ] ) class Identity(Initializer): """Initializer that generates the identity matrix. Only usable for generating 2D matrices. Examples: >>> # Standalone usage: >>> initializer = Identity() >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: >>> initializer = Identity() >>> layer = Dense(3, kernel_initializer=initializer) Args: gain: Multiplicative factor to apply to the identity matrix. """ def __init__(self, gain=1.0): self.gain = gain def __call__(self, shape, dtype=None): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. If not specified, `keras_core.backend.floatx()` is used, which default to `float32` unless you configured it otherwise (via `keras_core.backend.set_floatx(float_dtype)`). """ if len(shape) != 2: raise ValueError( "Identity matrix initializer can only be used for 2D matrices. " f"Received: shape={shape} of rank {len(shape)}." ) dtype = standardize_dtype(dtype) return self.gain * ops.eye(*shape, dtype=dtype)
keras-core/keras_core/initializers/constant_initializers.py/0
{ "file_path": "keras-core/keras_core/initializers/constant_initializers.py", "repo_id": "keras-core", "token_count": 1893 }
37
import numpy as np import pytest from keras_core import testing from keras_core.layers.activations import relu class ReLUTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_relu(self): self.run_layer_test( relu.ReLU, init_kwargs={ "max_value": 10, "negative_slope": 1, "threshold": 0.5, }, input_shape=(2, 3, 4), supports_masking=True, ) def test_normal_relu_correctness(self): relu_layer = relu.ReLU(max_value=10, negative_slope=0.0, threshold=0) input = np.array([-10, -5, 0.0, 5, 10]) expected_output = np.array([0.0, 0.0, 0.0, 5.0, 10.0]) result = relu_layer(input) self.assertAllClose(result, expected_output) def test_leaky_relu_correctness(self): relu_layer = relu.ReLU(max_value=10, negative_slope=0.5, threshold=0) input = np.array([-10, -5, 0.0, 5, 10]) expected_output = np.array([-5.0, -2.5, 0.0, 5.0, 10.0]) result = relu_layer(input) self.assertAllClose(result, expected_output) def test_threshold_relu_correctness(self): relu_layer = relu.ReLU(max_value=8, negative_slope=0.0, threshold=5) input = np.array([6.0, 7.0, 0.0, 5, 10]) expected_output = np.array([6.0, 7.0, 0.0, 0.0, 8.0]) result = relu_layer(input) self.assertAllClose(result, expected_output) def test_invalid_usage(self): with self.assertRaisesRegex( ValueError, "max_value of a ReLU layer cannot be a negative value", ): self.run_layer_test( relu.ReLU, init_kwargs={ "max_value": -10, "negative_slope": 1, "threshold": 0.5, }, input_shape=(2, 3, 4), supports_masking=True, ) with self.assertRaisesRegex( ValueError, "negative_slope of a ReLU layer cannot be a negative value", ): self.run_layer_test( relu.ReLU, init_kwargs={ "max_value": 10, "negative_slope": -10, "threshold": 0.5, }, input_shape=(2, 3, 4), supports_masking=True, ) with self.assertRaisesRegex( ValueError, "threshold of a ReLU layer cannot be a negative value" ): self.run_layer_test( relu.ReLU, init_kwargs={ "max_value": 10, "negative_slope": 1, "threshold": -10, }, input_shape=(2, 3, 4), supports_masking=True, )
keras-core/keras_core/layers/activations/relu_test.py/0
{ "file_path": "keras-core/keras_core/layers/activations/relu_test.py", "repo_id": "keras-core", "token_count": 1617 }
38
from keras_core.api_export import keras_core_export from keras_core.layers.convolutional.base_conv_transpose import ( BaseConvTranspose, ) @keras_core_export( [ "keras_core.layers.Conv1DTranspose", "keras_core.layers.Convolution1DTranspose", ] ) class Conv1DTranspose(BaseConvTranspose): """1D transposed convolution layer. The need for transposed convolutions generally arise from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. Args: filters: int, the dimension of the output space (the number of filters in the transpose convolution). kernel_size: int or tuple/list of 1 integer, specifying the size of the transposed convolution window. strides: int or tuple/list of 1 integer, specifying the stride length of the transposed convolution. `strides > 1` is incompatible with `dilation_rate > 1`. padding: string, either `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, steps, features)` while `"channels_first"` corresponds to inputs with shape `(batch, features, steps)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `"channels_last"`. dilation_rate: int or tuple/list of 1 integers, specifying the dilation rate to use for dilated transposed convolution. activation: Activation function. If `None`, no activation is applied. use_bias: bool, if `True`, bias will be added to the output. kernel_initializer: Initializer for the convolution kernel. If `None`, the default initializer (`"glorot_uniform"`) will be used. bias_initializer: Initializer for the bias vector. If `None`, the default initializer (`"zeros"`) will be used. kernel_regularizer: Optional regularizer for the convolution kernel. bias_regularizer: Optional regularizer for the bias vector. activity_regularizer: Optional regularizer function for the output. kernel_constraint: Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer`. Input shape: - If `data_format="channels_last"`: A 3D tensor with shape: `(batch_shape, steps, channels)` - If `data_format="channels_first"`: A 3D tensor with shape: `(batch_shape, channels, steps)` Output shape: - If `data_format="channels_last"`: A 3D tensor with shape: `(batch_shape, new_steps, filters)` - If `data_format="channels_first"`: A 3D tensor with shape: `(batch_shape, filters, new_steps)` Returns: A 3D tensor representing `activation(conv1d_transpose(inputs, kernel) + bias)`. Raises: ValueError: when both `strides > 1` and `dilation_rate > 1`. References: - [A guide to convolution arithmetic for deep learning]( https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks]( https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) Examples: >>> x = np.random.rand(4, 10, 128) >>> y = keras_core.layers.Conv1DTranspose(32, 3, 2, activation='relu')(x) >>> print(y.shape) (4, 21, 32) """ def __init__( self, filters, kernel_size, strides=1, padding="valid", data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs ): super().__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs )
keras-core/keras_core/layers/convolutional/conv1d_transpose.py/0
{ "file_path": "keras-core/keras_core/layers/convolutional/conv1d_transpose.py", "repo_id": "keras-core", "token_count": 2261 }
39
import re from keras_core import activations from keras_core import constraints from keras_core import initializers from keras_core import ops from keras_core import regularizers from keras_core.api_export import keras_core_export from keras_core.layers.layer import Layer @keras_core_export("keras_core.layers.EinsumDense") class EinsumDense(Layer): """A layer that uses `einsum` as the backing computation. This layer can perform einsum calculations of arbitrary dimensionality. Args: equation: An equation describing the einsum to perform. This equation must be a valid einsum string of the form `ab,bc->ac`, `...ab,bc->...ac`, or `ab...,bc->ac...` where 'ab', 'bc', and 'ac' can be any valid einsum axis expression sequence. output_shape: The expected shape of the output tensor (excluding the batch dimension and any dimensions represented by ellipses). You can specify `None` for any dimension that is unknown or can be inferred from the input shape. activation: Activation function to use. If you don't specify anything, no activation is applied (that is, a "linear" activation: `a(x) = x`). bias_axes: A string containing the output dimension(s) to apply a bias to. Each character in the `bias_axes` string should correspond to a character in the output portion of the `equation` string. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. kernel_constraint: Constraint function applied to the `kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. **kwargs: Base layer keyword arguments, such as `name` and `dtype`. Examples: **Biased dense layer with einsums** This example shows how to instantiate a standard Keras dense layer using einsum operations. This example is equivalent to `keras_core.layers.Dense(64, use_bias=True)`. >>> layer = keras_core.layers.EinsumDense("ab,bc->ac", ... output_shape=64, ... bias_axes="c") >>> input_tensor = keras_core.Input(shape=[32]) >>> output_tensor = layer(input_tensor) >>> output_tensor.shape (None, 64) **Applying a dense layer to a sequence** This example shows how to instantiate a layer that applies the same dense operation to every element in a sequence. Here, the `output_shape` has two values (since there are two non-batch dimensions in the output); the first dimension in the `output_shape` is `None`, because the sequence dimension `b` has an unknown shape. >>> layer = keras_core.layers.EinsumDense("abc,cd->abd", ... output_shape=(None, 64), ... bias_axes="d") >>> input_tensor = keras_core.Input(shape=[32, 128]) >>> output_tensor = layer(input_tensor) >>> output_tensor.shape (None, 32, 64) **Applying a dense layer to a sequence using ellipses** This example shows how to instantiate a layer that applies the same dense operation to every element in a sequence, but uses the ellipsis notation instead of specifying the batch and sequence dimensions. Because we are using ellipsis notation and have specified only one axis, the `output_shape` arg is a single value. When instantiated in this way, the layer can handle any number of sequence dimensions - including the case where no sequence dimension exists. >>> layer = keras_core.layers.EinsumDense("...x,xy->...y", ... output_shape=64, ... bias_axes="y") >>> input_tensor = keras_core.Input(shape=[32, 128]) >>> output_tensor = layer(input_tensor) >>> output_tensor.shape (None, 32, 64) """ def __init__( self, equation, output_shape, activation=None, bias_axes=None, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs, ): super().__init__(**kwargs) self.equation = equation if isinstance(output_shape, int): self.partial_output_shape = (output_shape,) else: self.partial_output_shape = tuple(output_shape) self.bias_axes = bias_axes self.activation = activations.get(activation) self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) def build(self, input_shape): shape_data = _analyze_einsum_string( self.equation, self.bias_axes, input_shape, self.partial_output_shape, ) kernel_shape, bias_shape, full_output_shape = shape_data self.full_output_shape = tuple(full_output_shape) self.kernel = self.add_weight( name="kernel", shape=tuple(kernel_shape), initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, dtype=self.dtype, trainable=True, ) if bias_shape is not None: self.bias = self.add_weight( name="bias", shape=tuple(bias_shape), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, dtype=self.dtype, trainable=True, ) else: self.bias = None super().build(input_shape) def compute_output_shape(self, _): return self.full_output_shape def get_config(self): base_config = super().get_config() config = { "output_shape": self.partial_output_shape, "equation": self.equation, "activation": activations.serialize(self.activation), "bias_axes": self.bias_axes, "kernel_initializer": initializers.serialize( self.kernel_initializer ), "bias_initializer": initializers.serialize(self.bias_initializer), "kernel_regularizer": regularizers.serialize( self.kernel_regularizer ), "bias_regularizer": regularizers.serialize(self.bias_regularizer), "activity_regularizer": regularizers.serialize( self.activity_regularizer ), "kernel_constraint": constraints.serialize(self.kernel_constraint), "bias_constraint": constraints.serialize(self.bias_constraint), } return {**base_config, **config} def call(self, inputs): x = ops.einsum(self.equation, inputs, self.kernel) if self.bias is not None: x += self.bias if self.activation is not None: x = self.activation(x) return x def _analyze_einsum_string(equation, bias_axes, input_shape, output_shape): """Analyzes an einsum string to determine the required weight shape.""" dot_replaced_string = re.sub(r"\.\.\.", "0", equation) # This is the case where no ellipses are present in the string. split_string = re.match( "([a-zA-Z]+),([a-zA-Z]+)->([a-zA-Z]+)", dot_replaced_string ) if split_string: return _analyze_split_string( split_string, bias_axes, input_shape, output_shape ) # This is the case where ellipses are present on the left. split_string = re.match( "0([a-zA-Z]+),([a-zA-Z]+)->0([a-zA-Z]+)", dot_replaced_string ) if split_string: return _analyze_split_string( split_string, bias_axes, input_shape, output_shape, left_elided=True ) # This is the case where ellipses are present on the right. split_string = re.match( "([a-zA-Z]{2,})0,([a-zA-Z]+)->([a-zA-Z]+)0", dot_replaced_string ) if split_string: return _analyze_split_string( split_string, bias_axes, input_shape, output_shape ) raise ValueError( f"Invalid einsum equation '{equation}'. Equations must be in the form " "[X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]...." ) def _analyze_split_string( split_string, bias_axes, input_shape, output_shape, left_elided=False ): """Analyze an pre-split einsum string to find the weight shape.""" input_spec = split_string.group(1) weight_spec = split_string.group(2) output_spec = split_string.group(3) elided = len(input_shape) - len(input_spec) if isinstance(output_shape, int): output_shape = [output_shape] else: output_shape = list(output_shape) output_shape.insert(0, input_shape[0]) if elided > 0 and left_elided: for i in range(1, elided): # We already inserted the 0th input dimension at dim 0, so we need # to start at location 1 here. output_shape.insert(1, input_shape[i]) elif elided > 0 and not left_elided: for i in range(len(input_shape) - elided, len(input_shape)): output_shape.append(input_shape[i]) if left_elided: # If we have beginning dimensions elided, we need to use negative # indexing to determine where in the input dimension our values are. input_dim_map = { dim: (i + elided) - len(input_shape) for i, dim in enumerate(input_spec) } # Because we've constructed the full output shape already, we don't need # to do negative indexing. output_dim_map = { dim: (i + elided) for i, dim in enumerate(output_spec) } else: input_dim_map = {dim: i for i, dim in enumerate(input_spec)} output_dim_map = {dim: i for i, dim in enumerate(output_spec)} for dim in input_spec: input_shape_at_dim = input_shape[input_dim_map[dim]] if dim in output_dim_map: output_shape_at_dim = output_shape[output_dim_map[dim]] if ( output_shape_at_dim is not None and output_shape_at_dim != input_shape_at_dim ): raise ValueError( "Input shape and output shape do not match at shared " f"dimension '{dim}'. Input shape is {input_shape_at_dim}, " "and output shape " f"is {output_shape[output_dim_map[dim]]}." ) for dim in output_spec: if dim not in input_spec and dim not in weight_spec: raise ValueError( f"Dimension '{dim}' was specified in the output " f"'{output_spec}' but has no corresponding dim in the input " f"spec '{input_spec}' or weight spec '{output_spec}'" ) weight_shape = [] for dim in weight_spec: if dim in input_dim_map: weight_shape.append(input_shape[input_dim_map[dim]]) elif dim in output_dim_map: weight_shape.append(output_shape[output_dim_map[dim]]) else: raise ValueError( f"Weight dimension '{dim}' did not have a match in either " f"the input spec '{input_spec}' or the output " f"spec '{output_spec}'. For this layer, the weight must " "be fully specified." ) if bias_axes is not None: num_left_elided = elided if left_elided else 0 idx_map = { char: output_shape[i + num_left_elided] for i, char in enumerate(output_spec) } for char in bias_axes: if char not in output_spec: raise ValueError( f"Bias dimension '{char}' was requested, but is not part " f"of the output spec '{output_spec}'" ) first_bias_location = min( [output_spec.find(char) for char in bias_axes] ) bias_output_spec = output_spec[first_bias_location:] bias_shape = [ idx_map[char] if char in bias_axes else 1 for char in bias_output_spec ] if not left_elided: for _ in range(elided): bias_shape.append(1) else: bias_shape = None return weight_shape, bias_shape, output_shape
keras-core/keras_core/layers/core/einsum_dense.py/0
{ "file_path": "keras-core/keras_core/layers/core/einsum_dense.py", "repo_id": "keras-core", "token_count": 5895 }
40
import numpy as np import pytest from keras_core import backend from keras_core import layers from keras_core import metrics from keras_core import models from keras_core import ops from keras_core import testing class LayerTest(testing.TestCase): def test_compute_output_spec(self): # Test that implementing compute_output_shape # is enough to make compute_output_spec work. # Case: single output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return input_shape layer = TestLayer() self.assertEqual( layer.compute_output_spec(backend.KerasTensor((2, 3))).shape, (2, 3) ) # Case: tuple output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return (input_shape, input_shape) layer = TestLayer() out = layer.compute_output_spec(backend.KerasTensor((2, 3))) self.assertIsInstance(out, tuple) self.assertEqual(len(out), 2) self.assertEqual(out[0].shape, (2, 3)) self.assertEqual(out[1].shape, (2, 3)) # Case: list output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return [input_shape, input_shape] layer = TestLayer() out = layer.compute_output_spec(backend.KerasTensor((2, 3))) self.assertIsInstance(out, list) self.assertEqual(len(out), 2) self.assertEqual(out[0].shape, (2, 3)) self.assertEqual(out[1].shape, (2, 3)) # Case: dict output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return {"1": input_shape, "2": input_shape} layer = TestLayer() out = layer.compute_output_spec(backend.KerasTensor((2, 3))) self.assertIsInstance(out, dict) self.assertEqual(len(out), 2) self.assertEqual(out["1"].shape, (2, 3)) self.assertEqual(out["2"].shape, (2, 3)) # Case: nested tuple output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return ( input_shape, (input_shape, input_shape), (input_shape, input_shape), ) layer = TestLayer() out = layer.compute_output_spec(backend.KerasTensor((2, 3))) self.assertIsInstance(out, tuple) self.assertEqual(len(out), 3) self.assertEqual(out[0].shape, (2, 3)) self.assertIsInstance(out[1], tuple) self.assertEqual(len(out[1]), 2) self.assertEqual(out[1][0].shape, (2, 3)) self.assertEqual(out[1][1].shape, (2, 3)) self.assertIsInstance(out[2], tuple) self.assertEqual(len(out[2]), 2) self.assertEqual(out[2][0].shape, (2, 3)) self.assertEqual(out[2][1].shape, (2, 3)) # Case: nested dict output class TestLayer(layers.Layer): def call(self, x): assert False # Should never be called. def compute_output_shape(self, input_shape): return { "1": input_shape, "2": {"11": input_shape, "22": input_shape}, } layer = TestLayer() out = layer.compute_output_spec(backend.KerasTensor((2, 3))) self.assertIsInstance(out, dict) self.assertEqual(len(out), 2) self.assertEqual(out["1"].shape, (2, 3)) self.assertIsInstance(out["2"], dict) self.assertEqual(len(out["2"]), 2) self.assertEqual(out["2"]["11"].shape, (2, 3)) self.assertEqual(out["2"]["22"].shape, (2, 3)) def test_positional_arg_error(self): class SomeLayer(layers.Layer): def call(self, x, bool_arg): if bool_arg: return x return x + 1 x = backend.KerasTensor(shape=(2, 3), name="x") with self.assertRaisesRegex( ValueError, "Only input tensors may be passed as" ): SomeLayer()(x, True) # This works SomeLayer()(x, bool_arg=True) def test_rng_seed_tracking(self): class RNGLayer(layers.Layer): def __init__(self): super().__init__() self.seed_gen = backend.random.SeedGenerator(seed=1337) def call(self, x): return x * backend.random.normal(x.shape, seed=self.seed_gen) layer = RNGLayer() self.assertEqual(layer.variables, [layer.seed_gen.state]) self.assertAllClose(layer.variables[0], [1337, 0]) layer(np.ones((3, 4))) self.assertAllClose(layer.variables[0], [1337, 1]) # Test tracking in list attributes. class RNGListLayer(layers.Layer): def __init__(self): super().__init__() self.seed_gens = [] self.seed_gens.append(backend.random.SeedGenerator(seed=1)) self.seed_gens.append(backend.random.SeedGenerator(seed=10)) def call(self, x): x = x * backend.random.normal(x.shape, seed=self.seed_gens[0]) x = x * backend.random.normal(x.shape, seed=self.seed_gens[1]) return x layer = RNGListLayer() self.assertEqual( layer.variables, [layer.seed_gens[0].state, layer.seed_gens[1].state], ) self.assertAllClose(layer.variables[0], [1, 0]) self.assertAllClose(layer.variables[1], [10, 0]) layer(np.ones((3, 4))) self.assertAllClose(layer.variables[0], [1, 1]) self.assertAllClose(layer.variables[1], [10, 1]) def test_layer_tracking(self): class NestedLayer(layers.Layer): def __init__(self, units): super().__init__() self.dense1 = layers.Dense(units) self.layer_dict = { "dense2": layers.Dense(units), } self.layer_list = [layers.Dense(units)] self.units = units def build(self, input_shape): self.layer_list.append(layers.Dense(self.units)) def call(self, x): x = self.dense1(x) x = self.layer_dict["dense2"](x) x = self.layer_list[0](x) x = self.layer_list[1](x) return x class DoubleNestedLayer(layers.Layer): def __init__(self, units): super().__init__() self.inner_layer = NestedLayer(units) def call(self, x): return self.inner_layer(x) layer = NestedLayer(3) layer.build((1, 3)) self.assertLen(layer._layers, 4) layer(np.zeros((1, 3))) self.assertLen(layer.weights, 8) layer = DoubleNestedLayer(3) self.assertLen(layer._layers, 1) layer(np.zeros((1, 3))) self.assertLen(layer.inner_layer.weights, 8) self.assertLen(layer.weights, 8) def test_metric_tracking(self): class LayerWithMetric(layers.Layer): def __init__(self, units): super().__init__() self.dense = layers.Dense(units) self.metric = metrics.MeanSquaredError(name="my_metric") def build(self, input_shape): self.dense.build(input_shape) def call(self, x): return self.dense(x) class NestedLayerWithMetric(layers.Layer): def __init__(self, units): super().__init__() self.layer_with_metric = LayerWithMetric(units) self.metric = metrics.MeanSquaredError(name="my_metric") def build(self, input_shape): self.layer_with_metric.build(input_shape) def call(self, x): return self.layer_with_metric(x) layer = LayerWithMetric(3) layer.build((1, 3)) self.assertLen(layer.metrics_variables, 2) self.assertLen(layer.trainable_variables, 2) self.assertLen(layer.non_trainable_variables, 0) layer = NestedLayerWithMetric(3) layer.build((1, 3)) self.assertLen(layer.metrics_variables, 4) self.assertLen(layer.trainable_variables, 2) self.assertLen(layer.non_trainable_variables, 0) def test_build_on_call(self): class LayerWithUnbuiltState(layers.Layer): def __init__(self, units): super().__init__() self.dense1 = layers.Dense(units) def call(self, x): return self.dense1(x) layer = LayerWithUnbuiltState(2) layer(backend.KerasTensor((3, 4))) self.assertLen(layer.weights, 2) class KwargsLayerWithUnbuiltState(layers.Layer): def __init__(self, units): super().__init__() self.dense1 = layers.Dense(units) self.dense2 = layers.Dense(units) def call(self, x1, x2): return self.dense1(x1) + self.dense2(x2) layer = KwargsLayerWithUnbuiltState(2) layer(backend.KerasTensor((3, 4)), backend.KerasTensor((3, 4))) self.assertLen(layer.weights, 4) layer = KwargsLayerWithUnbuiltState(2) layer(x1=backend.KerasTensor((3, 4)), x2=backend.KerasTensor((3, 4))) self.assertLen(layer.weights, 4) def test_activity_regularization(self): class ActivityRegularizer(layers.Layer): def call(self, x): return x layer = ActivityRegularizer(activity_regularizer="l1") layer(np.ones((1,))) self.assertLen(layer.losses, 1) self.assertAllClose(layer.losses[0], 0.01) # losses are reset upon call layer(np.ones((1,))) self.assertLen(layer.losses, 1) self.assertAllClose(layer.losses[0], 0.01) # KerasTensors are no op layer = ActivityRegularizer(activity_regularizer="l1") layer(layers.Input(batch_shape=(2, 2))) self.assertLen(layer.losses, 0) @pytest.mark.requires_trainable_backend def test_add_loss(self): class LossLayer(layers.Layer): def call(self, x): self.add_loss(ops.sum(x)) return x layer = LossLayer() layer(np.ones((1,))) self.assertLen(layer.losses, 1) self.assertAllClose(layer.losses[0], 1.0) # losses are reset upon call layer = LossLayer() layer(np.ones((1,))) self.assertLen(layer.losses, 1) self.assertAllClose(layer.losses[0], 1.0) # It works inside a model model = models.Sequential([layer]) model(np.ones((1,))) self.assertLen(model.losses, 1) self.assertAllClose(model.losses[0], 1.0) def test_training_arg_value_resolution(self): # Check that even if `training` is not passed # to an inner layer, the outer value gets propagated # in __call__. class TrainingLayer(layers.Layer): def __init__(self): super().__init__() self.dp = layers.Dropout(0.9) def call(self, x, training=False): return self.dp(x) layer = TrainingLayer() x = np.ones((4, 4)) y = layer(x) self.assertEqual(ops.min(y), 1) y = layer(x, training=True) self.assertEqual(ops.min(y), 0) # Check that it still works one level deeper. class WrappedTrainingLayer(layers.Layer): def __init__(self): super().__init__() self.dp = TrainingLayer() def call(self, x, training=False): return self.dp(x) layer = WrappedTrainingLayer() x = np.ones((4, 4)) y = layer(x) self.assertEqual(ops.min(y), 1) y = layer(x, training=True) self.assertEqual(ops.min(y), 0) # Check that if `training` is passed # to an inner layer in call(), the explicitly # passed value is what the layer sees. class TrainingLayerExplicit(layers.Layer): def __init__(self): super().__init__() self.dp = layers.Dropout(0.9) def call(self, x, training=False): return self.dp(x, training=True) layer = TrainingLayerExplicit() x = np.ones((4, 4)) y = layer(x, training=False) self.assertEqual(ops.min(y), 0) # Test that layer interruption does not cause # the call context to linger class BadLayer(layers.Layer): def call(self, x, training=False): raise RuntimeError("oops!") x = np.ones((4, 4)) layer = BadLayer() try: # training=True will be recorded # in the call context layer(x, training=True) except RuntimeError: pass layer = TrainingLayer() # But this layer call should not see it y = layer(x) self.assertEqual(ops.min(y), 1) @pytest.mark.skipif( backend.backend() == "torch", reason="Some torch ops not implemented for float16 on CPU.", ) def test_mixed_precision(self): x = np.ones((4, 4)) layer = layers.Dense(2, dtype="float16") y = layer(x) self.assertEqual(layer.compute_dtype, "float16") self.assertEqual(layer.variable_dtype, "float16") self.assertEqual(backend.standardize_dtype(y.dtype), "float16") layer = layers.Dense(2, dtype="mixed_float16") y = layer(x) self.assertEqual(layer.compute_dtype, "float16") self.assertEqual(layer.variable_dtype, "float32") self.assertEqual(backend.standardize_dtype(y.dtype), "float16") self.assertEqual(layer.kernel.dtype, "float32") @pytest.mark.skipif( backend.backend() == "torch", reason="Some torch ops not implemented for float16 on CPU.", ) def test_autocast(self): assertEqual = self.assertEqual # A layer with a int dtype (some preprocessing layers do this). class InnerLayerOne(layers.Layer): def __init__(self): super().__init__(dtype="int") self.v = self.add_weight( shape=(), initializer="ones", trainable=True, dtype="float32", ) self.built = True def call(self, x): # Should not autocast. assertEqual(backend.standardize_dtype(self.v.dtype), "float32") return ops.cast(x, "float32") + self.v # A layer that is explicitly full precision. class InnerLayerTwo(layers.Layer): def __init__(self): super().__init__(dtype="float32") self.v = self.add_weight( shape=(), initializer="ones", trainable=True, ) self.built = True def call(self, x): # Should not autocast. assertEqual(backend.standardize_dtype(self.v.dtype), "float32") return x + self.v # A layer that is explicitly mixed precision with inner layers. class MixedPrecisionLayer(layers.Layer): def __init__(self): super().__init__(dtype="mixed_float16") self.v = self.add_weight( shape=(), initializer="ones", trainable=True, ) self.inner_one = InnerLayerOne() self.inner_two = InnerLayerTwo() self.built = True def call(self, x): # Should autocast. assertEqual(backend.standardize_dtype(self.v.dtype), "float16") return self.inner_two(self.inner_one(x + self.v)) layer = MixedPrecisionLayer() y = layer(np.array(0.0)) self.assertEqual(y, 3.0) @pytest.mark.skipif( backend.backend() == "numpy", reason="Numpy backend does not support masking.", ) def test_masking(self): class BasicMaskedLayer(layers.Layer): def __init__(self): super().__init__() self.supports_masking = True def call(self, x, mask=None): assert mask is not None return x layer = BasicMaskedLayer() x = backend.numpy.ones((4, 4)) x._keras_mask = backend.numpy.ones((4,)) layer(x) layer(backend.numpy.ones((4, 4)), mask=backend.numpy.ones((4,))) class NestedInputMaskedLayer(layers.Layer): def __init__(self): super().__init__() self.supports_masking = True def call(self, x, mask=None): assert isinstance(x, list) assert len(x) == 2 assert isinstance(mask, list) assert len(mask) == 2 return x layer = NestedInputMaskedLayer() x1 = backend.numpy.ones((4, 4)) x1._keras_mask = backend.numpy.ones((4,)) x2 = backend.numpy.ones((4, 4)) x2._keras_mask = backend.numpy.ones((4,)) layer([x1, x2]) layer( [backend.numpy.ones((4, 4)), backend.numpy.ones((4, 4))], mask=[backend.numpy.ones((4,)), backend.numpy.ones((4,))], ) class PositionalInputsMaskedLayer(layers.Layer): def __init__(self): super().__init__() self.supports_masking = True def call(self, x1, x2, x1_mask=None, x2_mask=None): assert x1_mask is not None assert x2_mask is not None return x1 + x2 layer = PositionalInputsMaskedLayer() layer(x1, x2) layer(x1=x1, x2=x2) class PositionalNestedInputsMaskedLayer(layers.Layer): def __init__(self): super().__init__() self.supports_masking = True def call(self, x1, x2, x1_mask=None, x2_mask=None): assert isinstance(x1, tuple) assert x1_mask is not None assert x2_mask is not None assert isinstance(x1_mask, tuple) return x1[0] + x1[1] + x2 layer = PositionalNestedInputsMaskedLayer() x1_1 = backend.numpy.ones((4, 4)) x1_1._keras_mask = backend.numpy.ones((4,)) x1_2 = backend.numpy.ones((4, 4)) x1_2._keras_mask = backend.numpy.ones((4,)) x2 = backend.numpy.ones((4, 4)) x2._keras_mask = backend.numpy.ones((4,)) layer((x1_1, x1_2), x2) layer(x1=(x1_1, x1_2), x2=x2) def test_stateless_call(self): class TestLayer(layers.Layer): def __init__(self): super().__init__() self._seed_generator = backend.random.SeedGenerator(1337) self.ntw = self.add_weight( shape=(), initializer="zeros", trainable=False, ) self.tw = self.add_weight( shape=(), initializer="zeros", trainable=True, ) self.built = True def call(self, x): x = backend.convert_to_tensor(x, dtype="float32") self.add_loss(ops.sum(x)) self.ntw.assign(ops.sum(x)) x = x + backend.random.normal( shape=(), seed=self._seed_generator ) return x + self.tw + self.ntw data = np.random.random((3, 4)) layer = TestLayer() out = layer(data) layer1 = TestLayer() out1 = layer1(data) # Check that the layer is in fact deterministic self.assertAllClose(out, out1) # Test stateless_call correctness layer2 = TestLayer() trainable_variables = layer2.trainable_variables non_trainable_variables = layer2.non_trainable_variables out2, non_trainable_variables = layer2.stateless_call( trainable_variables, non_trainable_variables, data ) self.assertAllClose(out1, out2) self.assertEqual( len(layer1.non_trainable_variables), len(non_trainable_variables) ) for ref_v, v in zip( layer1.non_trainable_variables, non_trainable_variables ): self.assertAllClose(ref_v, v) # Test with loss collection layer3 = TestLayer() trainable_variables = layer3.trainable_variables non_trainable_variables = layer3.non_trainable_variables out3, non_trainable_variables, losses = layer3.stateless_call( trainable_variables, non_trainable_variables, data, return_losses=True, ) self.assertAllClose(out1, out3) for ref_v, v in zip( layer1.non_trainable_variables, non_trainable_variables ): self.assertAllClose(ref_v, v) for ref_loss, loss in zip(layer1.losses, losses): self.assertAllClose(ref_loss, loss) def test_trainable_setting(self): class NonTrainableWeightsLayer(layers.Layer): def build(self, _): self.w1 = self.add_weight( shape=(), initializer="ones", trainable=True, ) self.w2 = self.add_weight( shape=(), initializer="ones", trainable=False, ) self.seed = backend.random.SeedGenerator(123) def call(self, inputs): return inputs class NestedNonTrainableWeightsLayer(layers.Layer): def build(self, _): self.w1 = self.add_weight( shape=(), initializer="ones", trainable=True, ) self.w2 = self.add_weight( shape=(), initializer="ones", trainable=False, ) self.nested = NonTrainableWeightsLayer() self.nested.build(None) def call(self, inputs): return inputs layer = NestedNonTrainableWeightsLayer() layer.build(None) self.assertEqual(len(layer.trainable_weights), 2) self.assertEqual(len(layer.trainable_variables), 2) self.assertEqual(len(layer.non_trainable_weights), 2) self.assertEqual(len(layer.non_trainable_variables), 3) layer.trainable = False self.assertEqual(len(layer.trainable_weights), 0) self.assertEqual(len(layer.trainable_variables), 0) self.assertEqual(len(layer.non_trainable_weights), 4) self.assertEqual(len(layer.non_trainable_variables), 5) self.assertFalse(layer.w1.trainable) self.assertFalse(layer.nested.w1.trainable) layer.trainable = True self.assertEqual(len(layer.trainable_weights), 2) self.assertEqual(len(layer.trainable_variables), 2) self.assertEqual(len(layer.non_trainable_weights), 2) self.assertEqual(len(layer.non_trainable_variables), 3) self.assertTrue(layer.w1.trainable) self.assertTrue(layer.nested.w1.trainable) layer = NestedNonTrainableWeightsLayer(trainable=False) layer.build(None) self.assertEqual(len(layer.trainable_weights), 0) self.assertEqual(len(layer.trainable_variables), 0) self.assertEqual(len(layer.non_trainable_weights), 4) self.assertEqual(len(layer.non_trainable_variables), 5) layer.trainable = True self.assertEqual(len(layer.trainable_weights), 2) self.assertEqual(len(layer.trainable_variables), 2) self.assertEqual(len(layer.non_trainable_weights), 2) self.assertEqual(len(layer.non_trainable_variables), 3) def test_build_signature_errors(self): class NoShapeSuffix(layers.Layer): def build(self, foo_shape, bar): self.built = True def call(self, foo, bar): return foo + bar class NonMatchingArgument(layers.Layer): def build(self, foo_shape, baz_shape): self.built = True def call(self, foo, bar): return foo[:, 0] + bar[:, 0] class MatchingArguments(layers.Layer): def build(self, bar_shape, foo_shape): self.foo_shape = foo_shape self.bar_shape = bar_shape self.built = True def call(self, foo, bar): return foo[:, 0] + bar[:, 0] class SubsetArguments(layers.Layer): def build(self, baz_shape, foo_shape): self.foo_shape = foo_shape self.baz_shape = baz_shape self.built = True def call(self, foo, bar=None, baz=None): return foo[:, 0] + bar[:, 0] + baz[:, 0] class SingleArgument(layers.Layer): def build(self, anything_whatsoever): self.foo_shape = anything_whatsoever self.built = True def call(self, foo, bar): return foo[:, 0] + bar[:, 0] foo = backend.numpy.ones((4, 1)) bar = backend.numpy.ones((4, 2)) baz = backend.numpy.ones((4, 3)) with self.assertRaisesRegex( ValueError, r"argument `bar`, which does not end in `_shape`", ): layer = NoShapeSuffix() layer(foo, bar) with self.assertRaisesRegex( ValueError, r"`baz_shape`, but `call\(\)` does not have argument `baz`", ): layer = NonMatchingArgument() layer(foo, bar) # Align by name when build and call arguments match. layer = MatchingArguments() layer(foo, bar) self.assertEqual(layer.foo_shape, foo.shape) self.assertEqual(layer.bar_shape, bar.shape) # Align by name when build supports a subset of call arguments. layer = SubsetArguments() layer(foo, bar, baz) self.assertEqual(layer.foo_shape, foo.shape) self.assertEqual(layer.baz_shape, baz.shape) # When build has only one argument, match the first call argument. layer = SingleArgument() layer(foo, bar) self.assertEqual(layer.foo_shape, foo.shape) def test_training_arg_not_specified(self): class NoTrainingSpecified(layers.Layer): def __init__(self): super().__init__() def build(self, input_shape): self.activation = layers.Activation("linear") def call(self, inputs): return self.activation(inputs) layer = NoTrainingSpecified() inputs = ops.random.uniform(shape=(1, 100, 100, 3)) layer(inputs, training=True) def test_tracker_locking(self): class BadLayer(layers.Layer): def call(self, x): self.w = self.add_weight(initializer="zeros", shape=()) return x layer = BadLayer() with self.assertRaisesRegex( ValueError, "cannot add new elements of state", ): layer(np.random.random((3, 2))) def test_init_after_state_tracking(self): class MyLayer(layers.Layer): def __init__(self): self.some_attr = True self.w = backend.Variable(np.random.random((2,))) super().__init__() layer = MyLayer() self.assertEqual(len(layer.weights), 1)
keras-core/keras_core/layers/layer_test.py/0
{ "file_path": "keras-core/keras_core/layers/layer_test.py", "repo_id": "keras-core", "token_count": 14562 }
41
import numpy as np import pytest from keras_core import constraints from keras_core import layers from keras_core import regularizers from keras_core import testing class GroupNormalizationTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_groupnorm(self): self.run_layer_test( layers.GroupNormalization, init_kwargs={ "gamma_regularizer": regularizers.L2(0.01), "beta_regularizer": regularizers.L2(0.01), }, input_shape=(3, 4, 32), expected_output_shape=(3, 4, 32), expected_num_trainable_weights=2, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=2, supports_masking=True, ) self.run_layer_test( layers.GroupNormalization, init_kwargs={ "groups": 4, "gamma_constraint": constraints.UnitNorm(), "beta_constraint": constraints.UnitNorm(), }, input_shape=(3, 4, 4), expected_output_shape=(3, 4, 4), expected_num_trainable_weights=2, expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=True, ) def test_undefined_dim_error(self): inputs = layers.Input(shape=(2, 2, 2, None)) layer = layers.GroupNormalization() with self.assertRaisesRegex( ValueError, ( "input tensor should have a defined dimension but the layer " "received an input with shape" ), ): _ = layer(inputs) def test_groups_bigger_than_dim_error(self): inputs = np.ones(shape=(2, 2, 2, 4)) layer = layers.GroupNormalization(groups=5) with self.assertRaisesRegex( ValueError, "cannot be more than the number of channels", ): _ = layer(inputs) def test_groups_not_a_multiple_of_dim_error(self): inputs = np.ones(shape=(2, 2, 2, 4)) layer = layers.GroupNormalization(groups=3) with self.assertRaisesRegex( ValueError, "must be a multiple of the number of channels", ): _ = layer(inputs) def test_groups_instance_norm(self): # GroupNormalization with groups=-1 will become InstanceNormalization instance_norm_layer_1 = layers.GroupNormalization( groups=-1, axis=-1, scale=False, center=False ) instance_norm_layer_2 = layers.GroupNormalization( groups=4, axis=-1, scale=False, center=False ) inputs = np.array([[[-1.0, 1.0, 0, 2.0], [1.0, 3.0, -4, -2.0]]]) outputs_1 = instance_norm_layer_1(inputs) outputs_2 = instance_norm_layer_2(inputs) self.assertAllClose(outputs_1, outputs_2) def test_correctness_instance_norm(self): instance_norm_layer = layers.GroupNormalization( groups=4, axis=-1, scale=False, center=False ) inputs = np.array([[[-1.0, 1.0, 0, 2.0], [1.0, 3.0, -4, -2.0]]]) expected_instance_norm_output = np.array( [[[-1.0, -1.0, 1.0, 1.0], [1.0, 1.0, -1.0, -1.0]]] ) self.assertAllClose( instance_norm_layer(inputs), expected_instance_norm_output, atol=1e-3, ) def test_correctness_1d(self): layer_with_1_group = layers.GroupNormalization( groups=1, axis=-1, scale=False, center=False ) layer_with_2_groups = layers.GroupNormalization( groups=2, axis=1, scale=False, center=False ) inputs = np.array([[-1.0, -1.0, 1.0, 1.0, 2.0, 2.0, 0, -2.0]]) expected_output_1_group = np.array( [[-0.898, -0.898, 0.539, 0.539, 1.257, 1.257, -0.180, -1.616]], ) self.assertAllClose( layer_with_1_group(inputs), expected_output_1_group, atol=1e-3, ) expected_output_2_groups = np.array( [[-1.0, -1.0, 1.0, 1.0, 0.904, 0.904, -0.301, -1.507]] ) self.assertAllClose( layer_with_2_groups(inputs), expected_output_2_groups, atol=1e-3, ) def test_correctness_2d(self): layer_with_1_group = layers.GroupNormalization( groups=1, axis=-1, scale=False, center=False ) layer_with_2_groups = layers.GroupNormalization( groups=2, axis=2, scale=False, center=False ) inputs = np.array([[[-1.0, -1.0, 2.0, 2.0], [1.0, 1.0, 0, -2.0]]]) expected_output_1_group = np.array( [[[-0.898, -0.898, 1.257, 1.257], [0.539, 0.539, -0.180, -1.616]]] ) self.assertAllClose( layer_with_1_group(inputs), expected_output_1_group, atol=1e-3, ) expected_output_2_groups = np.array( [[[-1.0, -1.0, 0.904, 0.904], [1.0, 1.0, -0.301, -1.507]]] ) self.assertAllClose( layer_with_2_groups(inputs), expected_output_2_groups, atol=1e-3, ) def test_broadcasting_2d_channels_first(self): x = np.arange(16).reshape((1, 4, 2, 2)).astype("float32") x = layers.GroupNormalization(groups=2, axis=1)(x) self.assertAllClose( x, np.array( [ [ [[-1.5274, -1.0910], [-0.6546, -0.2182]], [[0.2182, 0.6546], [1.0910, 1.5274]], [[-1.5274, -1.0910], [-0.6546, -0.2182]], [[0.2182, 0.6546], [1.0910, 1.5274]], ] ] ), atol=1e-3, )
keras-core/keras_core/layers/normalization/group_normalization_test.py/0
{ "file_path": "keras-core/keras_core/layers/normalization/group_normalization_test.py", "repo_id": "keras-core", "token_count": 3207 }
42