repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
keras
keras-master/keras/api/create_python_api_wrapper.py
# 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. # ============================================================================== """Thin wrapper to call TensorFlow's API generation script. This file exists to provide a main function for the py_binary in the API generation genrule. It just calls the main function for the actual API generation script in TensorFlow. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import keras # pylint: disable=unused-import from tensorflow.python.tools.api.generator import create_python_api if __name__ == '__main__': create_python_api.main()
1,211
38.096774
80
py
keras
keras-master/keras/api/tests/api_compatibility_test.py
# Lint as: python3 # 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. # # ============================================================================== """Keras API compatibility tests. This test ensures all changes to the public API of Keras are intended. If this test fails, it means a change has been made to the public API. Backwards incompatible changes are not allowed. You can run the test with "--update_goldens" flag set to "True" to update goldens when making changes to the public Keras python API. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import argparse import os import re import sys import six from google.protobuf import message from google.protobuf import text_format from tensorflow.python.lib.io import file_io from tensorflow.python.platform import tf_logging as logging from tensorflow.tools.api.lib import api_objects_pb2 from tensorflow.tools.api.lib import python_object_to_proto_visitor from tensorflow.tools.common import public_api from tensorflow.tools.common import traverse # FLAGS defined at the bottom: FLAGS = None # DEFINE_boolean, update_goldens, default False: _UPDATE_GOLDENS_HELP = """ Update stored golden files if API is updated. WARNING: All API changes have to be authorized by TensorFlow leads. """ # DEFINE_boolean, verbose_diffs, default True: _VERBOSE_DIFFS_HELP = """ If set to true, print line by line diffs on all libraries. If set to false, only print which libraries have differences. """ # Initialized with _InitPathConstants function below. _API_GOLDEN_FOLDER_V1 = None _API_GOLDEN_FOLDER_V2 = None def _InitPathConstants(): global _API_GOLDEN_FOLDER_V1 global _API_GOLDEN_FOLDER_V2 root_golden_path_v2 = os.path.join( tf.compat.v1.resource_loader.get_data_files_path(), '..', 'golden', 'v2', 'tensorflow.keras.pbtxt') if FLAGS.update_goldens: root_golden_path_v2 = os.path.realpath(root_golden_path_v2) # Get API directories based on the root golden file. This way # we make sure to resolve symbolic links before creating new files. _API_GOLDEN_FOLDER_V2 = os.path.dirname(root_golden_path_v2) _API_GOLDEN_FOLDER_V1 = os.path.normpath( os.path.join(_API_GOLDEN_FOLDER_V2, '..', 'v1')) _TEST_README_FILE = os.path.join( tf.compat.v1.resource_loader.get_data_files_path(), 'README.txt') _UPDATE_WARNING_FILE = os.path.join( tf.compat.v1.resource_loader.get_data_files_path(), 'API_UPDATE_WARNING.txt') def _KeyToFilePath(key, api_version): """From a given key, construct a filepath. Filepath will be inside golden folder for api_version. Args: key: a string used to determine the file path api_version: a number indicating the tensorflow API version, e.g. 1 or 2. Returns: A string of file path to the pbtxt file which describes the public API """ def _ReplaceCapsWithDash(matchobj): match = matchobj.group(0) return '-%s' % (match.lower()) case_insensitive_key = re.sub('([A-Z]{1})', _ReplaceCapsWithDash, six.ensure_str(key)) api_folder = ( _API_GOLDEN_FOLDER_V2 if api_version == 2 else _API_GOLDEN_FOLDER_V1) return os.path.join(api_folder, '%s.pbtxt' % case_insensitive_key) def _FileNameToKey(filename): """From a given filename, construct a key we use for api objects.""" def _ReplaceDashWithCaps(matchobj): match = matchobj.group(0) return match[1].upper() base_filename = os.path.basename(filename) base_filename_without_ext = os.path.splitext(base_filename)[0] api_object_key = re.sub('((-[a-z]){1})', _ReplaceDashWithCaps, six.ensure_str(base_filename_without_ext)) return api_object_key def _VerifyNoSubclassOfMessageVisitor(path, parent, unused_children): """A Visitor that crashes on subclasses of generated proto classes.""" # If the traversed object is a proto Message class if not (isinstance(parent, type) and issubclass(parent, message.Message)): return if parent is message.Message: return # Check that it is a direct subclass of Message. if message.Message not in parent.__bases__: raise NotImplementedError( 'Object tf.%s is a subclass of a generated proto Message. ' 'They are not yet supported by the API tools.' % path) def _FilterGoldenProtoDict(golden_proto_dict, omit_golden_symbols_map): """Filter out golden proto dict symbols that should be omitted.""" if not omit_golden_symbols_map: return golden_proto_dict filtered_proto_dict = dict(golden_proto_dict) for key, symbol_list in six.iteritems(omit_golden_symbols_map): api_object = api_objects_pb2.TFAPIObject() api_object.CopyFrom(filtered_proto_dict[key]) filtered_proto_dict[key] = api_object module_or_class = None if api_object.HasField('tf_module'): module_or_class = api_object.tf_module elif api_object.HasField('tf_class'): module_or_class = api_object.tf_class if module_or_class is not None: for members in (module_or_class.member, module_or_class.member_method): filtered_members = [m for m in members if m.name not in symbol_list] # Two steps because protobuf repeated fields disallow slice assignment. del members[:] members.extend(filtered_members) return filtered_proto_dict class ApiCompatibilityTest(tf.test.TestCase): def __init__(self, *args, **kwargs): super(ApiCompatibilityTest, self).__init__(*args, **kwargs) self._update_golden_warning = file_io.read_file_to_string( _UPDATE_WARNING_FILE) self._test_readme_message = file_io.read_file_to_string(_TEST_README_FILE) def _AssertProtoDictEquals(self, expected_dict, actual_dict, verbose=False, update_goldens=False, additional_missing_object_message='', api_version=2): """Diff given dicts of protobufs and report differences a readable way. Args: expected_dict: a dict of TFAPIObject protos constructed from golden files. actual_dict: a ict of TFAPIObject protos constructed by reading from the TF package linked to the test. verbose: Whether to log the full diffs, or simply report which files were different. update_goldens: Whether to update goldens when there are diffs found. additional_missing_object_message: Message to print when a symbol is missing. api_version: TensorFlow API version to test. """ diffs = [] verbose_diffs = [] expected_keys = set(expected_dict.keys()) actual_keys = set(actual_dict.keys()) only_in_expected = expected_keys - actual_keys only_in_actual = actual_keys - expected_keys all_keys = expected_keys | actual_keys # This will be populated below. updated_keys = [] for key in all_keys: diff_message = '' verbose_diff_message = '' # First check if the key is not found in one or the other. if key in only_in_expected: diff_message = 'Object %s expected but not found (removed). %s' % ( key, additional_missing_object_message) verbose_diff_message = diff_message elif key in only_in_actual: diff_message = 'New object %s found (added).' % key verbose_diff_message = diff_message else: # Do not truncate diff self.maxDiff = None # pylint: disable=invalid-name # Now we can run an actual proto diff. try: self.assertProtoEquals(expected_dict[key], actual_dict[key]) except AssertionError as e: updated_keys.append(key) diff_message = 'Change detected in python object: %s.' % key verbose_diff_message = str(e) # All difference cases covered above. If any difference found, add to the # list. if diff_message: diffs.append(diff_message) verbose_diffs.append(verbose_diff_message) # If diffs are found, handle them based on flags. if diffs: diff_count = len(diffs) logging.error(self._test_readme_message) logging.error('%d differences found between API and golden.', diff_count) if update_goldens: # Write files if requested. logging.warning(self._update_golden_warning) # If the keys are only in expected, some objects are deleted. # Remove files. for key in only_in_expected: filepath = _KeyToFilePath(key, api_version) tf.io.gfile.remove(filepath) # If the files are only in actual (current library), these are new # modules. Write them to files. Also record all updates in files. for key in only_in_actual | set(updated_keys): filepath = _KeyToFilePath(key, api_version) file_io.write_string_to_file( filepath, text_format.MessageToString(actual_dict[key])) else: # Include the actual differences to help debugging. for d, verbose_d in zip(diffs, verbose_diffs): logging.error(' %s', d) logging.error(' %s', verbose_d) # Fail if we cannot fix the test by updating goldens. self.fail('%d differences found between API and golden.' % diff_count) else: logging.info('No differences found between API and golden.') def _checkBackwardsCompatibility(self, root, golden_file_patterns, api_version, additional_private_map=None, omit_golden_symbols_map=None): # Extract all API stuff. visitor = python_object_to_proto_visitor.PythonObjectToProtoVisitor( default_path='tensorflow.keras') public_api_visitor = public_api.PublicAPIVisitor(visitor) if additional_private_map: public_api_visitor.private_map.update(additional_private_map) public_api_visitor.set_root_name('tf.keras') traverse.traverse(root, public_api_visitor) proto_dict = visitor.GetProtos() # Read all golden files. golden_file_list = tf.compat.v1.gfile.Glob(golden_file_patterns) def _ReadFileToProto(filename): """Read a filename, create a protobuf from its contents.""" ret_val = api_objects_pb2.TFAPIObject() text_format.Merge(file_io.read_file_to_string(filename), ret_val) return ret_val golden_proto_dict = { _FileNameToKey(filename): _ReadFileToProto(filename) for filename in golden_file_list } golden_proto_dict = _FilterGoldenProtoDict(golden_proto_dict, omit_golden_symbols_map) # Diff them. Do not fail if called with update. # If the test is run to update goldens, only report diffs but do not fail. self._AssertProtoDictEquals( golden_proto_dict, proto_dict, verbose=FLAGS.verbose_diffs, update_goldens=FLAGS.update_goldens, api_version=api_version) def testAPIBackwardsCompatibility(self): api_version = 1 if hasattr(tf, '_major_api_version') and tf._major_api_version == 2: api_version = 2 golden_file_patterns = [ os.path.join( tf.compat.v1.resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version))] self._checkBackwardsCompatibility( tf.keras, golden_file_patterns, api_version, # Skip compat.v1 and compat.v2 since they are validated # in separate tests. additional_private_map={'tf.compat': ['v1', 'v2']}, omit_golden_symbols_map={}) def testAPIBackwardsCompatibilityV1(self): api_version = 1 golden_file_patterns = os.path.join( tf.compat.v1.resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version)) self._checkBackwardsCompatibility( tf.compat.v1.keras, golden_file_patterns, api_version, additional_private_map={ 'tf': ['pywrap_tensorflow'], 'tf.compat': ['v1', 'v2'], }, omit_golden_symbols_map={}) def testAPIBackwardsCompatibilityV2(self): api_version = 2 golden_file_patterns = [os.path.join( tf.compat.v1.resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version))] self._checkBackwardsCompatibility( tf.compat.v2.keras, golden_file_patterns, api_version, additional_private_map={'tf.compat': ['v1', 'v2']}, omit_golden_symbols_map={}) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--update_goldens', type=bool, default=False, help=_UPDATE_GOLDENS_HELP) parser.add_argument( '--verbose_diffs', type=bool, default=True, help=_VERBOSE_DIFFS_HELP) FLAGS, unparsed = parser.parse_known_args() _InitPathConstants() # Now update argv, so that unittest library does not get confused. sys.argv = [sys.argv[0]] + unparsed tf.test.main()
13,733
35.919355
80
py
keras
keras-master/keras/initializers/initializers_test.py
# 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 Keras initializers.""" import tensorflow.compat.v2 as tf import numpy as np from keras import backend from keras import combinations from keras import initializers from keras import models from keras import testing_utils from keras.engine import input_layer from keras.layers import core 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) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class KerasInitializersTest(tf.test.TestCase): def _runner(self, init, shape, target_mean=None, target_std=None, target_max=None, target_min=None): variable = backend.variable(init(shape)) output = backend.get_value(variable) # Test serialization (assumes deterministic behavior). config = init.get_config() reconstructed_init = init.__class__.from_config(config) variable = backend.variable(reconstructed_init(shape)) output_2 = backend.get_value(variable) self.assertAllClose(output, output_2, atol=1e-4) def test_uniform(self): tensor_shape = (9, 6, 7) with self.cached_session(): self._runner( initializers.RandomUniformV2(minval=-1, maxval=1, seed=124), tensor_shape, target_mean=0., target_max=1, target_min=-1) def test_normal(self): tensor_shape = (8, 12, 99) with self.cached_session(): self._runner( initializers.RandomNormalV2(mean=0, stddev=1, seed=153), tensor_shape, target_mean=0., target_std=1) def test_truncated_normal(self): tensor_shape = (12, 99, 7) with self.cached_session(): self._runner( initializers.TruncatedNormalV2(mean=0, stddev=1, seed=126), tensor_shape, target_mean=0., target_max=2, target_min=-2) def test_constant(self): tensor_shape = (5, 6, 4) with self.cached_session(): self._runner( initializers.ConstantV2(2.), tensor_shape, target_mean=2, target_max=2, target_min=2) def test_lecun_uniform(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, _ = _compute_fans(tensor_shape) std = np.sqrt(1. / fan_in) self._runner( initializers.LecunUniformV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_glorot_uniform(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, fan_out = _compute_fans(tensor_shape) std = np.sqrt(2. / (fan_in + fan_out)) self._runner( initializers.GlorotUniformV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_he_uniform(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, _ = _compute_fans(tensor_shape) std = np.sqrt(2. / fan_in) self._runner( initializers.HeUniformV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_lecun_normal(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, _ = _compute_fans(tensor_shape) std = np.sqrt(1. / fan_in) self._runner( initializers.LecunNormalV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_glorot_normal(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, fan_out = _compute_fans(tensor_shape) std = np.sqrt(2. / (fan_in + fan_out)) self._runner( initializers.GlorotNormalV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_he_normal(self): tensor_shape = (5, 6, 4, 2) with self.cached_session(): fan_in, _ = _compute_fans(tensor_shape) std = np.sqrt(2. / fan_in) self._runner( initializers.HeNormalV2(seed=123), tensor_shape, target_mean=0., target_std=std) def test_orthogonal(self): tensor_shape = (20, 20) with self.cached_session(): self._runner( initializers.OrthogonalV2(seed=123), tensor_shape, target_mean=0.) def test_identity(self): with self.cached_session(): tensor_shape = (3, 4, 5) with self.assertRaises(ValueError): self._runner( initializers.IdentityV2(), tensor_shape, target_mean=1. / tensor_shape[0], target_max=1.) tensor_shape = (3, 3) self._runner( initializers.IdentityV2(), tensor_shape, target_mean=1. / tensor_shape[0], target_max=1.) def test_zero(self): tensor_shape = (4, 5) with self.cached_session(): self._runner( initializers.ZerosV2(), tensor_shape, target_mean=0., target_max=0.) def test_one(self): tensor_shape = (4, 5) with self.cached_session(): self._runner( initializers.OnesV2(), tensor_shape, target_mean=1., target_max=1.) def test_default_random_uniform(self): ru = initializers.get('uniform') self.assertEqual(ru.minval, -0.05) self.assertEqual(ru.maxval, 0.05) def test_default_random_normal(self): rn = initializers.get('normal') self.assertEqual(rn.mean, 0.0) self.assertEqual(rn.stddev, 0.05) def test_default_truncated_normal(self): tn = initializers.get('truncated_normal') self.assertEqual(tn.mean, 0.0) self.assertEqual(tn.stddev, 0.05) def test_custom_initializer_saving(self): def my_initializer(shape, dtype=None): return tf.ones(shape, dtype=dtype) inputs = input_layer.Input((10,)) outputs = core.Dense(1, kernel_initializer=my_initializer)(inputs) model = models.Model(inputs, outputs) model2 = model.from_config( model.get_config(), custom_objects={'my_initializer': my_initializer}) self.assertEqual(model2.layers[1].kernel_initializer, my_initializer) @testing_utils.run_v2_only def test_load_external_variance_scaling_v2(self): external_serialized_json = { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'normal', 'mode': 'fan_avg', 'scale': 1.0, 'seed': None } } initializer = initializers.deserialize(external_serialized_json) self.assertEqual(initializer.distribution, 'truncated_normal') def test_partition(self): with self.cached_session(): partition_enabled_initializers = [ initializers.ZerosV2(), initializers.OnesV2(), initializers.RandomUniformV2(), initializers.RandomNormalV2(), initializers.TruncatedNormalV2(), initializers.LecunUniformV2(), initializers.GlorotUniformV2(), initializers.HeUniformV2() ] for initializer in partition_enabled_initializers: got = initializer( shape=(4, 2), partition_shape=(2, 2), partition_offset=(0, 0)) self.assertEqual(got.shape, (2, 2)) partition_forbidden_initializers = [ initializers.OrthogonalV2(), initializers.IdentityV2() ] for initializer in partition_forbidden_initializers: with self.assertRaisesRegex( ValueError, "initializer doesn't support partition-related arguments"): initializer( shape=(4, 2), partition_shape=(2, 2), partition_offset=(0, 0)) if __name__ == '__main__': tf.test.main()
8,888
30.409894
80
py
keras
keras-master/keras/initializers/initializers_v2.py
# 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 for TF 2.""" # pylint: disable=g-classes-have-attributes import math from keras import backend import tensorflow.compat.v2 as tf from tensorflow.python.ops import stateless_random_ops from tensorflow.python.util.tf_export import keras_export _PARTITION_SHAPE = 'partition_shape' _PARTITION_OFFSET = 'partition_offset' @keras_export('keras.initializers.Initializer') class Initializer: """Initializer base class: all 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. ``` Optionally, you an also implement the method `get_config` and the class method `from_config` in order to support serialization -- just like with any Keras object. Here's a simple example: a random normal initializer. ```python import tensorflow as tf class ExampleRandomNormal(tf.keras.initializers.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 configuration of the initializer 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: A `tf.keras.initializers.Initializer` instance. """ config.pop('dtype', None) return cls(**config) @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 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, `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_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] 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 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, `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_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] 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 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, `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. """ del kwargs return tf.constant( self.value, dtype=_get_dtype(dtype), shape=shape) def get_config(self): return {'value': self.value} @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 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. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. """ def __init__(self, minval=-0.05, maxval=0.05, seed=None): self.minval = minval self.maxval = maxval self.seed = seed self._random_generator = _RandomGenerator(seed) 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] return self._random_generator.random_uniform(shape, self.minval, self.maxval, dtype) 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 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. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. """ def __init__(self, mean=0.0, stddev=0.05, seed=None): self.mean = mean self.stddev = stddev self.seed = seed self._random_generator = _RandomGenerator(seed) 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] return self._random_generator.random_normal(shape, self.mean, self.stddev, dtype) 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 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. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. """ def __init__(self, mean=0.0, stddev=0.05, seed=None): self.mean = mean self.stddev = stddev self.seed = seed self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=None, **kwargs): """Returns a tensor object 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] return self._random_generator.truncated_normal(shape, self.mean, self.stddev, dtype) 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 capable of adapting its scale to the shape of weights 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 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" and "uniform". seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. """ def __init__(self, scale=1.0, mode='fan_in', distribution='truncated_normal', seed=None): if scale <= 0.: raise ValueError('`scale` must be positive float. ' f'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 = _RandomGenerator(seed) 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)) scale = self.scale fan_in, fan_out = _compute_fans(shape) if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] if self.mode == 'fan_in': scale /= max(1., fan_in) elif self.mode == 'fan_out': scale /= max(1., fan_out) else: scale /= max(1., (fan_in + fan_out) / 2.) if self.distribution == 'truncated_normal': # constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.) stddev = math.sqrt(scale) / .87962566103423978 return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype) elif self.distribution == 'untruncated_normal': stddev = math.sqrt(scale) return self._random_generator.random_normal(shape, 0.0, stddev, dtype) else: limit = math.sqrt(3.0 * scale) return self._random_generator.random_uniform(shape, -limit, limit, dtype) 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 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. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) ([pdf](https://arxiv.org/pdf/1312.6120.pdf)) """ def __init__(self, gain=1.0, seed=None): self.gain = gain self.seed = seed self._random_generator = _RandomGenerator(seed) 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)}.') # 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 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)}.') 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 Keras layer: >>> initializer = tf.keras.initializers.GlorotUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) """ def __init__(self, seed=None): super(GlorotUniform, self).__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 Keras layer: >>> initializer = tf.keras.initializers.GlorotNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) """ def __init__(self, seed=None): super(GlorotNormal, self).__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 Keras layer: >>> initializer = tf.keras.initializers.LecunNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. Used to seed the random generator. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017] (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) ([pdf] (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) """ def __init__(self, seed=None): super(LecunNormal, self).__init__( scale=1., 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 Keras layer: >>> initializer = tf.keras.initializers.LecunUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) """ def __init__(self, seed=None): super(LecunUniform, self).__init__( scale=1., 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 Keras layer: >>> initializer = tf.keras.initializers.HeNormal() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) """ def __init__(self, seed=None): super(HeNormal, self).__init__( scale=2., 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 Keras layer: >>> initializer = tf.keras.initializers.HeUniform() >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) Args: seed: A Python integer. An initializer created with a given seed will always produce the same random tensor for a given shape and dtype. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) """ def __init__(self, seed=None): super(HeUniform, self).__init__( scale=2., 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 class _RandomGenerator: """Random generator that selects appropriate random ops.""" def __init__(self, seed=None): super(_RandomGenerator, self).__init__() if seed is not None: # Stateless random ops requires 2-int seed. self.seed = [seed, 0] else: self.seed = None def random_normal(self, shape, mean=0.0, stddev=1, dtype=tf.float32): """A deterministic random normal if seed is passed.""" if self.seed: op = tf.random.stateless_normal else: op = tf.random.normal return op( shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) def random_uniform(self, shape, minval, maxval, dtype): """A deterministic random uniform if seed is passed.""" if self.seed: op = stateless_random_ops.stateless_random_uniform else: op = tf.random.uniform return op( shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed) def truncated_normal(self, shape, mean, stddev, dtype): """A deterministic truncated normal if seed is passed.""" if self.seed: op = tf.random.stateless_truncated_normal else: op = tf.random.truncated_normal return op( shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) 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): for kwarg in kwargs: allowed_kwargs = [_PARTITION_SHAPE, _PARTITION_OFFSET] if kwarg not in allowed_kwargs: raise TypeError(f'Unknown keyword arguments: {kwarg}. Allowed keyword ' f'arguments: {allowed_kwargs}.') elif not support_partition: raise ValueError(f'{cls_name} initializer doesn\'t support ' 'partition-related arguments.')
35,554
33.552964
162
py
keras
keras-master/keras/initializers/initializers_v1.py
# 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 for TF 1.""" # pylint:disable=g-classes-have-attributes import tensorflow.compat.v2 as tf from tensorflow.python.util.tf_export import keras_export _v1_zeros_initializer = tf.compat.v1.zeros_initializer _v1_ones_initializer = tf.compat.v1.ones_initializer _v1_constant_initializer = tf.compat.v1.constant_initializer _v1_variance_scaling_initializer = tf.compat.v1.variance_scaling_initializer _v1_orthogonal_initializer = tf.compat.v1.orthogonal_initializer _v1_identity = tf.compat.v1.initializers.identity _v1_glorot_uniform_initializer = tf.compat.v1.glorot_uniform_initializer _v1_glorot_normal_initializer = tf.compat.v1.glorot_normal_initializer keras_export(v1=['keras.initializers.Zeros', 'keras.initializers.zeros'], allow_multiple_exports=True)( _v1_zeros_initializer) keras_export(v1=['keras.initializers.Ones', 'keras.initializers.ones'], allow_multiple_exports=True)( _v1_ones_initializer) keras_export(v1=['keras.initializers.Constant', 'keras.initializers.constant'], allow_multiple_exports=True)( _v1_constant_initializer) keras_export(v1=['keras.initializers.VarianceScaling'], allow_multiple_exports=True)( _v1_variance_scaling_initializer) keras_export(v1=['keras.initializers.Orthogonal', 'keras.initializers.orthogonal'], allow_multiple_exports=True)(_v1_orthogonal_initializer) keras_export(v1=['keras.initializers.Identity', 'keras.initializers.identity'], allow_multiple_exports=True)(_v1_identity) keras_export(v1=['keras.initializers.glorot_uniform'], allow_multiple_exports=True)( _v1_glorot_uniform_initializer) keras_export(v1=['keras.initializers.glorot_normal'], allow_multiple_exports=True)( _v1_glorot_normal_initializer) @keras_export(v1=['keras.initializers.RandomNormal', 'keras.initializers.random_normal', 'keras.initializers.normal']) class RandomNormal(tf.compat.v1.random_normal_initializer): """Initializer that generates a normal distribution. 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 create random seeds. See `tf.compat.v1.set_random_seed` for behavior. dtype: Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. @compatibility(TF2) Although it is a legacy compat.v1 api, `tf.compat.v1.keras.initializers.RandomNormal` is compatible with eager execution and `tf.function`. To switch to native TF2, switch to using `tf.keras.initializers.RandomNormal` (not from `compat.v1`) and if you need to change the default dtype use `tf.keras.backend.set_floatx(float_dtype)` or pass the dtype when calling the initializer, rather than passing it when constructing the initializer. Random seed behavior: Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 intializer) #### Structural Mapping to Native TF2 Before: ```python initializer = tf.compat.v1.keras.initializers.RandomNormal( mean=mean, stddev=stddev, seed=seed, dtype=dtype) weight_one = tf.Variable(initializer(shape_one)) weight_two = tf.Variable(initializer(shape_two)) ``` After: ```python initializer = tf.keras.initializers.RandomNormal( mean=mean, # seed=seed, # Setting a seed in the native TF2 API # causes it to produce the same initializations # across multiple calls of the same initializer. stddev=stddev) weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) ``` #### How to Map Arguments | TF1 Arg Name | TF2 Arg Name | Note | | :---------------- | :-------------- | :------------------------- | | `mean` | `mean` | No change to defaults | | `stddev` | `stddev` | No change to defaults | | `seed` | `seed` | Different random number generation | : : : semantics (to change in a : : : : future version). If set, the TF2 version : : : : will use stateless random number : : : : generation which will produce the exact : : : : same initialization even across multiple : : : : calls of the initializer instance. the : : : : `compat.v1` version will generate new : : : : initializations each time. Do not set : : : : a seed if you need different : : : : initializations each time. Instead : : : : either set a global tf seed with : : : : `tf.random.set_seed` if you need : : : : determinism, or initialize each weight: : : : with a separate initializer instance : : : : and a different seed. : | `dtype` | `dtype` | The TF2 native api only takes it | : : : as a `__call__` arg, not a constructor arg. : | `partition_info` | - | (`__call__` arg in TF1) Not supported | #### Example of fixed-seed behavior differences `compat.v1` Fixed seed behavior: >>> initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=False> After: >>> initializer = tf.keras.initializers.TruncatedNormal(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=True> @end_compatibility """ def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=tf.float32): super(RandomNormal, self).__init__( mean=mean, stddev=stddev, seed=seed, dtype=dtype) @keras_export(v1=['keras.initializers.RandomUniform', 'keras.initializers.random_uniform', 'keras.initializers.uniform']) class RandomUniform(tf.compat.v1.random_uniform_initializer): """Initializer that generates tensors with a uniform distribution. Args: minval: A python scalar or a scalar tensor. Lower bound of the range of random values to generate. maxval: A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. seed: A Python integer. Used to create random seeds. See `tf.compat.v1.set_random_seed` for behavior. dtype: Default data type, used if no `dtype` argument is provided when calling the initializer. @compatibility(TF2) Although it is a legacy `compat.v1` api, `tf.compat.v1.keras.initializers.RandomUniform` is compatible with eager execution and `tf.function`. To switch to native TF2, switch to using `tf.keras.initializers.RandomUniform` (not from `compat.v1`) and if you need to change the default dtype use `tf.keras.backend.set_floatx(float_dtype)` or pass the dtype when calling the initializer, rather than passing it when constructing the initializer. Random seed behavior: Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 intializer) #### Structural Mapping to Native TF2 Before: ```python initializer = tf.compat.v1.keras.initializers.RandomUniform( minval=minval, maxval=maxval, seed=seed, dtype=dtype) weight_one = tf.Variable(initializer(shape_one)) weight_two = tf.Variable(initializer(shape_two)) ``` After: ```python initializer = tf.keras.initializers.RandomUniform( minval=minval, maxval=maxval, # seed=seed, # Setting a seed in the native TF2 API # causes it to produce the same initializations # across multiple calls of the same initializer. ) weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) ``` #### How to Map Arguments | TF1 Arg Name | TF2 Arg Name | Note | | :---------------- | :-------------- | :------------------------- | | `minval` | `minval` | No change to defaults | | `maxval` | `maxval` | No change to defaults | | `seed` | `seed` | Different random number generation | : : : semantics (to change in a : : : : future version). If set, the TF2 version : : : : will use stateless random number : : : : generation which will produce the exact : : : : same initialization even across multiple : : : : calls of the initializer instance. the : : : : `compat.v1` version will generate new : : : : initializations each time. Do not set : : : : a seed if you need different : : : : initializations each time. Instead : : : : either set a global tf seed with : : : `tf.random.set_seed` if you need : : : : determinism, or initialize each weight : : : : with a separate initializer instance : : : : and a different seed. : | `dtype` | `dtype` | The TF2 native api only takes it | : : : as a `__call__` arg, not a constructor arg. : | `partition_info` | - | (`__call__` arg in TF1) Not supported | #### Example of fixed-seed behavior differences `compat.v1` Fixed seed behavior: >>> initializer = tf.compat.v1.keras.initializers.RandomUniform(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=False> After: >>> initializer = tf.keras.initializers.RandomUniform(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=True> @end_compatibility """ def __init__(self, minval=-0.05, maxval=0.05, seed=None, dtype=tf.float32): super(RandomUniform, self).__init__( minval=minval, maxval=maxval, seed=seed, dtype=dtype) @keras_export(v1=['keras.initializers.TruncatedNormal', 'keras.initializers.truncated_normal']) class TruncatedNormal(tf.compat.v1.truncated_normal_initializer): """Initializer that generates a truncated normal distribution. These values are similar to values from a `random_normal_initializer` except that values more than two standard deviations from the mean are discarded and re-drawn. This is the recommended initializer for neural network weights and filters. 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 create random seeds. See `tf.compat.v1.set_random_seed` for behavior. dtype: Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. @compatibility(TF2) Although it is a legacy compat.v1 api, `tf.compat.v1.keras.initializers.TruncatedNormal` is compatible with eager execution and `tf.function`. To switch to native TF2, switch to using `tf.keras.initializers.TruncatedNormal` (not from `compat.v1`) and if you need to change the default dtype use `tf.keras.backend.set_floatx(float_dtype)` or pass the dtype when calling the initializer, rather than passing it when constructing the initializer. Random seed behavior: Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 intializer) #### Structural Mapping to Native TF2 Before: ```python initializer = tf.compat.v1.keras.initializers.TruncatedNormal( mean=mean, stddev=stddev, seed=seed, dtype=dtype) weight_one = tf.Variable(initializer(shape_one)) weight_two = tf.Variable(initializer(shape_two)) ``` After: ```python initializer = tf.keras.initializers.TruncatedNormal( mean=mean, # seed=seed, # Setting a seed in the native TF2 API # causes it to produce the same initializations # across multiple calls of the same initializer. stddev=stddev) weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) ``` #### How to Map Arguments | TF1 Arg Name | TF2 Arg Name | Note | | :---------------- | :-------------- | :------------------------- | | `mean` | `mean` | No change to defaults | | `stddev` | `stddev` | No change to defaults | | `seed` | `seed` | Different random number generation | : : : semantics (to change in a : : : : future version). If set, the TF2 version : : : : will use stateless random number : : : : generation which will produce the exact : : : : same initialization even across multiple : : : : calls of the initializer instance. the : : : : `compat.v1` version will generate new : : : : initializations each time. Do not set : : : : a seed if you need different : : : : initializations each time. Instead : : : : either set a global tf seed with : : : `tf.random.set_seed` if you need : : : : determinism, or initialize each weight : : : : with a separate initializer instance : : : : and a different seed. : | `dtype` | `dtype` | The TF2 native api only takes it | : : : as a `__call__` arg, not a constructor arg. : | `partition_info` | - | (`__call__` arg in TF1) Not supported | #### Example of fixed-seed behavior differences `compat.v1` Fixed seed behavior: >>> initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=False> After: >>> initializer = tf.keras.initializers.TruncatedNormal(seed=10) >>> a = initializer(shape=(2, 2)) >>> b = initializer(shape=(2, 2)) >>> tf.reduce_sum(a - b) == 0 <tf.Tensor: shape=(), dtype=bool, numpy=True> @end_compatibility """ def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=tf.float32): """Initializer that generates a truncated normal distribution. 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 create random seeds. See `tf.compat.v1.set_random_seed` for behavior. dtype: Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. """ super(TruncatedNormal, self).__init__( mean=mean, stddev=stddev, seed=seed, dtype=dtype) @keras_export(v1=['keras.initializers.lecun_normal']) class LecunNormal(tf.compat.v1.variance_scaling_initializer): def __init__(self, seed=None): super(LecunNormal, self).__init__( scale=1., mode='fan_in', distribution='truncated_normal', seed=seed) def get_config(self): return {'seed': self.seed} @keras_export(v1=['keras.initializers.lecun_uniform']) class LecunUniform(tf.compat.v1.variance_scaling_initializer): def __init__(self, seed=None): super(LecunUniform, self).__init__( scale=1., mode='fan_in', distribution='uniform', seed=seed) def get_config(self): return {'seed': self.seed} @keras_export(v1=['keras.initializers.he_normal']) class HeNormal(tf.compat.v1.variance_scaling_initializer): def __init__(self, seed=None): super(HeNormal, self).__init__( scale=2., mode='fan_in', distribution='truncated_normal', seed=seed) def get_config(self): return {'seed': self.seed} @keras_export(v1=['keras.initializers.he_uniform']) class HeUniform(tf.compat.v1.variance_scaling_initializer): def __init__(self, seed=None): super(HeUniform, self).__init__( scale=2., mode='fan_in', distribution='uniform', seed=seed) def get_config(self): return {'seed': self.seed}
18,330
39.376652
109
py
keras
keras-master/keras/initializers/__init__.py
# 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 initializer serialization / deserialization.""" import tensorflow.compat.v2 as tf import threading from tensorflow.python import tf2 from keras.initializers import initializers_v1 from keras.initializers import initializers_v2 from keras.utils import generic_utils from keras.utils import tf_inspect as inspect from tensorflow.python.ops import init_ops from tensorflow.python.util.tf_export import keras_export # LOCAL.ALL_OBJECTS is meant to be a global mutable. Hence we need to make it # thread-local to avoid concurrent mutations. LOCAL = threading.local() def populate_deserializable_objects(): """Populates dict ALL_OBJECTS with every built-in initializer. """ global LOCAL if not hasattr(LOCAL, 'ALL_OBJECTS'): LOCAL.ALL_OBJECTS = {} LOCAL.GENERATED_WITH_V2 = None if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf.__internal__.tf2.enabled(): # Objects dict is already generated for the proper TF version: # do nothing. return LOCAL.ALL_OBJECTS = {} LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled() # Compatibility aliases (need to exist in both V1 and V2). LOCAL.ALL_OBJECTS['ConstantV2'] = initializers_v2.Constant LOCAL.ALL_OBJECTS['GlorotNormalV2'] = initializers_v2.GlorotNormal LOCAL.ALL_OBJECTS['GlorotUniformV2'] = initializers_v2.GlorotUniform LOCAL.ALL_OBJECTS['HeNormalV2'] = initializers_v2.HeNormal LOCAL.ALL_OBJECTS['HeUniformV2'] = initializers_v2.HeUniform LOCAL.ALL_OBJECTS['IdentityV2'] = initializers_v2.Identity LOCAL.ALL_OBJECTS['LecunNormalV2'] = initializers_v2.LecunNormal LOCAL.ALL_OBJECTS['LecunUniformV2'] = initializers_v2.LecunUniform LOCAL.ALL_OBJECTS['OnesV2'] = initializers_v2.Ones LOCAL.ALL_OBJECTS['OrthogonalV2'] = initializers_v2.Orthogonal LOCAL.ALL_OBJECTS['RandomNormalV2'] = initializers_v2.RandomNormal LOCAL.ALL_OBJECTS['RandomUniformV2'] = initializers_v2.RandomUniform LOCAL.ALL_OBJECTS['TruncatedNormalV2'] = initializers_v2.TruncatedNormal LOCAL.ALL_OBJECTS['VarianceScalingV2'] = initializers_v2.VarianceScaling LOCAL.ALL_OBJECTS['ZerosV2'] = initializers_v2.Zeros # Out of an abundance of caution we also include these aliases that have # a non-zero probability of having been included in saved configs in the past. LOCAL.ALL_OBJECTS['glorot_normalV2'] = initializers_v2.GlorotNormal LOCAL.ALL_OBJECTS['glorot_uniformV2'] = initializers_v2.GlorotUniform LOCAL.ALL_OBJECTS['he_normalV2'] = initializers_v2.HeNormal LOCAL.ALL_OBJECTS['he_uniformV2'] = initializers_v2.HeUniform LOCAL.ALL_OBJECTS['lecun_normalV2'] = initializers_v2.LecunNormal LOCAL.ALL_OBJECTS['lecun_uniformV2'] = initializers_v2.LecunUniform if tf.__internal__.tf2.enabled(): # For V2, entries are generated automatically based on the content of # initializers_v2.py. v2_objs = {} base_cls = initializers_v2.Initializer generic_utils.populate_dict_with_module_objects( v2_objs, [initializers_v2], obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls)) for key, value in v2_objs.items(): LOCAL.ALL_OBJECTS[key] = value # Functional aliases. LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value else: # V1 initializers. v1_objs = { 'Constant': tf.compat.v1.constant_initializer, 'GlorotNormal': tf.compat.v1.glorot_normal_initializer, 'GlorotUniform': tf.compat.v1.glorot_uniform_initializer, 'Identity': tf.compat.v1.initializers.identity, 'Ones': tf.compat.v1.ones_initializer, 'Orthogonal': tf.compat.v1.orthogonal_initializer, 'VarianceScaling': tf.compat.v1.variance_scaling_initializer, 'Zeros': tf.compat.v1.zeros_initializer, 'HeNormal': initializers_v1.HeNormal, 'HeUniform': initializers_v1.HeUniform, 'LecunNormal': initializers_v1.LecunNormal, 'LecunUniform': initializers_v1.LecunUniform, 'RandomNormal': initializers_v1.RandomNormal, 'RandomUniform': initializers_v1.RandomUniform, 'TruncatedNormal': initializers_v1.TruncatedNormal, } for key, value in v1_objs.items(): LOCAL.ALL_OBJECTS[key] = value # Functional aliases. LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value # More compatibility aliases. LOCAL.ALL_OBJECTS['normal'] = LOCAL.ALL_OBJECTS['random_normal'] LOCAL.ALL_OBJECTS['uniform'] = LOCAL.ALL_OBJECTS['random_uniform'] LOCAL.ALL_OBJECTS['one'] = LOCAL.ALL_OBJECTS['ones'] LOCAL.ALL_OBJECTS['zero'] = LOCAL.ALL_OBJECTS['zeros'] # For backwards compatibility, we populate this file with the objects # from ALL_OBJECTS. We make no guarantees as to whether these objects will # using their correct version. populate_deserializable_objects() globals().update(LOCAL.ALL_OBJECTS) # Utility functions @keras_export('keras.initializers.serialize') def serialize(initializer): return generic_utils.serialize_keras_object(initializer) @keras_export('keras.initializers.deserialize') def deserialize(config, custom_objects=None): """Return an `Initializer` object from its config.""" populate_deserializable_objects() return generic_utils.deserialize_keras_object( config, module_objects=LOCAL.ALL_OBJECTS, custom_objects=custom_objects, printable_module_name='initializer') @keras_export('keras.initializers.get') def get(identifier): """Retrieve a Keras initializer by the identifier. The `identifier` may be the string name of a initializers function or class ( case-sensitively). >>> identifier = 'Ones' >>> tf.keras.initializers.deserialize(identifier) <...keras.initializers.initializers_v2.Ones...> You can also specify `config` of the initializer to this function by passing dict containing `class_name` and `config` as an identifier. Also note that the `class_name` must map to a `Initializer` class. >>> cfg = {'class_name': 'Ones', 'config': {}} >>> tf.keras.initializers.deserialize(cfg) <...keras.initializers.initializers_v2.Ones...> In the case that the `identifier` is a class, this method will return a new instance of the class by its constructor. Args: identifier: String or dict that contains the initializer name or configurations. Returns: Initializer instance base on the input identifier. Raises: ValueError: If the input identifier is not a supported type or in a bad format. """ if identifier is None: return None if isinstance(identifier, dict): return deserialize(identifier) elif isinstance(identifier, str): identifier = str(identifier) return deserialize(identifier) elif callable(identifier): if inspect.isclass(identifier): identifier = identifier() return identifier else: raise ValueError('Could not interpret initializer identifier: ' + str(identifier))
7,577
38.061856
84
py
keras
keras-master/keras/saving/saving_utils.py
# 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. # ============================================================================== """Utils related to keras model saving.""" # pylint: disable=g-bad-import-order, g-direct-tensorflow-import import tensorflow.compat.v2 as tf import copy import os from keras import backend as K from keras import losses from keras import optimizer_v1 from keras import optimizers from keras.engine import base_layer_utils from keras.utils import generic_utils from keras.utils import version_utils from keras.utils.io_utils import ask_to_proceed_with_overwrite from tensorflow.python.platform import tf_logging as logging # pylint: enable=g-bad-import-order, g-direct-tensorflow-import def extract_model_metrics(model): """Convert metrics from a Keras model `compile` API to dictionary. This is used for converting Keras models to Estimators and SavedModels. Args: model: A `tf.keras.Model` object. Returns: Dictionary mapping metric names to metric instances. May return `None` if the model does not contain any metrics. """ if getattr(model, '_compile_metrics', None): # TODO(psv/kathywu): use this implementation in model to estimator flow. # We are not using model.metrics here because we want to exclude the metrics # added using `add_metric` API. return {m.name: m for m in model._compile_metric_functions} # pylint: disable=protected-access return None def model_call_inputs(model, keep_original_batch_size=False): """Inspect model to get its input signature. The model's input signature is a list with a single (possibly-nested) object. This is due to the Keras-enforced restriction that tensor inputs must be passed in as the first argument. For example, a model with input {'feature1': <Tensor>, 'feature2': <Tensor>} will have input signature: [{'feature1': TensorSpec, 'feature2': TensorSpec}] Args: model: Keras Model object. keep_original_batch_size: A boolean indicating whether we want to keep using the original batch size or set it to None. Default is `False`, which means that the batch dim of the returned input signature will always be set to `None`. Returns: A tuple containing `(args, kwargs)` TensorSpecs of the model call function inputs. `kwargs` does not contain the `training` argument. """ input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size) if input_specs is None: return None, None input_specs = _enforce_names_consistency(input_specs) return input_specs def raise_model_input_error(model): raise ValueError( f'Model {model} cannot be saved because the input shapes have not ' f'been set. Usually, input shapes are automatically determined when ' f'calling `.fit()` or `.predict()`. To manually set the shapes, call ' f'`model.build(input_shape)') def trace_model_call(model, input_signature=None): """Trace the model call to create a tf.function for exporting a Keras model. Args: model: A Keras model. input_signature: optional, a list of tf.TensorSpec objects specifying the inputs to the model. Returns: A tf.function wrapping the model's call function with input signatures set. Raises: ValueError: if input signature cannot be inferred from the model. """ if input_signature is None: if isinstance(model.call, tf.__internal__.function.Function): input_signature = model.call.input_signature if input_signature: model_args = input_signature model_kwargs = {} else: model_args, model_kwargs = model_call_inputs(model) input_signature = model_args # store if model_args is None: raise_model_input_error(model) @tf.function def _wrapped_model(*args, **kwargs): """A concrete tf.function that wraps the model's call function.""" kwargs['training'] = False with base_layer_utils.call_context().enter( model, inputs=None, build_graph=False, training=False, saving=True): outputs = model(*args, **kwargs) # Outputs always has to be a flat dict. output_names = model.output_names # Functional Model. if output_names is None: # Subclassed Model. from keras.engine import compile_utils # pylint: disable=g-import-not-at-top output_names = compile_utils.create_pseudo_output_names(outputs) outputs = tf.nest.flatten(outputs) return {name: output for name, output in zip(output_names, outputs)} return _wrapped_model.get_concrete_function(*model_args, **model_kwargs) def model_metadata(model, include_optimizer=True, require_config=True): """Returns a dictionary containing the model metadata.""" from keras import __version__ as keras_version # pylint: disable=g-import-not-at-top from keras.optimizer_v2 import optimizer_v2 # pylint: disable=g-import-not-at-top model_config = {'class_name': model.__class__.__name__} try: model_config['config'] = model.get_config() except NotImplementedError as e: if require_config: raise e metadata = dict( keras_version=str(keras_version), backend=K.backend(), model_config=model_config) if model.optimizer and include_optimizer: if isinstance(model.optimizer, optimizer_v1.TFOptimizer): logging.warning( 'TensorFlow optimizers do not ' 'make it possible to access ' 'optimizer attributes or optimizer state ' 'after instantiation. ' 'As a result, we cannot save the optimizer ' 'as part of the model save file. ' 'You will have to compile your model again after loading it. ' 'Prefer using a Keras optimizer instead ' '(see keras.io/optimizers).') elif model._compile_was_called: # pylint: disable=protected-access training_config = model._get_compile_args(user_metrics=False) # pylint: disable=protected-access training_config.pop('optimizer', None) # Handled separately. metadata['training_config'] = _serialize_nested_config(training_config) if isinstance(model.optimizer, optimizer_v2.RestoredOptimizer): raise NotImplementedError( 'Optimizers loaded from a SavedModel cannot be saved. ' 'If you are calling `model.save` or `tf.keras.models.save_model`, ' 'please set the `include_optimizer` option to `False`. For ' '`tf.saved_model.save`, delete the optimizer from the model.') else: optimizer_config = { 'class_name': generic_utils.get_registered_name(model.optimizer.__class__), 'config': model.optimizer.get_config() } metadata['training_config']['optimizer_config'] = optimizer_config return metadata def should_overwrite(filepath, overwrite): """Returns whether the filepath should be overwritten.""" # If file exists and should not be overwritten. if not overwrite and os.path.isfile(filepath): return ask_to_proceed_with_overwrite(filepath) return True def compile_args_from_training_config(training_config, custom_objects=None): """Return model.compile arguments from training config.""" if custom_objects is None: custom_objects = {} with generic_utils.CustomObjectScope(custom_objects): optimizer_config = training_config['optimizer_config'] optimizer = optimizers.deserialize(optimizer_config) # Recover losses. loss = None loss_config = training_config.get('loss', None) if loss_config is not None: loss = _deserialize_nested_config(losses.deserialize, loss_config) # Recover metrics. metrics = None metrics_config = training_config.get('metrics', None) if metrics_config is not None: metrics = _deserialize_nested_config(_deserialize_metric, metrics_config) # Recover weighted metrics. weighted_metrics = None weighted_metrics_config = training_config.get('weighted_metrics', None) if weighted_metrics_config is not None: weighted_metrics = _deserialize_nested_config(_deserialize_metric, weighted_metrics_config) sample_weight_mode = training_config['sample_weight_mode'] if hasattr( training_config, 'sample_weight_mode') else None loss_weights = training_config['loss_weights'] return dict( optimizer=optimizer, loss=loss, metrics=metrics, weighted_metrics=weighted_metrics, loss_weights=loss_weights, sample_weight_mode=sample_weight_mode) def _deserialize_nested_config(deserialize_fn, config): """Deserializes arbitrary Keras `config` using `deserialize_fn`.""" def _is_single_object(obj): if isinstance(obj, dict) and 'class_name' in obj: return True # Serialized Keras object. if isinstance(obj, str): return True # Serialized function or string. return False if config is None: return None if _is_single_object(config): return deserialize_fn(config) elif isinstance(config, dict): return { k: _deserialize_nested_config(deserialize_fn, v) for k, v in config.items() } elif isinstance(config, (tuple, list)): return [_deserialize_nested_config(deserialize_fn, obj) for obj in config] raise ValueError( 'Saved configuration not understood. Configuration should be a ' f'dictionary, string, tuple or list. Received: config={config}.') def _serialize_nested_config(config): """Serialized a nested structure of Keras objects.""" def _serialize_fn(obj): if callable(obj): return generic_utils.serialize_keras_object(obj) return obj return tf.nest.map_structure(_serialize_fn, config) def _deserialize_metric(metric_config): """Deserialize metrics, leaving special strings untouched.""" from keras import metrics as metrics_module # pylint:disable=g-import-not-at-top if metric_config in ['accuracy', 'acc', 'crossentropy', 'ce']: # Do not deserialize accuracy and cross-entropy strings as we have special # case handling for these in compile, based on model output shape. return metric_config return metrics_module.deserialize(metric_config) def _enforce_names_consistency(specs): """Enforces that either all specs have names or none do.""" def _has_name(spec): return hasattr(spec, 'name') and spec.name is not None def _clear_name(spec): spec = copy.deepcopy(spec) if hasattr(spec, 'name'): spec._name = None # pylint:disable=protected-access return spec flat_specs = tf.nest.flatten(specs) name_inconsistency = ( any(_has_name(s) for s in flat_specs) and not all(_has_name(s) for s in flat_specs)) if name_inconsistency: specs = tf.nest.map_structure(_clear_name, specs) return specs def try_build_compiled_arguments(model): if (not version_utils.is_v1_layer_or_model(model) and model.outputs is not None): try: if not model.compiled_loss.built: model.compiled_loss.build(model.outputs) if not model.compiled_metrics.built: model.compiled_metrics.build(model.outputs, model.outputs) except: # pylint: disable=bare-except logging.warning( 'Compiled the loaded model, but the compiled metrics have yet to ' 'be built. `model.compile_metrics` will be empty until you train ' 'or evaluate the model.') def is_hdf5_filepath(filepath): return (filepath.endswith('.h5') or filepath.endswith('.keras') or filepath.endswith('.hdf5'))
12,066
36.243827
103
py
keras
keras-master/keras/saving/pickle_utils_test.py
# 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 pickling / deepcopying of Keras Models.""" # pylint: disable=g-bad-import-order import tensorflow.compat.v2 as tf import copy import pickle import numpy as np from keras import keras_parameterized from keras import testing_utils class TestPickleProtocol(keras_parameterized.TestCase): """Tests pickle protoocol support.""" @keras_parameterized.run_with_all_model_types @keras_parameterized.parameterized.named_parameters( ('copy', copy.copy), ('deepcopy', copy.deepcopy), *((f'pickle_protocol_level_{protocol}', lambda model: pickle.loads(pickle.dumps(model, protocol=protocol))) # pylint: disable=cell-var-from-loop for protocol in range(pickle.HIGHEST_PROTOCOL + 1))) def test_built_models(self, serializer): """Built models should be copyable and picklable for all model types.""" model = testing_utils.get_small_mlp( num_hidden=1, num_classes=2, input_dim=3) model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy') # train x = np.random.random(size=(1000, 3)) y = np.random.randint(low=0, high=2, size=(1000,)) model.fit(x, y) # builds model y1 = model.predict(x) # roundtrip with training model = serializer(model) y2 = model.predict(x) # check that the predictions are the same self.assertAllClose(y1, y2) # and that we can continue training model.fit(x, y) y3 = model.predict(x) # check that the predictions are the same self.assertNotAllClose(y2, y3) @keras_parameterized.run_with_all_model_types @keras_parameterized.parameterized.named_parameters( ('copy', copy.copy), ('deepcopy', copy.deepcopy), ) def test_unbuilt_models(self, serializer): """Unbuilt models should be copyable & deepcopyable for all model types.""" original_model = testing_utils.get_small_mlp( num_hidden=1, num_classes=2, input_dim=3) # roundtrip without compiling or training model = serializer(original_model) # compile model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy') # roundtrip compiled but not trained model = serializer(model) if __name__ == '__main__': tf.test.main()
2,889
35.582278
114
py
keras
keras-master/keras/saving/saved_model_experimental.py
# 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. # ============================================================================== """Deprecated experimental Keras SavedModel implementation.""" import tensorflow.compat.v2 as tf import os import warnings from keras import backend from keras import optimizer_v1 from keras.optimizer_v2 import optimizer_v2 from keras.saving import model_config from keras.saving import saving_utils from keras.saving import utils_v1 as model_utils from keras.utils import mode_keys from keras.utils.generic_utils import LazyLoader from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export # 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. # pylint:disable=g-inconsistent-quotes metrics_lib = LazyLoader("metrics_lib", globals(), "keras.metrics") models_lib = LazyLoader("models_lib", globals(), "keras.models") sequential = LazyLoader( "sequential", globals(), "keras.engine.sequential") # pylint:enable=g-inconsistent-quotes # File name for json format of SavedModel. SAVED_MODEL_FILENAME_JSON = 'saved_model.json' @keras_export(v1=['keras.experimental.export_saved_model']) def export_saved_model(model, saved_model_path, custom_objects=None, as_text=False, input_signature=None, serving_only=False): """Exports a `tf.keras.Model` as a Tensorflow SavedModel. Note that at this time, subclassed models can only be saved using `serving_only=True`. The exported `SavedModel` is a standalone serialization of Tensorflow objects, and is supported by TF language APIs and the Tensorflow Serving system. To load the model, use the function `tf.keras.experimental.load_from_saved_model`. The `SavedModel` contains: 1. a checkpoint containing the model weights. 2. a `SavedModel` proto containing the Tensorflow backend graph. Separate graphs are saved for prediction (serving), train, and evaluation. If the model has not been compiled, then only the graph computing predictions will be exported. 3. the model's json config. If the model is subclassed, this will only be included if the model's `get_config()` method is overwritten. Example: ```python import tensorflow as tf # Create a tf.keras model. model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_shape=[10])) model.summary() # Save the tf.keras model in the SavedModel format. path = '/tmp/simple_keras_model' tf.keras.experimental.export_saved_model(model, path) # Load the saved keras model back. new_model = tf.keras.experimental.load_from_saved_model(path) new_model.summary() ``` Args: model: A `tf.keras.Model` to be saved. If the model is subclassed, the flag `serving_only` must be set to True. saved_model_path: a string specifying the path to the SavedModel directory. custom_objects: Optional dictionary mapping string names to custom classes or functions (e.g. custom loss functions). as_text: bool, `False` by default. Whether to write the `SavedModel` proto in text format. Currently unavailable in serving-only mode. input_signature: A possibly nested sequence of `tf.TensorSpec` objects, used to specify the expected model inputs. See `tf.function` for more details. serving_only: bool, `False` by default. When this is true, only the prediction graph is saved. Raises: NotImplementedError: If the model is a subclassed model, and serving_only is False. ValueError: If the input signature cannot be inferred from the model. AssertionError: If the SavedModel directory already exists and isn't empty. """ warnings.warn('`tf.keras.experimental.export_saved_model` is deprecated' 'and will be removed in a future version. ' 'Please use `model.save(..., save_format="tf")` or ' '`tf.keras.models.save_model(..., save_format="tf")`.') if serving_only: tf.saved_model.save( model, saved_model_path, signatures=saving_utils.trace_model_call(model, input_signature)) else: _save_v1_format(model, saved_model_path, custom_objects, as_text, input_signature) try: _export_model_json(model, saved_model_path) except NotImplementedError: logging.warning('Skipped saving model JSON, subclassed model does not have ' 'get_config() defined.') def _export_model_json(model, saved_model_path): """Saves model configuration as a json string under assets folder.""" model_json = model.to_json() model_json_filepath = os.path.join( _get_or_create_assets_dir(saved_model_path), tf.compat.as_text(SAVED_MODEL_FILENAME_JSON)) with tf.io.gfile.GFile(model_json_filepath, 'w') as f: f.write(model_json) def _export_model_variables(model, saved_model_path): """Saves model weights in checkpoint format under variables folder.""" _get_or_create_variables_dir(saved_model_path) checkpoint_prefix = _get_variables_path(saved_model_path) model.save_weights(checkpoint_prefix, save_format='tf', overwrite=True) return checkpoint_prefix def _save_v1_format(model, path, custom_objects, as_text, input_signature): """Exports model to v1 SavedModel format.""" if not model._is_graph_network: # pylint: disable=protected-access if isinstance(model, sequential.Sequential): # If input shape is not directly set in the model, the exported model # will infer the expected shapes of the input from the model. if not model.built: raise ValueError('Weights for sequential model have not yet been ' 'created. Weights are created when the Model is first ' 'called on inputs or `build()` is called with an ' '`input_shape`, or the first layer in the model has ' '`input_shape` during construction.') # TODO(kathywu): Build the model with input_signature to create the # weights before _export_model_variables(). else: raise NotImplementedError( 'Subclassed models can only be exported for serving. Please set ' 'argument serving_only=True.') builder = tf.__internal__.saved_model.SavedModelBuilder(path) # pylint: disable=protected-access # Manually save variables to export them in an object-based checkpoint. This # skips the `builder.add_meta_graph_and_variables()` step, which saves a # named-based checkpoint. # TODO(b/113134168): Add fn to Builder to save with object-based saver. # TODO(b/113178242): This should only export the model json structure. Only # one save is needed once the weights can be copied from the model to clone. checkpoint_path = _export_model_variables(model, path) # Export each mode. Use ModeKeys enums defined for `Estimator` to ensure that # Keras models and `Estimator`s are exported with the same format. # Every time a mode is exported, the code checks to see if new variables have # been created (e.g. optimizer slot variables). If that is the case, the # checkpoint is re-saved to include the new variables. export_args = {'builder': builder, 'model': model, 'custom_objects': custom_objects, 'checkpoint_path': checkpoint_path, 'input_signature': input_signature} has_saved_vars = False if model.optimizer: if isinstance(model.optimizer, (optimizer_v1.TFOptimizer, optimizer_v2.OptimizerV2)): _export_mode(mode_keys.ModeKeys.TRAIN, has_saved_vars, **export_args) has_saved_vars = True _export_mode(mode_keys.ModeKeys.TEST, has_saved_vars, **export_args) else: logging.warning( 'Model was compiled with an optimizer, but the optimizer is not from ' '`tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving ' 'graph was exported. The train and evaluate graphs were not added to ' 'the SavedModel.') _export_mode(mode_keys.ModeKeys.PREDICT, has_saved_vars, **export_args) builder.save(as_text) def _get_var_list(model): """Returns list of all checkpointed saveable objects in the model.""" var_list, _, _ = tf.__internal__.tracking.ObjectGraphView(model).serialize_object_graph() return var_list def create_placeholder(spec): return backend.placeholder(shape=spec.shape, dtype=spec.dtype, name=spec.name) def _export_mode( mode, has_saved_vars, builder, model, custom_objects, checkpoint_path, input_signature): """Exports a model, and optionally saves new vars from the clone model. Args: mode: A `tf.estimator.ModeKeys` string. has_saved_vars: A `boolean` indicating whether the SavedModel has already exported variables. builder: A `SavedModelBuilder` object. model: A `tf.keras.Model` object. custom_objects: A dictionary mapping string names to custom classes or functions. checkpoint_path: String path to checkpoint. input_signature: Nested TensorSpec containing the expected inputs. Can be `None`, in which case the signature will be inferred from the model. Raises: ValueError: If the train/eval mode is being exported, but the model does not have an optimizer. """ compile_clone = (mode != mode_keys.ModeKeys.PREDICT) if compile_clone and not model.optimizer: raise ValueError( f'Model {model.name} does not have an optimizer. ' f'Cannot export mode {mode}.') model_graph = tf.compat.v1.get_default_graph() with tf.Graph().as_default() as g, backend.learning_phase_scope( mode == mode_keys.ModeKeys.TRAIN): if input_signature is None: input_tensors = None else: input_tensors = tf.nest.map_structure(create_placeholder, input_signature) # Clone the model into blank graph. This will create placeholders for inputs # and targets. clone = models_lib.clone_and_build_model( model, input_tensors=input_tensors, custom_objects=custom_objects, compile_clone=compile_clone) # Make sure that iterations variable is added to the global step collection, # to ensure that, when the SavedModel graph is loaded, the iterations # variable is returned by `tf.compat.v1.train.get_global_step()`. This is # required for compatibility with the SavedModelEstimator. if compile_clone: g.add_to_collection(tf.compat.v1.GraphKeys.GLOBAL_STEP, clone.optimizer.iterations) # Extract update and train ops from train/test/predict functions. train_op = None if mode == mode_keys.ModeKeys.TRAIN: clone._make_train_function() # pylint: disable=protected-access train_op = clone.train_function.updates_op elif mode == mode_keys.ModeKeys.TEST: clone._make_test_function() # pylint: disable=protected-access else: clone._make_predict_function() # pylint: disable=protected-access g.get_collection_ref(tf.compat.v1.GraphKeys.UPDATE_OPS).extend(clone.state_updates) with tf.compat.v1.Session().as_default(): clone_var_list = _get_var_list(clone) if has_saved_vars: # Confirm all variables in the clone have an entry in the checkpoint. status = clone.load_weights(checkpoint_path) status.assert_existing_objects_matched() else: # Confirm that variables between the clone and model match up exactly, # not counting optimizer objects. Optimizer objects are ignored because # if the model has not trained, the slot variables will not have been # created yet. # TODO(b/113179535): Replace with trackable equivalence. _assert_same_non_optimizer_objects(model, model_graph, clone, g) # TODO(b/113178242): Use value transfer for trackable objects. clone.load_weights(checkpoint_path) # Add graph and variables to SavedModel. # TODO(b/113134168): Switch to add_meta_graph_and_variables. clone.save_weights(checkpoint_path, save_format='tf', overwrite=True) builder._has_saved_variables = True # pylint: disable=protected-access # Add graph to the SavedModel builder. builder.add_meta_graph( model_utils.EXPORT_TAG_MAP[mode], signature_def_map=_create_signature_def_map(clone, mode), saver=tf.compat.v1.train.Saver( clone_var_list, # Allow saving Models with no variables. This is somewhat odd, but # it's not necessarily a bug. allow_empty=True), init_op=tf.compat.v1.local_variables_initializer(), train_op=train_op) return None def _create_signature_def_map(model, mode): """Creates a SignatureDef map from a Keras model.""" inputs_dict = {name: x for name, x in zip(model.input_names, model.inputs)} if model.optimizer: targets_dict = {x.name.split(':')[0]: x for x in model._targets if x is not None} # pylint: disable=protected-access inputs_dict.update(targets_dict) outputs_dict = {name: x for name, x in zip(model.output_names, model.outputs)} metrics = saving_utils.extract_model_metrics(model) # Add metric variables to the `LOCAL_VARIABLES` collection. Metric variables # are by default not added to any collections. We are doing this here, so # that metric variables get initialized. local_vars = set(tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.LOCAL_VARIABLES)) vars_to_add = set() if metrics is not None: for key, value in metrics.items(): if isinstance(value, metrics_lib.Metric): vars_to_add.update(value.variables) # Convert Metric instances to (value_tensor, update_op) tuple. metrics[key] = (value.result(), value.updates[0]) # Remove variables that are in the local variables collection already. vars_to_add = vars_to_add.difference(local_vars) for v in vars_to_add: tf.compat.v1.add_to_collection(tf.compat.v1.GraphKeys.LOCAL_VARIABLES, v) export_outputs = model_utils.export_outputs_for_mode( mode, predictions=outputs_dict, loss=model.total_loss if model.optimizer else None, metrics=metrics) return model_utils.build_all_signature_defs( inputs_dict, export_outputs=export_outputs, serving_only=(mode == mode_keys.ModeKeys.PREDICT)) def _assert_same_non_optimizer_objects(model, model_graph, clone, clone_graph): # pylint: disable=unused-argument """Asserts model and clone contain the same trackable objects.""" # TODO(fchollet, kathywu): make sure this works in eager mode. return True @keras_export(v1=['keras.experimental.load_from_saved_model']) def load_from_saved_model(saved_model_path, custom_objects=None): """Loads a keras Model from a SavedModel created by `export_saved_model()`. This function reinstantiates model state by: 1) loading model topology from json (this will eventually come from metagraph). 2) loading model weights from checkpoint. Example: ```python import tensorflow as tf # Create a tf.keras model. model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_shape=[10])) model.summary() # Save the tf.keras model in the SavedModel format. path = '/tmp/simple_keras_model' tf.keras.experimental.export_saved_model(model, path) # Load the saved keras model back. new_model = tf.keras.experimental.load_from_saved_model(path) new_model.summary() ``` Args: saved_model_path: a string specifying the path to an existing SavedModel. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: a keras.Model instance. """ warnings.warn('`tf.keras.experimental.load_from_saved_model` is deprecated' 'and will be removed in a future version. ' 'Please switch to `tf.keras.models.load_model`.') # restore model topology from json string model_json_filepath = os.path.join( tf.compat.as_bytes(saved_model_path), tf.compat.as_bytes(tf.saved_model.ASSETS_DIRECTORY), tf.compat.as_bytes(SAVED_MODEL_FILENAME_JSON)) with tf.io.gfile.GFile(model_json_filepath, 'r') as f: model_json = f.read() model = model_config.model_from_json( model_json, custom_objects=custom_objects) # restore model weights checkpoint_prefix = os.path.join( tf.compat.as_text(saved_model_path), tf.compat.as_text(tf.saved_model.VARIABLES_DIRECTORY), tf.compat.as_text(tf.saved_model.VARIABLES_FILENAME)) model.load_weights(checkpoint_prefix) return model #### Directory / path helpers def _get_or_create_variables_dir(export_dir): """Return variables sub-directory, or create one if it doesn't exist.""" variables_dir = _get_variables_dir(export_dir) tf.io.gfile.makedirs(variables_dir) return variables_dir def _get_variables_dir(export_dir): """Return variables sub-directory in the SavedModel.""" return os.path.join( tf.compat.as_text(export_dir), tf.compat.as_text(tf.saved_model.VARIABLES_DIRECTORY)) def _get_variables_path(export_dir): """Return the variables path, used as the prefix for checkpoint files.""" return os.path.join( tf.compat.as_text(_get_variables_dir(export_dir)), tf.compat.as_text(tf.saved_model.VARIABLES_FILENAME)) def _get_or_create_assets_dir(export_dir): """Return assets sub-directory, or create one if it doesn't exist.""" assets_destination_dir = _get_assets_dir(export_dir) tf.io.gfile.makedirs(assets_destination_dir) return assets_destination_dir def _get_assets_dir(export_dir): """Return path to asset directory in the SavedModel.""" return os.path.join( tf.compat.as_text(export_dir), tf.compat.as_text(tf.saved_model.ASSETS_DIRECTORY))
18,748
39.670282
114
py
keras
keras-master/keras/saving/saving_utils_test.py
# 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 saving utility functions.""" import tensorflow.compat.v2 as tf import os import numpy as np import keras from keras import backend from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.engine import sequential from keras.feature_column import dense_features from keras.optimizer_v2 import gradient_descent from keras.saving import saving_utils class TraceModelCallTest(keras_parameterized.TestCase): def _assert_all_close(self, expected, actual): if not tf.executing_eagerly(): with self.cached_session() as sess: backend._initialize_variables(sess) self.assertAllClose(expected, actual) else: self.assertAllClose(expected, actual) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_trace_model_outputs(self): input_dim = 5 if testing_utils.get_model_type() == 'functional' else None model = testing_utils.get_small_mlp(10, 3, input_dim) inputs = tf.ones((8, 5)) if input_dim is None: with self.assertRaisesRegex(ValueError, 'input shapes have not been set'): saving_utils.trace_model_call(model) model._set_inputs(inputs) fn = saving_utils.trace_model_call(model) signature_outputs = fn(inputs) if model.output_names: expected_outputs = {model.output_names[0]: model(inputs)} else: expected_outputs = {'output_1': model(inputs)} self._assert_all_close(expected_outputs, signature_outputs) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_trace_model_outputs_after_fitting(self): input_dim = 5 if testing_utils.get_model_type() == 'functional' else None model = testing_utils.get_small_mlp(10, 3, input_dim) model.compile( optimizer='sgd', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.fit( x=np.random.random((8, 5)).astype(np.float32), y=np.random.random((8, 3)).astype(np.float32), epochs=2) inputs = tf.ones((8, 5)) fn = saving_utils.trace_model_call(model) signature_outputs = fn(inputs) if model.output_names: expected_outputs = {model.output_names[0]: model(inputs)} else: expected_outputs = {'output_1': model(inputs)} self._assert_all_close(expected_outputs, signature_outputs) @keras_parameterized.run_with_all_model_types(exclude_models='sequential') @keras_parameterized.run_all_keras_modes def test_trace_multi_io_model_outputs(self): input_dim = 5 num_classes = 3 num_classes_b = 4 input_a = keras.layers.Input(shape=(input_dim,), name='input_a') input_b = keras.layers.Input(shape=(input_dim,), name='input_b') dense = keras.layers.Dense(num_classes, name='dense') dense2 = keras.layers.Dense(num_classes_b, name='dense2') dropout = keras.layers.Dropout(0.5, name='dropout') branch_a = [input_a, dense] branch_b = [input_b, dense, dense2, dropout] model = testing_utils.get_multi_io_model(branch_a, branch_b) input_a_ts = tf.constant( np.random.random((10, input_dim)).astype(np.float32)) input_b_ts = tf.constant( np.random.random((10, input_dim)).astype(np.float32)) if testing_utils.get_model_type() == 'subclass': with self.assertRaisesRegex(ValueError, 'input shapes have not been set'): saving_utils.trace_model_call(model) model.compile( optimizer='sgd', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.fit(x=[np.random.random((8, input_dim)).astype(np.float32), np.random.random((8, input_dim)).astype(np.float32)], y=[np.random.random((8, num_classes)).astype(np.float32), np.random.random((8, num_classes_b)).astype(np.float32)], epochs=2) fn = saving_utils.trace_model_call(model) # tf.function requires that the input structures match when calling a # ConcreteFunction. For some reason V1 models defines the inputs as a list, # while V2 models sets the inputs as a tuple. if (not tf.executing_eagerly() and testing_utils.get_model_type() != 'functional'): signature_outputs = fn([input_a_ts, input_b_ts]) else: signature_outputs = fn((input_a_ts, input_b_ts)) outputs = model([input_a_ts, input_b_ts]) if model.output_names: expected_outputs = { model.output_names[0]: outputs[0], model.output_names[1]: outputs[1] } else: expected_outputs = {'output_1': outputs[0], 'output_2': outputs[1]} self._assert_all_close(expected_outputs, signature_outputs) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_trace_features_layer(self): columns = [tf.feature_column.numeric_column('x')] model = sequential.Sequential([dense_features.DenseFeatures(columns)]) model_input = {'x': tf.constant([[1.]])} model.predict(model_input, steps=1) fn = saving_utils.trace_model_call(model) self.assertAllClose({'output_1': [[1.]]}, fn(model_input)) columns = [ tf.feature_column.numeric_column('x'), tf.feature_column.numeric_column('y') ] model = sequential.Sequential([dense_features.DenseFeatures(columns)]) model_input = {'x': tf.constant([[1.]]), 'y': tf.constant([[2.]])} model.predict(model_input, steps=1) fn = saving_utils.trace_model_call(model) self.assertAllClose({'output_1': [[1., 2.]]}, fn(model_input)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_specify_input_signature(self): model = testing_utils.get_small_sequential_mlp(10, 3, None) inputs = tf.ones((8, 5)) with self.assertRaisesRegex(ValueError, 'input shapes have not been set'): saving_utils.trace_model_call(model) fn = saving_utils.trace_model_call( model, [tf.TensorSpec(shape=[None, 5], dtype=tf.float32)]) signature_outputs = fn(inputs) if model.output_names: expected_outputs = {model.output_names[0]: model(inputs)} else: expected_outputs = {'output_1': model(inputs)} self._assert_all_close(expected_outputs, signature_outputs) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_subclassed_model_with_input_signature(self): class Model(keras.Model): def __init__(self): super(Model, self).__init__() self.dense = keras.layers.Dense(3, name='dense') @tf.function( input_signature=[[tf.TensorSpec([None, 5], tf.float32), tf.TensorSpec([None], tf.float32)]],) def call(self, inputs, *args): x, y = inputs return self.dense(x) + y model = Model() fn = saving_utils.trace_model_call(model) x = tf.ones((8, 5), dtype=tf.float32) y = tf.ones((3,), dtype=tf.float32) expected_outputs = {'output_1': model([x, y])} signature_outputs = fn([x, y]) self._assert_all_close(expected_outputs, signature_outputs) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_model_with_fixed_input_dim(self): """Ensure that the batch_dim is removed when saving. When serving or retraining, it is important to reset the batch dim. This can be an issue inside of tf.function. See b/132783590 for context. """ model = testing_utils.get_small_mlp(10, 3, 5) loss_object = keras.losses.MeanSquaredError() optimizer = gradient_descent.SGD() @tf.function def train_step(data, labels): with tf.GradientTape() as tape: predictions = model(data) loss = loss_object(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) x = np.random.random((8, 5)) y = np.random.random((8, 3)) train_step(x, y) fn = saving_utils.trace_model_call(model) self.assertEqual(fn.structured_input_signature[0][0].shape.as_list(), tf.TensorShape([None, 5]).as_list()) def _import_and_infer(save_dir, inputs): """Import a SavedModel into a TF 1.x-style graph and run `signature_key`.""" graph = tf.Graph() with graph.as_default(), tf.compat.v1.Session() as session: model = tf.compat.v1.saved_model.load(session, [tf.saved_model.SERVING], save_dir) signature = model.signature_def[ tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] assert set(inputs.keys()) == set( signature.inputs.keys()), ('expected {}, found {}'.format( signature.inputs.keys(), inputs.keys())) feed_dict = {} for arg_name in inputs.keys(): feed_dict[graph.get_tensor_by_name(signature.inputs[arg_name].name)] = ( inputs[arg_name]) output_dict = {} for output_name, output_tensor_info in signature.outputs.items(): output_dict[output_name] = graph.get_tensor_by_name( output_tensor_info.name) return session.run(output_dict, feed_dict=feed_dict) class AutographedMetric(keras.metrics.Metric): def build(self, input_shape): pass def update_state(self, values): if tf.constant(False): x = 1 else: x = 2 return x def reset_states(self): pass def result(self): return tf.constant(0) def GetMean(self): return tf.constant(0) def GetCount(self): return tf.constant(0) class BasicAutographedMetricLayer(keras.layers.Layer): def build(self, input_shape): self._metric = AutographedMetric() def call(self, inp): self._metric.update_state(inp) # TODO(b/172853147): Test control flow here. return inp class BasicAutographedMetricModel(keras.models.Model): def __init__(self): super(BasicAutographedMetricModel, self).__init__(name='test_model') self._layer = BasicAutographedMetricLayer() def call(self, inputs, **kwargs): return self._layer(inputs) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class ModelSaveTest(keras_parameterized.TestCase): def test_model_save_preserves_autograph(self): model = BasicAutographedMetricModel() inputs = tf.ones((8, 5)) model._set_inputs(inputs) save_dir = os.path.join(self.get_temp_dir(), 'saved_model') tf.saved_model.save(model, save_dir) if model.output_names: output_name = model.output_names[0] input_name = model.input_names[0] else: output_name = 'output_1' input_name = 'input_1' self.assertAllClose({output_name: model.predict_on_batch(inputs)}, _import_and_infer(save_dir, {input_name: np.ones((8, 5))})) # Test v2 loading. # TODO(mdan): tests using _import_and_infer should uniformly do this. self.assertAllClose(model.predict_on_batch(inputs), tf.saved_model.load(save_dir)(inputs)) def test_model_save(self): input_dim = 5 model = testing_utils.get_small_mlp(10, 3, input_dim) inputs = tf.ones((8, 5)) if testing_utils.get_model_type() == 'subclass': model._set_inputs(inputs) save_dir = os.path.join(self.get_temp_dir(), 'saved_model') tf.saved_model.save(model, save_dir) if model.output_names: output_name = model.output_names[0] input_name = model.input_names[0] else: output_name = 'output_1' input_name = 'input_1' self.assertAllClose({output_name: model.predict_on_batch(inputs)}, _import_and_infer(save_dir, {input_name: np.ones((8, 5))})) class ExtractModelMetricsTest(keras_parameterized.TestCase): def test_extract_model_metrics(self): # saving_utils.extract_model_metrics is used in V1 only API # keras.experimental.export_saved_model. with tf.Graph().as_default(): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(3,), name='input_b') dense = keras.layers.Dense(4, name='dense') c = dense(a) d = dense(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) extract_metrics = saving_utils.extract_model_metrics(model) self.assertEqual(None, extract_metrics) extract_metric_names = [ 'dense_binary_accuracy', 'dropout_binary_accuracy', 'dense_mean_squared_error', 'dropout_mean_squared_error' ] if tf.__internal__.tf2.enabled(): extract_metric_names.extend(['dense_mae', 'dropout_mae']) else: extract_metric_names.extend( ['dense_mean_absolute_error', 'dropout_mean_absolute_error']) model_metric_names = ['loss', 'dense_loss', 'dropout_loss' ] + extract_metric_names model.compile( loss='mae', metrics=[ keras.metrics.BinaryAccuracy(), 'mae', keras.metrics.mean_squared_error ], optimizer=tf.compat.v1.train.RMSPropOptimizer(learning_rate=0.01)) extract_metrics = saving_utils.extract_model_metrics(model) self.assertEqual(set(model_metric_names), set(model.metrics_names)) self.assertEqual(set(extract_metric_names), set(extract_metrics.keys())) if __name__ == '__main__': tf.test.main()
14,119
34.388471
86
py
keras
keras-master/keras/saving/model_config.py
# 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. # ============================================================================== # pylint: disable=protected-access """Functions that save the model's config into different formats.""" from keras.saving.saved_model import json_utils from tensorflow.python.util.tf_export import keras_export @keras_export('keras.models.model_from_config') def model_from_config(config, custom_objects=None): """Instantiates a Keras model from its config. Usage: ``` # for a Functional API model tf.keras.Model().from_config(model.get_config()) # for a Sequential model tf.keras.Sequential().from_config(model.get_config()) ``` Args: config: Configuration dictionary. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). Raises: TypeError: if `config` is not a dictionary. """ if isinstance(config, list): raise TypeError('`model_from_config` expects a dictionary, not a list. ' f'Received: config={config}. Did you meant to use ' '`Sequential.from_config(config)`?') from keras.layers import deserialize # pylint: disable=g-import-not-at-top return deserialize(config, custom_objects=custom_objects) @keras_export('keras.models.model_from_yaml') def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. Args: yaml_string: YAML string or open file encoding a model configuration. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model_from_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `Model.to_json()` and ' '`model_from_json()` instead.' ) @keras_export('keras.models.model_from_json') def model_from_json(json_string, custom_objects=None): """Parses a JSON model configuration string and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model = tf.keras.models.model_from_json(config) Args: json_string: JSON string encoding a model configuration. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). """ config = json_utils.decode(json_string) from keras.layers import deserialize # pylint: disable=g-import-not-at-top return deserialize(config, custom_objects=custom_objects)
3,683
34.085714
80
py
keras
keras-master/keras/saving/save_weights_test.py
# 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 model saving in the HDF5 format.""" import tensorflow.compat.v2 as tf import os import shutil import uuid from absl.testing import parameterized import numpy as np import keras from keras import combinations from keras import keras_parameterized from keras import optimizer_v1 from keras import testing_utils from keras.engine import training from keras.saving import hdf5_format try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class TestWeightSavingAndLoading(tf.test.TestCase, parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) @keras_parameterized.run_with_all_weight_formats def test_weight_loading(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3)(a) b = keras.layers.Dense(1)(x) model = keras.models.Model(a, b) x = np.random.random((3, 2)) ref_y = model.predict(x) weights = model.get_weights() model.set_weights(weights) y = model.predict(x) self.assertAllClose(ref_y, y) with self.assertRaises(ValueError): model.set_weights(weights[1:]) with self.assertRaises(ValueError): model.set_weights(weights[::-1]) model.save_weights(saved_model_dir, save_format=save_format) model.load_weights(saved_model_dir) y = model.predict(x) self.assertAllClose(ref_y, y) def test_weight_preprocessing(self): input_dim = 3 output_dim = 3 size = 2 cases = [ [ (keras.layers.Bidirectional(keras.layers.SimpleRNN(2))), [np.random.random((2, 1)), np.random.random((2, 1))], (None, 3, 2), ], [ (keras.layers.TimeDistributed(keras.layers.Dense(1))), [np.random.random((2, 1)), np.random.random((1,))], (None, 3, 2), ], [ (keras.layers.Conv1D(output_dim, size, use_bias=False)), [np.random.random((output_dim, input_dim, size, 1))], (None, 4, input_dim), ], [ (keras.layers.Conv2D(output_dim, size, use_bias=False, data_format='channels_first')), [np.random.random((output_dim, input_dim, size, size))], (None, input_dim, 4, 4), ], [ (keras.layers.Conv2DTranspose(output_dim, size, use_bias=False, data_format='channels_first')), [np.random.random((output_dim, input_dim, size, size))], (None, input_dim, 4, 4), ], [ (keras.layers.Conv2DTranspose(output_dim, size, use_bias=False, data_format='channels_last')), [np.random.random((size, size, input_dim, output_dim))], (None, 4, 4, input_dim), ], [ (keras.layers.Conv3D(output_dim, size, use_bias=False, data_format='channels_first')), [np.random.random((output_dim, input_dim, size, size, size))], (None, input_dim, 4, 4, 4), ], [ (keras.layers.GRUV1(output_dim)), [np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,)), np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,)), np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,))], (None, 4, input_dim), ], [ (keras.layers.LSTMV1(output_dim)), [np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,)), np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,)), np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,)), np.random.random((input_dim, output_dim)), np.random.random((output_dim, output_dim)), np.random.random((output_dim,))], (None, 4, input_dim), ], ] for layer, weights, input_shape in cases: layer.build(input_shape) _ = hdf5_format.preprocess_weights_for_loading( layer, weights, original_keras_version='1') model = keras.models.Sequential([keras.layers.Dense(2, input_dim=2)]) _ = hdf5_format.preprocess_weights_for_loading( model, model.weights, original_keras_version='1') x = keras.Input((2,)) y = keras.layers.Dense(2)(x) model = keras.models.Model(x, y) _ = hdf5_format.preprocess_weights_for_loading( model, model.weights, original_keras_version='1') @parameterized.named_parameters( ('gru', keras.layers.GRU, { 'units': 2, 'input_shape': (3, 5) }), ('gru_with_reset_after', keras.layers.GRU, { 'units': 2, 'input_shape': (3, 5), 'reset_after': True }), ('lstm', keras.layers.LSTM, { 'units': 2, 'input_shape': (3, 5) }), ('cudnngru', keras.layers.CuDNNGRU, { 'units': 2, 'input_shape': (3, 5) }), ('cudnnlstm', keras.layers.CuDNNLSTM, { 'units': 2, 'input_shape': (3, 5) })) def test_preprocess_weights_for_loading_rnn_should_be_idempotent( self, layer_class, layer_args): with self.cached_session(): layer = layer_class(**layer_args) layer.build(input_shape=layer_args.get('input_shape')) weights1 = layer.get_weights() weights2 = hdf5_format.preprocess_weights_for_loading( layer, weights1) _ = [ self.assertAllClose(x, y, rtol=1e-05) for (x, y) in zip(weights1, weights2) ] def test_sequential_weight_loading(self): if h5py is None: return h5_path = self._save_model_dir('test.h5') num_hidden = 5 input_dim = 3 batch_size = 5 num_classes = 2 with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(num_hidden, input_dim=input_dim)) model.add(keras.layers.Dense(num_classes)) x = np.random.random((batch_size, input_dim)) ref_y = model.predict(x) model.save_weights(h5_path) model = keras.models.Sequential() model.add(keras.layers.Dense(num_hidden, input_dim=input_dim)) model.add(keras.layers.Dense(num_classes)) model.load_weights(h5_path) y = model.predict(x) self.assertAllClose(y, ref_y) @keras_parameterized.run_with_all_saved_model_formats( exclude_formats=['tf_no_traces']) def test_nested_model_weight_loading(self): save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() batch_size = 5 shape = (None, None, 3) with self.cached_session(): def gen_model(): def seq_model(): model = keras.models.Sequential([ keras.layers.Conv2D(3, 1, input_shape=shape), keras.layers.BatchNormalization()]) return model x = inner_inputs = keras.layers.Input((None, None, 3)) x = seq_model()(x) x = seq_model()(x) inner_model = keras.models.Model(inner_inputs, x) inputs = keras.layers.Input(shape) return keras.models.Model(inputs, inner_model(inputs)) model = gen_model() x = np.random.random((batch_size, 1, 1, 3)) ref_y = model.predict(x) model.save_weights(saved_model_dir, save_format=save_format) model = gen_model() model.load_weights(saved_model_dir) y = model.predict(x) self.assertAllClose(y, ref_y) def test_sequential_weight_loading_group_name_with_incorrect_length(self): if h5py is None: return h5_path = self._save_model_dir('test.h5') num_hidden = 5 input_dim = 3 num_classes = 2 with self.cached_session(): ref_model = keras.models.Sequential() ref_model.add(keras.layers.Dense(num_hidden, input_dim=input_dim, name='d1')) ref_model.add(keras.layers.Dense(num_classes, name='d2')) ref_model.compile(loss=keras.losses.MSE, optimizer='rmsprop', metrics=[keras.metrics.categorical_accuracy]) f_ref_model = h5py.File(h5_path, 'w') hdf5_format.save_weights_to_hdf5_group(f_ref_model, ref_model) f_model = h5py.File(h5_path, 'r') model = keras.models.Sequential() model.add(keras.layers.Dense(num_hidden, use_bias=False, input_dim=input_dim, name='d1')) model.add(keras.layers.Dense(num_classes, name='d2')) model.compile(loss=keras.losses.MSE, optimizer='rmsprop', metrics=[keras.metrics.categorical_accuracy]) with self.assertRaises( ValueError, msg='Weight count mismatch for layer #0 (named d1). ' 'Layer expects 1 weight(s). Received 2 saved weight(s)'): hdf5_format.load_weights_from_hdf5_group_by_name(f_model, model) hdf5_format.load_weights_from_hdf5_group_by_name( f_model, model, skip_mismatch=True) self.assertAllClose(keras.backend.get_value(ref_model.layers[1].kernel), keras.backend.get_value(model.layers[1].kernel)) def test_sequential_weight_loading_group_name_with_incorrect_shape(self): if h5py is None: return h5_path = self._save_model_dir('test.h5') num_hidden = 5 input_dim = 3 num_classes = 2 with tf.Graph().as_default(), self.cached_session(): ref_model = keras.models.Sequential() ref_model.add(keras.layers.Dense(num_hidden, input_dim=input_dim, name='d1')) ref_model.add(keras.layers.Dense(num_classes, name='d2')) ref_model.compile(loss=keras.losses.MSE, optimizer=optimizer_v1.RMSprop(lr=0.0001), metrics=[keras.metrics.categorical_accuracy]) f_ref_model = h5py.File(h5_path, 'w') keras.backend.set_value(ref_model.layers[1].bias, [3.5] * num_classes) hdf5_format.save_weights_to_hdf5_group(f_ref_model, ref_model) f_model = h5py.File(h5_path, 'r') model = keras.models.Sequential() model.add(keras.layers.Dense(num_hidden + 5, input_dim=input_dim, name='d1')) model.add(keras.layers.Dense(num_classes, name='d2')) model.compile(loss=keras.losses.MSE, optimizer=optimizer_v1.RMSprop(lr=0.0001), metrics=[keras.metrics.categorical_accuracy]) with self.assertRaises( ValueError, msg='Shape mismatch in layer #0 (named d1) for weight d1_1/kernel:0. ' 'Weight expects shape (3, 10). ' 'Received saved weight with shape (3, 5)'): hdf5_format.load_weights_from_hdf5_group_by_name(f_model, model) hdf5_format.load_weights_from_hdf5_group_by_name( f_model, model, skip_mismatch=True) self.assertAllClose([3.5] * num_classes, keras.backend.get_value(model.layers[1].bias)) @keras_parameterized.run_with_all_saved_model_formats( exclude_formats=['tf_no_traces']) @keras_parameterized.run_with_all_model_types def test_load_weights_from_saved_model(self): save_path = self._save_model_dir() save_format = testing_utils.get_save_format() if save_format == 'h5' and testing_utils.get_model_type() == 'subclass': # TODO(b/173646281): HDF5 format currently does not allow saving # subclassed models. return with self.cached_session(): model = testing_utils.get_small_mlp(1, 4, input_dim=3) data = np.random.random((1, 3)) labels = np.random.random((1, 4)) model.compile(loss='mse', optimizer='rmsprop') model.fit(data, labels) model.save(save_path, save_format=save_format) new_model = testing_utils.get_small_mlp(1, 4, input_dim=3) if testing_utils.get_model_type() == 'subclass': # Call on test data to build the model. new_model.predict(data) new_model.load_weights(save_path) self.assertAllClose(model.weights, new_model.weights) class SubclassedModel(training.Model): def __init__(self): super(SubclassedModel, self).__init__() self.x_layer = keras.layers.Dense(3) self.b_layer = keras.layers.Dense(1) def call(self, a): return self.b_layer(self.x_layer(a)) class TestWeightSavingAndLoadingTFFormat(tf.test.TestCase, parameterized.TestCase): @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_tensorflow_format_overwrite(self): with self.cached_session() as session: model = SubclassedModel() temp_dir = self.get_temp_dir() prefix = os.path.join(temp_dir, 'ckpt') x = tf.constant(np.random.random((3, 2)), dtype=tf.float32) executing_eagerly = tf.executing_eagerly() model(x) # pylint: disable=not-callable if not executing_eagerly: session.run([v.initializer for v in model.variables]) model.save_weights(prefix, save_format='tensorflow') model.save_weights(prefix, save_format='tensorflow', overwrite=True) with self.assertRaises(EOFError): # Indirectly tests that the user is prompted model.save_weights(prefix, save_format='tensorflow', overwrite=False) def test_no_default_session(self): with tf.Graph().as_default(): self.assertFalse(tf.compat.v1.get_default_session()) data = np.random.random((1000, 32)).astype(np.float32) labels = np.random.random((1000, 10)).astype(np.float32) model = keras.models.Sequential([ keras.layers.Dense(10, activation='softmax'), keras.layers.Dense(10, activation='softmax')]) model.compile(optimizer=tf.compat.v1.train.RMSPropOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels) fname = os.path.join(self.get_temp_dir(), 'weights', 'ckpt') model.save_weights(fname) model.load_weights(fname) def test_no_graph_pollution(self): with tf.compat.v1.get_default_graph().as_default(): graph = tf.Graph() with graph.as_default(), self.session(graph) as session: model = SubclassedModel() temp_dir = self.get_temp_dir() prefix = os.path.join(temp_dir, 'ckpt') x = tf.constant(np.random.random((3, 2)), dtype=tf.float32) model(x) # pylint: disable=not-callable session.run([v.initializer for v in model.variables]) model.save_weights(prefix, save_format='tensorflow') op_count = len(graph.get_operations()) model.save_weights(prefix, save_format='tensorflow') self.assertLen(graph.get_operations(), op_count) model.load_weights(prefix) op_count = len(graph.get_operations()) model.load_weights(prefix) self.assertLen(graph.get_operations(), op_count) def _weight_loading_test_template(self, make_model_fn): with self.cached_session(): model = make_model_fn() model.compile( loss='mse', optimizer=tf.compat.v1.train.RMSPropOptimizer(0.1), metrics=['acc', keras.metrics.CategoricalAccuracy()]) temp_dir = self.get_temp_dir() prefix = os.path.join(temp_dir, 'ckpt') train_x = np.random.random((3, 2)) train_y = np.random.random((3,)) x = tf.constant(train_x, dtype=tf.float32) model.train_on_batch(train_x, train_y) model.save_weights(prefix, save_format='tf') ref_y_before_train = model.predict(train_x) model.train_on_batch(train_x, train_y) ref_y_after_train = model.predict(train_x) for v in model.variables: self.evaluate( v.assign(tf.random.normal(shape=tf.shape(v)))) self.addCleanup(shutil.rmtree, temp_dir) model.load_weights(prefix) self.assertAllClose(ref_y_before_train, self.evaluate(model(x))) # Test restore-on-create if this is a subclassed Model (graph Networks # will have already created their variables). load_model = make_model_fn() load_model.load_weights(prefix) self.assertAllClose( ref_y_before_train, self.evaluate(load_model(x))) load_model = make_model_fn() load_model.load_weights(prefix) # We need to run some of the restore ops for predict(), but not all # variables have been created yet (optimizer slot variables). Tests # incremental restore. load_model.predict(train_x) load_model.compile( loss='mse', optimizer=tf.compat.v1.train.RMSPropOptimizer(0.1), metrics=['acc', keras.metrics.CategoricalAccuracy()]) load_model.train_on_batch(train_x, train_y) self.assertAllClose(ref_y_after_train, self.evaluate(load_model(x))) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_weight_loading_graph_model(self): def _make_graph_model(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3)(a) b = keras.layers.Dense(1)(x) return keras.models.Model(a, b) self._weight_loading_test_template(_make_graph_model) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_weight_loading_subclassed_model(self): self._weight_loading_test_template(SubclassedModel) def _new_layer_weight_loading_test_template( self, first_model_fn, second_model_fn): with self.cached_session() as session: model = first_model_fn() temp_dir = self.get_temp_dir() prefix = os.path.join(temp_dir, 'ckpt') x = tf.constant(np.random.random((3, 2)), dtype=tf.float32) executing_eagerly = tf.executing_eagerly() ref_y_tensor = model(x) if not executing_eagerly: session.run([v.initializer for v in model.variables]) ref_y = self.evaluate(ref_y_tensor) model.save_weights(prefix) self.assertEqual( prefix, tf.train.latest_checkpoint(temp_dir)) for v in model.variables: self.evaluate( v.assign(tf.random.normal(shape=tf.shape(v)))) self.addCleanup(shutil.rmtree, temp_dir) second_model = second_model_fn() status = second_model.load_weights(prefix) second_model(x) status.run_restore_ops() second_model.save_weights(prefix) # Check that the second model's checkpoint loads into the original model status = model.load_weights(prefix) status.run_restore_ops(session) y = self.evaluate(model(x)) self.assertAllClose(ref_y, y) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_weight_loading_graph_model_added_layer(self): def _save_graph_model(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3, name='first')(a) b = keras.layers.Dense(1, name='second')(x) return keras.models.Model(a, b) def _restore_graph_model(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3, name='first')(a) y = keras.layers.Dense(1, name='second')(x) b = keras.layers.Dense(3, name='secondjr')(y) return keras.models.Model(a, b) self._new_layer_weight_loading_test_template( _save_graph_model, _restore_graph_model) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_weight_loading_graph_model_added_no_weight_layer(self): def _save_graph_model(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3, name='first')(a) b = keras.layers.Dense(1, name='second')(x) return keras.models.Model(a, b) def _restore_graph_model(): a = keras.layers.Input(shape=(2,)) x = keras.layers.Dense(3, name='first')(a) b = keras.layers.Dense(1, name='second')(x) y = keras.layers.Dropout(rate=0.1)(b) return keras.models.Model(a, y) self._new_layer_weight_loading_test_template( _save_graph_model, _restore_graph_model) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_weight_loading_subclassed_model_added_layer(self): class SubclassedModelRestore(training.Model): def __init__(self): super(SubclassedModelRestore, self).__init__() self.x_layer = keras.layers.Dense(3) self.y_layer = keras.layers.Dense(3) self.b_layer = keras.layers.Dense(1) def call(self, a): return self.b_layer(self.y_layer(self.x_layer(a))) self._new_layer_weight_loading_test_template( SubclassedModel, SubclassedModelRestore) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_incompatible_checkpoint(self): save_path = tf.train.Checkpoint().save( os.path.join(self.get_temp_dir(), 'ckpt')) m = DummySubclassModel() with self.assertRaisesRegex(AssertionError, 'Nothing to load'): m.load_weights(save_path) m.dense = keras.layers.Dense(2) m.dense(tf.constant([[1.]])) with self.assertRaisesRegex(AssertionError, 'Nothing except the root object matched'): m.load_weights(save_path) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_directory_passed(self): with self.cached_session(): m = DummySubclassModel() v = m.add_weight(name='v', shape=[]) self.evaluate(v.assign(42.)) prefix = os.path.join(self.get_temp_dir(), str(uuid.uuid4()), 'ckpt/') m.save_weights(prefix) self.evaluate(v.assign(2.)) m.load_weights(prefix) self.assertEqual(42., self.evaluate(v)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_relative_path(self): with self.cached_session(): m = DummySubclassModel() v = m.add_weight(name='v', shape=[]) os.chdir(self.get_temp_dir()) prefix = 'ackpt' self.evaluate(v.assign(42.)) m.save_weights(prefix) self.assertTrue(tf.io.gfile.exists('ackpt.index')) self.evaluate(v.assign(1.)) m.load_weights(prefix) self.assertEqual(42., self.evaluate(v)) prefix = 'subdir/ackpt' self.evaluate(v.assign(43.)) m.save_weights(prefix) self.assertTrue(tf.io.gfile.exists('subdir/ackpt.index')) self.evaluate(v.assign(2.)) m.load_weights(prefix) self.assertEqual(43., self.evaluate(v)) prefix = 'ackpt/' self.evaluate(v.assign(44.)) m.save_weights(prefix) self.assertTrue(tf.io.gfile.exists('ackpt/.index')) self.evaluate(v.assign(3.)) m.load_weights(prefix) self.assertEqual(44., self.evaluate(v)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_nonexistent_prefix_directory(self): with self.cached_session(): m = DummySubclassModel() v = m.add_weight(name='v', shape=[]) self.evaluate(v.assign(42.)) prefix = os.path.join(self.get_temp_dir(), str(uuid.uuid4()), 'bckpt') m.save_weights(prefix) self.evaluate(v.assign(2.)) m.load_weights(prefix) self.assertEqual(42., self.evaluate(v)) class DummySubclassModel(training.Model): pass if __name__ == '__main__': tf.test.main()
24,805
36.079223
83
py
keras
keras-master/keras/saving/save.py
# 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 model saving code.""" import tensorflow.compat.v2 as tf from keras.saving import hdf5_format from keras.saving import saving_utils from keras.saving.saved_model import load as saved_model_load from keras.saving.saved_model import load_context from keras.saving.saved_model import save as saved_model_save from keras.utils import generic_utils from keras.utils import traceback_utils from keras.utils.io_utils import path_to_string from tensorflow.python.util.tf_export import keras_export # pylint: disable=g-import-not-at-top try: import h5py except ImportError: h5py = None # pylint: enable=g-import-not-at-top @keras_export('keras.models.save_model') @traceback_utils.filter_traceback def save_model(model, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True): # pylint: disable=line-too-long """Saves a model as a TensorFlow SavedModel or HDF5 file. See the [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) for details. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) The SavedModel and HDF5 file contains: - the model's configuration (topology) - the model's weights - the model's optimizer's state (if any) Thus models can be reinstantiated in the exact same state, without any of the code used for model definition or training. Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as `"dense_1/kernel:0"`. It is recommended that you use the layer properties to access specific variables, e.g. `model.get_layer("dense_1").kernel`. __SavedModel serialization format__ Keras SavedModel uses `tf.saved_model.save` to save the model and all trackable objects attached to the model (e.g. layers and variables). The model config, weights, and optimizer are saved in the SavedModel. Additionally, for every Keras layer attached to the model, the SavedModel stores: * the config and metadata -- e.g. name, dtype, trainable status * traced call and loss functions, which are stored as TensorFlow subgraphs. The traced functions allow the SavedModel format to save and load custom layers without the original class definition. You can choose to not save the traced functions by disabling the `save_traces` option. This will decrease the time it takes to save the model and the amount of disk space occupied by the output SavedModel. If you enable this option, then you _must_ provide all custom class definitions when loading the model. See the `custom_objects` argument in `tf.keras.models.load_model`. Args: model: Keras model instance to be saved. filepath: One of the following: - String or `pathlib.Path` object, path where to save the model - `h5py.File` object where to save the model overwrite: Whether we should overwrite any existing model at the target location, or instead ask the user with a manual prompt. include_optimizer: If True, save optimizer's state together. save_format: Either 'tf' or 'h5', indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. signatures: Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the `signatures` argument in `tf.saved_model.save` for details. options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` object that specifies options for saving to SavedModel. save_traces: (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to `True`. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a `get_config()` method. Raises: ImportError: If save format is hdf5, and h5py is not available. """ # pylint: enable=line-too-long from keras.engine import sequential # pylint: disable=g-import-not-at-top default_format = 'tf' if tf.__internal__.tf2.enabled() else 'h5' save_format = save_format or default_format filepath = path_to_string(filepath) # If the user has not already called fit or built the underlying metrics, we # should do that before saving to ensure the metric names have all # appropriate name transformations applied. saving_utils.try_build_compiled_arguments(model) if (save_format == 'h5' or (h5py is not None and isinstance(filepath, h5py.File)) or saving_utils.is_hdf5_filepath(filepath)): # TODO(b/130258301): add utility method for detecting model type. if (not model._is_graph_network and # pylint:disable=protected-access not isinstance(model, sequential.Sequential)): raise NotImplementedError( 'Saving the model to HDF5 format requires the model to be a ' 'Functional model or a Sequential model. It does not work for ' 'subclassed models, because such models are defined via the body of ' 'a Python method, which isn\'t safely serializable. Consider saving ' 'to the Tensorflow SavedModel format (by setting save_format="tf") ' 'or using `save_weights`.') hdf5_format.save_model_to_hdf5( model, filepath, overwrite, include_optimizer) else: with generic_utils.SharedObjectSavingScope(): saved_model_save.save(model, filepath, overwrite, include_optimizer, signatures, options, save_traces) @keras_export('keras.models.load_model') @traceback_utils.filter_traceback def load_model(filepath, custom_objects=None, compile=True, options=None): # pylint: disable=redefined-builtin """Loads a model saved via `model.save()`. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as `"dense_1/kernel:0"`. It is recommended that you use the layer properties to access specific variables, e.g. `model.get_layer("dense_1").kernel`. Args: filepath: One of the following: - String or `pathlib.Path` object, path to the saved model - `h5py.File` object from which to load the model custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. compile: Boolean, whether to compile the model after loading. options: Optional `tf.saved_model.LoadOptions` object that specifies options for loading from SavedModel. Returns: A Keras model instance. If the original model was compiled, and saved with the optimizer, then the returned model will be compiled. Otherwise, the model will be left uncompiled. In the case that an uncompiled model is returned, a warning is displayed if the `compile` argument is set to `True`. Raises: ImportError: if loading from an hdf5 file and h5py is not available. IOError: In case of an invalid savefile. """ with generic_utils.SharedObjectLoadingScope(): with generic_utils.CustomObjectScope(custom_objects or {}): with load_context.load_context(options): if (h5py is not None and (isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))): return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile) filepath = path_to_string(filepath) if isinstance(filepath, str): return saved_model_load.load(filepath, compile, options) raise IOError( 'Unable to load model. Filepath is not an hdf5 file (or h5py is not ' f'available) or SavedModel. Received: filepath={filepath}') # Inject the load_model function to keras_deps to remove the dependency # from TFLite to Keras. tf.__internal__.register_load_model_function(load_model)
9,504
42.801843
111
py
keras
keras-master/keras/saving/losses_serialization_test.py
# 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 Keras losses serialization.""" import tensorflow.compat.v2 as tf import os import shutil from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import layers from keras import losses from keras import optimizer_v2 from keras import testing_utils from keras.utils import generic_utils from keras.utils import losses_utils try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None # Custom loss class class MyMeanAbsoluteError(losses.LossFunctionWrapper): def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='mean_absolute_error'): super(MyMeanAbsoluteError, self).__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 = testing_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]) @keras_parameterized.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(keras_parameterized.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.], [1.], [2.]], dtype='float32') self.y = np.array([[0.5], [2.], [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 generic_utils.custom_object_scope({ 'MyMeanAbsoluteError': MyMeanAbsoluteError, 'my_mae': my_mae, 'Bias': testing_utils.Bias, }): model = _get_multi_io_model() model.compile( optimizer_v2.gradient_descent.SGD(0.1), loss=value, run_eagerly=testing_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., 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_v2.gradient_descent.SGD(0.1), loss=value, run_eagerly=testing_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., 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': testing_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()
6,673
33.580311
80
py
keras
keras-master/keras/saving/saved_model_experimental_test.py
# 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. # ============================================================================== # pylint: disable=protected-access """Tests for saving/loading function for keras Model.""" import tensorflow.compat.v2 as tf import os import shutil from absl.testing import parameterized import numpy as np import keras from keras import optimizer_v1 from keras.engine import training as model_lib from keras.optimizer_v2 import adadelta from keras.optimizer_v2 import rmsprop from keras.saving import saved_model_experimental as keras_saved_model from keras.saving import utils_v1 as model_utils from keras.utils import control_flow_util from keras.utils import mode_keys class TestModelSavingandLoading(parameterized.TestCase, tf.test.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def test_saving_sequential_model(self): with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) model.compile( loss=keras.losses.MSE, optimizer=rmsprop.RMSprop(lr=0.0001), metrics=[keras.metrics.categorical_accuracy], sample_weight_mode='temporal') x = np.random.random((1, 3)) y = np.random.random((1, 3, 3)) model.train_on_batch(x, y) ref_y = model.predict(x) saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model(model, saved_model_dir) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) def test_saving_sequential_model_without_compile(self): with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) x = np.random.random((1, 3)) ref_y = model.predict(x) saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model(model, saved_model_dir) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) def test_saving_functional_model(self): with self.cached_session(): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) output = keras.layers.Dense(3)(x) model = keras.models.Model(inputs, output) model.compile( loss=keras.losses.MSE, optimizer=rmsprop.RMSprop(lr=0.0001), metrics=[keras.metrics.categorical_accuracy]) x = np.random.random((1, 3)) y = np.random.random((1, 3)) model.train_on_batch(x, y) ref_y = model.predict(x) saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model(model, saved_model_dir) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) def test_saving_functional_model_without_compile(self): with self.cached_session(): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) output = keras.layers.Dense(3)(x) model = keras.models.Model(inputs, output) x = np.random.random((1, 3)) y = np.random.random((1, 3)) ref_y = model.predict(x) saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model(model, saved_model_dir) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) def test_saving_with_tf_optimizer(self): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) model.compile( loss='mse', optimizer=tf.compat.v1.train.RMSPropOptimizer(0.1), metrics=['acc']) x = np.random.random((1, 3)) y = np.random.random((1, 3)) model.train_on_batch(x, y) ref_y = model.predict(x) saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model(model, saved_model_dir) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir) loaded_model.compile( loss='mse', optimizer=tf.compat.v1.train.RMSPropOptimizer(0.1), metrics=['acc']) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) # test that new updates are the same with both models x = np.random.random((1, 3)) y = np.random.random((1, 3)) ref_loss = model.train_on_batch(x, y) loss = loaded_model.train_on_batch(x, y) self.assertAllClose(ref_loss, loss, atol=1e-05) ref_y = model.predict(x) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) # test saving/loading again saved_model_dir2 = self._save_model_dir('saved_model_2') keras_saved_model.export_saved_model(loaded_model, saved_model_dir2) loaded_model = keras_saved_model.load_from_saved_model(saved_model_dir2) y = loaded_model.predict(x) self.assertAllClose(ref_y, y, atol=1e-05) def test_saving_subclassed_model_raise_error(self): # For now, saving subclassed model should raise an error. It should be # avoided later with loading from SavedModel.pb. class SubclassedModel(model_lib.Model): def __init__(self): super(SubclassedModel, self).__init__() self.layer1 = keras.layers.Dense(3) self.layer2 = keras.layers.Dense(1) def call(self, inp): return self.layer2(self.layer1(inp)) model = SubclassedModel() saved_model_dir = self._save_model_dir() with self.assertRaises(NotImplementedError): keras_saved_model.export_saved_model(model, saved_model_dir) class LayerWithLearningPhase(keras.engine.base_layer.Layer): def build(self, input_shape): self.input_spec = keras.layers.InputSpec(shape=[None] * len(input_shape)) self.built = True def call(self, x, training=None): if training is None: training = keras.backend.learning_phase() output = control_flow_util.smart_cond(training, lambda: x * 0, lambda: tf.identity(x)) if not tf.executing_eagerly(): output._uses_learning_phase = True # pylint: disable=protected-access return output def compute_output_shape(self, input_shape): return input_shape def functional_model(uses_learning_phase=True): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) x = keras.layers.Dense(3)(x) if uses_learning_phase: x = LayerWithLearningPhase()(x) return keras.models.Model(inputs, x) def sequential_model(uses_learning_phase=True): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) if uses_learning_phase: model.add(LayerWithLearningPhase()) return model def sequential_model_without_input_shape(uses_learning_phase=True): model = keras.models.Sequential() model.add(keras.layers.Dense(2)) model.add(keras.layers.Dense(3)) if uses_learning_phase: model.add(LayerWithLearningPhase()) return model class Subclassed(keras.models.Model): def __init__(self): super(Subclassed, self).__init__() self.dense1 = keras.layers.Dense(2) self.dense2 = keras.layers.Dense(3) def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) return x def subclassed_model(): return Subclassed() def load_model(sess, path, mode): tags = model_utils.EXPORT_TAG_MAP[mode] sig_def_key = model_utils.SIGNATURE_KEY_MAP[mode] meta_graph_def = tf.compat.v1.saved_model.load(sess, tags, path) inputs = { k: sess.graph.get_tensor_by_name(v.name) for k, v in meta_graph_def.signature_def[sig_def_key].inputs.items()} outputs = { k: sess.graph.get_tensor_by_name(v.name) for k, v in meta_graph_def.signature_def[sig_def_key].outputs.items()} return inputs, outputs, meta_graph_def def get_train_op(meta_graph_def): graph = tf.compat.v1.get_default_graph() signature_def = meta_graph_def.signature_def['__saved_model_train_op'] op_name = signature_def.outputs['__saved_model_train_op'].name return graph.as_graph_element(op_name) class TestModelSavedModelExport(tf.test.TestCase, parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) @parameterized.parameters( { 'model_builder': functional_model, 'uses_learning_phase': True, 'optimizer_cls': adadelta.Adadelta, 'train_before_export': True}, { 'model_builder': functional_model, 'uses_learning_phase': True, 'optimizer_cls': tf.compat.v1.train.AdadeltaOptimizer, 'train_before_export': False}, { 'model_builder': functional_model, 'uses_learning_phase': False, 'optimizer_cls': None, 'train_before_export': False}, { 'model_builder': sequential_model, 'uses_learning_phase': True, 'optimizer_cls': tf.compat.v1.train.AdadeltaOptimizer, 'train_before_export': True}, { 'model_builder': sequential_model, 'uses_learning_phase': True, 'optimizer_cls': adadelta.Adadelta, 'train_before_export': False}, { 'model_builder': sequential_model, 'uses_learning_phase': False, 'optimizer_cls': None, 'train_before_export': False}, { 'model_builder': sequential_model_without_input_shape, 'uses_learning_phase': True, 'optimizer_cls': tf.compat.v1.train.AdadeltaOptimizer, 'train_before_export': False}) def testSaveAndLoadSavedModelExport( self, model_builder, uses_learning_phase, optimizer_cls, train_before_export): optimizer = None if optimizer_cls is None else optimizer_cls() saved_model_dir = self._save_model_dir() np.random.seed(130) input_arr = np.random.random((1, 3)) target_arr = np.random.random((1, 3)) model = model_builder(uses_learning_phase) if optimizer is not None: model.compile( loss='mse', optimizer=optimizer, metrics=['mae']) if train_before_export: model.train_on_batch(input_arr, target_arr) ref_loss, ref_mae = model.evaluate(input_arr, target_arr) ref_predict = model.predict(input_arr) # Export SavedModel keras_saved_model.export_saved_model(model, saved_model_dir) input_name = model.input_names[0] output_name = model.output_names[0] target_name = output_name + '_target' # Load predict graph, and test predictions with tf.compat.v1.Session(graph=tf.Graph()) as sess: inputs, outputs, _ = load_model(sess, saved_model_dir, mode_keys.ModeKeys.PREDICT) predictions = sess.run(outputs[output_name], {inputs[input_name]: input_arr}) self.assertAllClose(ref_predict, predictions, atol=1e-05) if optimizer: # Load eval graph, and test predictions, loss and metric values with tf.compat.v1.Session(graph=tf.Graph()) as sess: inputs, outputs, _ = load_model(sess, saved_model_dir, mode_keys.ModeKeys.TEST) # First obtain the loss and predictions, and run the metric update op by # feeding in the inputs and targets. metrics_name = 'mae' if tf.__internal__.tf2.enabled() else 'mean_absolute_error' metrics_update_op_key = 'metrics/' + metrics_name + '/update_op' metrics_value_op_key = 'metrics/' + metrics_name + '/value' loss, predictions, _ = sess.run( (outputs['loss'], outputs['predictions/' + output_name], outputs[metrics_update_op_key]), { inputs[input_name]: input_arr, inputs[target_name]: target_arr }) # The metric value should be run after the update op, to ensure that it # reflects the correct value. metric_value = sess.run(outputs[metrics_value_op_key]) self.assertEqual(int(train_before_export), sess.run(tf.compat.v1.train.get_global_step())) self.assertAllClose(ref_loss, loss, atol=1e-05) self.assertAllClose(ref_mae, metric_value, atol=1e-05) self.assertAllClose(ref_predict, predictions, atol=1e-05) # Load train graph, and check for the train op, and prediction values with tf.compat.v1.Session(graph=tf.Graph()) as sess: inputs, outputs, meta_graph_def = load_model( sess, saved_model_dir, mode_keys.ModeKeys.TRAIN) self.assertEqual(int(train_before_export), sess.run(tf.compat.v1.train.get_global_step())) self.assertIn('loss', outputs) self.assertIn(metrics_update_op_key, outputs) self.assertIn(metrics_value_op_key, outputs) self.assertIn('predictions/' + output_name, outputs) # Train for a step train_op = get_train_op(meta_graph_def) train_outputs, _ = sess.run( [outputs, train_op], {inputs[input_name]: input_arr, inputs[target_name]: target_arr}) self.assertEqual(int(train_before_export) + 1, sess.run(tf.compat.v1.train.get_global_step())) if uses_learning_phase: self.assertAllClose( [[0, 0, 0]], train_outputs['predictions/' + output_name], atol=1e-05) else: self.assertNotAllClose( [[0, 0, 0]], train_outputs['predictions/' + output_name], atol=1e-05) def testSaveAndLoadSavedModelWithCustomObject(self): saved_model_dir = self._save_model_dir() with tf.compat.v1.Session(graph=tf.Graph()) as sess: def relu6(x): return keras.backend.relu(x, max_value=6) inputs = keras.layers.Input(shape=(1,)) outputs = keras.layers.Activation(relu6)(inputs) model = keras.models.Model(inputs, outputs) keras_saved_model.export_saved_model( model, saved_model_dir, custom_objects={'relu6': relu6}) with tf.compat.v1.Session(graph=tf.Graph()) as sess: inputs, outputs, _ = load_model(sess, saved_model_dir, mode_keys.ModeKeys.PREDICT) input_name = model.input_names[0] output_name = model.output_names[0] predictions = sess.run( outputs[output_name], {inputs[input_name]: [[7], [-3], [4]]}) self.assertAllEqual([[6], [0], [4]], predictions) def testAssertModelCloneSameObjectsIgnoreOptimizer(self): input_arr = np.random.random((1, 3)) target_arr = np.random.random((1, 3)) model_graph = tf.Graph() clone_graph = tf.Graph() # Create two models with the same layers but different optimizers. with tf.compat.v1.Session(graph=model_graph): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) x = keras.layers.Dense(3)(x) model = keras.models.Model(inputs, x) model.compile(loss='mse', optimizer=tf.compat.v1.train.AdadeltaOptimizer()) model.train_on_batch(input_arr, target_arr) with tf.compat.v1.Session(graph=clone_graph): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) x = keras.layers.Dense(3)(x) clone = keras.models.Model(inputs, x) clone.compile(loss='mse', optimizer=optimizer_v1.RMSprop(lr=0.0001)) clone.train_on_batch(input_arr, target_arr) keras_saved_model._assert_same_non_optimizer_objects( model, model_graph, clone, clone_graph) def testAssertModelCloneSameObjectsThrowError(self): input_arr = np.random.random((1, 3)) target_arr = np.random.random((1, 3)) model_graph = tf.Graph() clone_graph = tf.Graph() # Create two models with the same layers but different optimizers. with tf.compat.v1.Session(graph=model_graph): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) x = keras.layers.Dense(3)(x) model = keras.models.Model(inputs, x) model.compile(loss='mse', optimizer=tf.compat.v1.train.AdadeltaOptimizer()) model.train_on_batch(input_arr, target_arr) with tf.compat.v1.Session(graph=clone_graph): inputs = keras.layers.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) x = keras.layers.Dense(4)(x) x = keras.layers.Dense(3)(x) clone = keras.models.Model(inputs, x) clone.compile(loss='mse', optimizer=optimizer_v1.RMSprop(lr=0.0001)) clone.train_on_batch(input_arr, target_arr) def testSaveSequentialModelWithoutInputShapes(self): model = sequential_model_without_input_shape(True) # A Sequential model that hasn't been built should raise an error. with self.assertRaisesRegex( ValueError, 'Weights for sequential model have not yet been created'): keras_saved_model.export_saved_model(model, '') # Even with input_signature, the model's weights has not been created. with self.assertRaisesRegex( ValueError, 'Weights for sequential model have not yet been created'): saved_model_dir = self._save_model_dir() keras_saved_model.export_saved_model( model, saved_model_dir, input_signature=tf.TensorSpec( shape=(10, 11, 12, 13, 14), dtype=tf.float32, name='spec_input')) @parameterized.parameters( { 'model_builder': sequential_model_without_input_shape, 'input_signature': [tf.TensorSpec(shape=[None, 3], dtype=tf.float32)]}, { 'model_builder': subclassed_model, 'input_signature': [tf.TensorSpec(shape=[None, 3], dtype=tf.float32)]}) def testServingOnly(self, model_builder, input_signature): if tf.executing_eagerly(): saved_model_dir = self._save_model_dir() input_arr = np.random.random((5, 3)).astype(np.float32) model = model_builder() ref_predict = model.predict(input_arr) keras_saved_model.export_saved_model( model, saved_model_dir, serving_only=True, input_signature=input_signature) # Load predict graph, and test predictions with tf.compat.v1.Session(graph=tf.Graph()) as sess: inputs, outputs, _ = load_model(sess, saved_model_dir, mode_keys.ModeKeys.PREDICT) predictions = sess.run(outputs[next(iter(outputs.keys()))], {inputs[next(iter(inputs.keys()))]: input_arr}) self.assertAllClose(ref_predict, predictions, atol=1e-05) if __name__ == '__main__': tf.test.main()
19,986
35.944547
88
py
keras
keras-master/keras/saving/__init__.py
0
0
0
py
keras
keras-master/keras/saving/metrics_serialization_test.py
# 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 Keras metrics serialization.""" import tensorflow.compat.v2 as tf import os import shutil from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import layers from keras import metrics from keras import optimizer_v2 from keras import testing_utils from keras.utils import generic_utils try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None # Custom metric class MyMeanAbsoluteError(metrics.MeanMetricWrapper): def __init__(self, name='my_mae', dtype=None): super(MyMeanAbsoluteError, self).__init__(_my_mae, name, dtype=dtype) # Custom metric 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 = testing_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]) @keras_parameterized.run_all_keras_modes @parameterized.named_parameters( dict(testcase_name='string', value=['mae']), dict(testcase_name='built_in_fn', value=[metrics.mae]), dict(testcase_name='built_in_class', value=[metrics.MeanAbsoluteError]), dict(testcase_name='custom_fn', value=[_my_mae]), dict(testcase_name='custom_class', value=[MyMeanAbsoluteError]), dict( testcase_name='list_of_built_in_fn_and_list', value=[metrics.mae, [metrics.mae]]), dict( testcase_name='list_of_built_in_class_and_list', value=[metrics.MeanAbsoluteError, [metrics.MeanAbsoluteError]]), dict( testcase_name='list_of_custom_fn_and_list', value=[_my_mae, [_my_mae]]), dict( testcase_name='list_of_custom_class_and_list', value=[MyMeanAbsoluteError, [MyMeanAbsoluteError]]), dict( testcase_name='list_of_lists_of_custom_fns', value=[[_my_mae], [_my_mae, 'mae']]), dict( testcase_name='list_of_lists_of_custom_classes', value=[[MyMeanAbsoluteError], [MyMeanAbsoluteError, 'mae']]), dict( testcase_name='dict_of_list_of_string', value={ 'output': ['mae'], 'output_1': ['mae'], }), dict( testcase_name='dict_of_list_of_built_in_fn', value={ 'output': [metrics.mae], 'output_1': [metrics.mae], }), dict( testcase_name='dict_of_list_of_built_in_class', value={ 'output': [metrics.MeanAbsoluteError], 'output_1': [metrics.MeanAbsoluteError], }), dict( testcase_name='dict_of_list_of_custom_fn', value={ 'output': [_my_mae], 'output_1': [_my_mae], }), dict( testcase_name='dict_of_list_of_custom_class', value={ 'output': [MyMeanAbsoluteError], 'output_1': [MyMeanAbsoluteError], }), dict( testcase_name='dict_of_string', value={ 'output': 'mae', 'output_1': 'mae', }), dict( testcase_name='dict_of_built_in_fn', value={ 'output': metrics.mae, 'output_1': metrics.mae, }), dict( testcase_name='dict_of_built_in_class', value={ 'output': metrics.MeanAbsoluteError, 'output_1': metrics.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 MetricsSerialization(keras_parameterized.TestCase): def setUp(self): super(MetricsSerialization, self).setUp() tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir) self.model_filename = os.path.join(tmpdir, 'tmp_model_metric.h5') self.x = np.array([[0.], [1.], [2.]], dtype='float32') self.y = np.array([[0.5], [2.], [3.5]], dtype='float32') self.w = np.array([1.25, 0.5, 1.25], dtype='float32') def test_serializing_model_with_metric_with_custom_object_scope(self, value): def get_instance(x): if isinstance(x, str): return x if isinstance(x, type) and issubclass(x, metrics.Metric): return x() return x metric_input = tf.nest.map_structure(get_instance, value) weighted_metric_input = tf.nest.map_structure(get_instance, value) with generic_utils.custom_object_scope({ 'MyMeanAbsoluteError': MyMeanAbsoluteError, '_my_mae': _my_mae, 'Bias': testing_utils.Bias, }): model = _get_multi_io_model() model.compile( optimizer_v2.gradient_descent.SGD(0.1), 'mae', metrics=metric_input, weighted_metrics=weighted_metric_input, run_eagerly=testing_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., 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_metric_with_custom_objects(self, value): def get_instance(x): if isinstance(x, str): return x if isinstance(x, type) and issubclass(x, metrics.Metric): return x() return x metric_input = tf.nest.map_structure(get_instance, value) weighted_metric_input = tf.nest.map_structure(get_instance, value) model = _get_multi_io_model() model.compile( optimizer_v2.gradient_descent.SGD(0.1), 'mae', metrics=metric_input, weighted_metrics=weighted_metric_input, run_eagerly=testing_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., 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': testing_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()
8,389
32.426295
80
py
keras
keras-master/keras/saving/pickle_utils.py
# 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.""" # pylint: disable=g-bad-import-order import tensorflow.compat.v2 as tf import os import tarfile import io import uuid import numpy from keras.saving import save as save_module def deserialize_model_from_bytecode(serialized_model): """Reconstruct a Model from the output of `serialize_model_as_bytecode`. Args: serialized_model: (np.array) return value from `serialize_model_as_bytecode`. Returns: keras.Model: Keras Model instance. """ temp_dir = f"ram://{uuid.uuid4()}" b = io.BytesIO(serialized_model) with tarfile.open(fileobj=b, mode="r") as archive: for name in archive.getnames(): dest_path = os.path.join(temp_dir, name) member = archive.getmember(name) tf.io.gfile.makedirs(os.path.dirname(dest_path)) if member.isfile(): with tf.io.gfile.GFile(dest_path, "wb") as f: f.write(archive.extractfile(name).read()) model = save_module.load_model(temp_dir) tf.io.gfile.rmtree(temp_dir) return model def serialize_model_as_bytecode(model): """Convert a Keras Model into a bytecode representation for pickling. Args: model: (tf.keras.Model) Keras Model instance. Returns: tuple: tuple of arguments that can be sent to `deserialize_from_bytecode`. """ temp_dir = f"ram://{uuid.uuid4()}" model.save(temp_dir) b = io.BytesIO() with tarfile.open(fileobj=b, mode="w") as archive: for root, dirs, filenames in tf.io.gfile.walk(temp_dir): for dirname in dirs: dest_path = os.path.join(root, dirname) t = tarfile.TarInfo(dest_path) t.type = tarfile.DIRTYPE archive.addfile(t) for filename in filenames: dest_path = os.path.join(root, filename) with tf.io.gfile.GFile(dest_path, "rb") as f: info = tarfile.TarInfo(name=os.path.relpath(dest_path, temp_dir)) info.size = f.size() archive.addfile(tarinfo=info, fileobj=f) tf.io.gfile.rmtree(temp_dir) b.seek(0) return (numpy.asarray(memoryview(b.read())),)
2,778
32.890244
80
py
keras
keras-master/keras/saving/save_test.py
# 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 Keras model saving code.""" import tensorflow.compat.v2 as tf import collections import os import pathlib import shutil import tempfile import warnings from absl.testing import parameterized import numpy as np import keras from keras import combinations from keras import keras_parameterized from keras import losses from keras import optimizer_v1 from keras import optimizers from keras import testing_utils from keras.engine import functional from keras.engine import sequential from keras.feature_column import dense_features from keras.feature_column import sequence_feature_column as ksfc from keras.layers import core from keras.saving import model_config from keras.saving import save from keras.utils import generic_utils try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None class TestSaveModel(tf.test.TestCase, parameterized.TestCase): def setUp(self): super(TestSaveModel, self).setUp() self.model = testing_utils.get_small_sequential_mlp(1, 2, 3) self.subclassed_model = testing_utils.get_small_subclass_mlp(1, 2) def assert_h5_format(self, path): if h5py is not None: self.assertTrue(h5py.is_hdf5(path), 'Model saved at path {} is not a valid hdf5 file.' .format(path)) def assert_saved_model(self, path): tf.__internal__.saved_model.parse_saved_model(path) @testing_utils.run_v2_only def test_save_format_defaults(self): path = os.path.join(self.get_temp_dir(), 'model_path') save.save_model(self.model, path) self.assert_saved_model(path) @testing_utils.run_v2_only def test_save_format_defaults_pathlib(self): path = pathlib.Path(self.get_temp_dir()) / 'model_path' save.save_model(self.model, path) self.assert_saved_model(path) @testing_utils.run_v2_only def test_save_hdf5(self): path = os.path.join(self.get_temp_dir(), 'model') save.save_model(self.model, path, save_format='h5') self.assert_h5_format(path) with self.assertRaisesRegex( NotImplementedError, 'requires the model to be a Functional model or a Sequential model.'): save.save_model(self.subclassed_model, path, save_format='h5') @testing_utils.run_v2_only def test_save_load_hdf5_pathlib(self): path = pathlib.Path(self.get_temp_dir()) / 'model' save.save_model(self.model, path, save_format='h5') save.load_model(path) @testing_utils.run_v2_only def test_save_tf(self): path = os.path.join(self.get_temp_dir(), 'model') save.save_model(self.model, path, save_format='tf') self.assert_saved_model(path) with self.assertRaisesRegex(ValueError, 'input shapes have not been set'): save.save_model(self.subclassed_model, path, save_format='tf') self.subclassed_model.predict(np.random.random((3, 5))) save.save_model(self.subclassed_model, path, save_format='tf') self.assert_saved_model(path) @testing_utils.run_v2_only def test_save_load_tf_string(self): path = os.path.join(self.get_temp_dir(), 'model') save.save_model(self.model, path, save_format='tf') save.load_model(path) @testing_utils.run_v2_only def test_save_load_tf_pathlib(self): path = pathlib.Path(self.get_temp_dir()) / 'model' save.save_model(self.model, path, save_format='tf') save.load_model(path) @testing_utils.run_v2_only def test_save_load_weights_tf_pathlib(self): path = pathlib.Path(self.get_temp_dir()) / 'model' self.model.save_weights(path, save_format='tf') self.model.load_weights(path) @testing_utils.run_v2_only def test_save_load_weights_hdf5_pathlib(self): path = pathlib.Path(self.get_temp_dir()) / 'model' self.model.save_weights(path, save_format='h5') self.model.load_weights(path) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_saving_with_dense_features(self): cols = [ tf.feature_column.numeric_column('a'), tf.feature_column.indicator_column( tf.feature_column.categorical_column_with_vocabulary_list( 'b', ['one', 'two'])) ] input_layers = { 'a': keras.layers.Input(shape=(1,), name='a'), 'b': keras.layers.Input(shape=(1,), name='b', dtype='string') } fc_layer = dense_features.DenseFeatures(cols)(input_layers) output = keras.layers.Dense(10)(fc_layer) model = keras.models.Model(input_layers, output) model.compile( loss=keras.losses.MSE, optimizer='rmsprop', metrics=[keras.metrics.categorical_accuracy]) config = model.to_json() loaded_model = model_config.model_from_json(config) inputs_a = np.arange(10).reshape(10, 1) inputs_b = np.arange(10).reshape(10, 1).astype('str') with self.cached_session(): # Initialize tables for V1 lookup. if not tf.executing_eagerly(): self.evaluate(tf.compat.v1.tables_initializer()) self.assertLen(loaded_model.predict({'a': inputs_a, 'b': inputs_b}), 10) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_saving_with_sequence_features(self): cols = [ tf.feature_column.sequence_numeric_column('a'), tf.feature_column.indicator_column( tf.feature_column.sequence_categorical_column_with_vocabulary_list( 'b', ['one', 'two'])) ] input_layers = { 'a': keras.layers.Input(shape=(None, 1), sparse=True, name='a'), 'b': keras.layers.Input( shape=(None, 1), sparse=True, name='b', dtype='string') } fc_layer, _ = ksfc.SequenceFeatures(cols)(input_layers) # TODO(tibell): Figure out the right dtype and apply masking. # sequence_length_mask = array_ops.sequence_mask(sequence_length) # x = keras.layers.GRU(32)(fc_layer, mask=sequence_length_mask) x = keras.layers.GRU(32)(fc_layer) output = keras.layers.Dense(10)(x) model = keras.models.Model(input_layers, output) model.compile( loss=keras.losses.MSE, optimizer='rmsprop', metrics=[keras.metrics.categorical_accuracy]) config = model.to_json() loaded_model = model_config.model_from_json(config) batch_size = 10 timesteps = 1 values_a = np.arange(10, dtype=np.float32) indices_a = np.zeros((10, 3), dtype=np.int64) indices_a[:, 0] = np.arange(10) inputs_a = tf.SparseTensor(indices_a, values_a, (batch_size, timesteps, 1)) values_b = np.zeros(10, dtype=np.str) indices_b = np.zeros((10, 3), dtype=np.int64) indices_b[:, 0] = np.arange(10) inputs_b = tf.SparseTensor(indices_b, values_b, (batch_size, timesteps, 1)) with self.cached_session(): # Initialize tables for V1 lookup. if not tf.executing_eagerly(): self.evaluate(tf.compat.v1.tables_initializer()) self.assertLen( loaded_model.predict({ 'a': inputs_a, 'b': inputs_b }, steps=1), batch_size) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_saving_h5_for_rnn_layers(self): # See https://github.com/tensorflow/tensorflow/issues/35731 for details. inputs = keras.Input([10, 91], name='train_input') rnn_layers = [ keras.layers.LSTMCell(size, recurrent_dropout=0, name='rnn_cell%d' % i) for i, size in enumerate([512, 512]) ] rnn_output = keras.layers.RNN( rnn_layers, return_sequences=True, name='rnn_layer')(inputs) pred_feat = keras.layers.Dense(91, name='prediction_features')(rnn_output) pred = keras.layers.Softmax()(pred_feat) model = keras.Model(inputs=[inputs], outputs=[pred, pred_feat]) path = os.path.join(self.get_temp_dir(), 'model_path.h5') model.save(path) # Make sure the variable name is unique. self.assertNotEqual(rnn_layers[0].kernel.name, rnn_layers[1].kernel.name) self.assertIn('rnn_cell1', rnn_layers[1].kernel.name) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_saving_optimizer_weights(self): class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.layer = keras.layers.Dense(1) def call(self, x): return self.layer(x) path = os.path.join(self.get_temp_dir(), 'weights_path') x, y = np.ones((10, 10)), np.ones((10, 1)) model = MyModel() model.compile('rmsprop', loss='bce') model.train_on_batch(x, y) model.reset_metrics() model.save_weights(path, save_format='tf') batch_loss = model.train_on_batch(x, y) new_model = MyModel() new_model.compile('rmsprop', loss='bce') new_model.train_on_batch(x, y) new_model.reset_metrics() new_model.load_weights(path) new_batch_loss = new_model.train_on_batch(x, y) self.assertAllClose(batch_loss, new_batch_loss) @combinations.generate(combinations.combine(mode=['eager', 'graph'])) def test_save_include_optimizer_false(self): def get_variables(file_name): reader = tf.train.load_checkpoint( os.path.join(file_name, 'variables/variables')) shape_from_key = reader.get_variable_to_shape_map() return sorted(shape_from_key.keys()) path = os.path.join(self.get_temp_dir(), 'no_optimizer') x, y = np.ones((10, 10)), np.ones((10, 1)) model = keras.models.Sequential() model.add(keras.layers.Dense(1)) model.compile('adam', loss='mse') model.train_on_batch(x, y) model.save(path, save_format='tf', include_optimizer=False) variables = get_variables(path) for v in variables: self.assertNotIn('optimizer', v) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_saving_model_with_custom_object(self): with generic_utils.custom_object_scope(), self.cached_session(): @generic_utils.register_keras_serializable() class CustomLoss(losses.MeanSquaredError): pass model = sequential.Sequential( [core.Dense(units=1, input_shape=(1,))]) model.compile(optimizer='sgd', loss=CustomLoss()) model.fit(np.zeros([10, 1]), np.zeros([10, 1])) temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, 'saving') model.save(filepath) # Make sure the model can be correctly load back. _ = save.load_model(filepath, compile=True) @keras_parameterized.run_with_all_saved_model_formats class TestWholeModelSaving(keras_parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def _assert_same_weights_and_metrics(self, model, loaded_model): """Checks that the loaded weights and metrics are the same as the original. Args: model: original model loaded_model: loaded model """ self.assertAllClose(model.weights, loaded_model.weights) if loaded_model.optimizer: if testing_utils.get_save_format() == 'tf': # TODO(b/153110928): Keras TF format doesn't restore optimizer weights # currently. return self.assertAllClose(model.optimizer.weights, loaded_model.optimizer.weights) # In V1/Graph mode, the model isn't built, so the metrics are not loaded # immediately (requires model to be called on some data before building # metrics). check_metrics = tf.__internal__.tf2.enabled() and tf.executing_eagerly() if check_metrics: self.assertAllEqual([m.name for m in model.metrics], [m.name for m in loaded_model.metrics]) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes def test_save_and_load(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() save_kwargs = testing_utils.get_save_kwargs() if ((save_format == 'h5' or not save_kwargs.get('save_traces', True)) and testing_utils.get_model_type() == 'subclass'): # HDF5 format currently does not allow saving subclassed models. # When saving with `save_traces=False`, the subclassed model must have a # get_config/from_config, which the autogenerated model does not have. return with self.cached_session(): model = testing_utils.get_model_from_layers( [keras.layers.Dense(2), keras.layers.RepeatVector(3), keras.layers.TimeDistributed(keras.layers.Dense(3))], input_shape=(3,)) model.compile( loss=keras.losses.MSE, optimizer=keras.optimizer_v2.rmsprop.RMSprop(lr=0.0001), metrics=[ keras.metrics.categorical_accuracy, keras.metrics.CategoricalCrossentropy( name='cce', label_smoothing=tf.constant(0.2)), ], weighted_metrics=[ keras.metrics.categorical_crossentropy, keras.metrics.CategoricalCrossentropy( name='cce', label_smoothing=tf.constant(0.2)), ], sample_weight_mode='temporal') x = np.random.random((1, 3)) y = np.random.random((1, 3, 3)) model.train_on_batch(x, y) out = model.predict(x) keras.models.save_model( model, saved_model_dir, save_format=save_format, **save_kwargs) loaded_model = keras.models.load_model(saved_model_dir) self._assert_same_weights_and_metrics(model, loaded_model) out2 = loaded_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) eval_out = model.evaluate(x, y) eval_out2 = loaded_model.evaluate(x, y) self.assertArrayNear(eval_out, eval_out2, 0.001) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_sequential_model_saving_without_input_shape(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2)) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) model.compile( loss=keras.losses.MSE, optimizer='rmsprop', metrics=[ keras.metrics.categorical_accuracy, keras.metrics.CategoricalAccuracy(name='cat_acc') ], weighted_metrics=[ keras.metrics.categorical_accuracy, keras.metrics.CategoricalAccuracy(name='cat_acc2') ], sample_weight_mode='temporal') x = np.random.random((1, 3)) y = np.random.random((1, 3, 3)) model.train_on_batch(x, y) out = model.predict(x) model.save(saved_model_dir, save_format=save_format) new_model = keras.models.load_model(saved_model_dir) self._assert_same_weights_and_metrics(model, new_model) out2 = new_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_sequential_model_saving_without_compile(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) x = np.random.random((1, 3)) out = model.predict(x) # Save the model without any compilation or training. keras.models.save_model(model, saved_model_dir, save_format=save_format) new_model = keras.models.load_model(saved_model_dir) self._assert_same_weights_and_metrics(model, new_model) out2 = new_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) def test_sequential_model_saving_2(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with tf.Graph().as_default(), self.cached_session(): # test with custom optimizer, loss class CustomOp(optimizer_v1.RMSprop): pass def custom_loss(y_true, y_pred): return keras.losses.mse(y_true, y_pred) model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) model.compile(loss=custom_loss, optimizer=CustomOp(), metrics=['acc']) x = np.random.random((1, 3)) y = np.random.random((1, 3)) model.train_on_batch(x, y) out = model.predict(x) keras.models.save_model(model, saved_model_dir, save_format=save_format) new_model = keras.models.load_model( saved_model_dir, custom_objects={'CustomOp': CustomOp, 'custom_loss': custom_loss}) self._assert_same_weights_and_metrics(model, new_model) out2 = new_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) def test_saving_without_compilation(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) model.compile(loss='mse', optimizer='sgd', metrics=['acc']) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) def test_saving_with_tf_optimizer(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) model.compile(loss='mse', optimizer=tf.compat.v1.train.AdadeltaOptimizer(0.1), metrics=['acc']) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) def test_saving_right_after_compilation(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.Dense(3)) model.compile(loss='mse', optimizer='sgd', metrics=['acc']) if not tf.compat.v1.executing_eagerly_outside_functions(): model._make_train_function() keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) def test_saving_lambda_numpy_array_arguments(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() if h5py is None: self.skipTest('h5py required to run this test') mean = np.random.random((4, 2, 3)) std = np.abs(np.random.random((4, 2, 3))) + 1e-5 inputs = keras.layers.Input(shape=(4, 2, 3)) output = keras.layers.Lambda(lambda image, mu, std: (image - mu) / std, arguments={'mu': mean, 'std': std})(inputs) model = keras.models.Model(inputs, output) model.compile(loss='mse', optimizer='sgd', metrics=['acc']) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) self.assertAllClose(mean, model.layers[1].arguments['mu']) self.assertAllClose(std, model.layers[1].arguments['std']) def test_saving_model_with_long_layer_names(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): # This layer name will make the `layers_name` HDF5 attribute blow # out of proportion. Note that it fits into the internal HDF5 # attribute memory limit on its own but because h5py converts # the list of layer names into numpy array, which uses the same # amount of memory for every item, it increases the memory # requirements substantially. x = keras.Input(shape=(2,), name='input_' + ('x' * (2**15))) f = x for i in range(4): f = keras.layers.Dense(2, name='dense_%d' % (i,))(f) model = keras.Model(inputs=[x], outputs=[f]) model.compile( 'adam', loss=keras.losses.MeanSquaredError(), metrics=['acc']) x = np.random.random((1, 2)) y = np.random.random((1, 2)) model.train_on_batch(x, y) out = model.predict(x) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) if save_format in ['tf', 'tensorflow']: return # Check that the HDF5 files contains chunked array # of layer names. with h5py.File(saved_model_dir, 'r') as h5file: num_names_arrays = len([attr for attr in h5file['model_weights'].attrs if attr.startswith('layer_names')]) # The chunking of layer names array should have happened. self.assertGreater(num_names_arrays, 0) out2 = model.predict(x) self.assertAllClose(out, out2, atol=1e-05) def test_saving_model_with_long_weights_names(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): x = keras.Input(shape=(2,), name='nested_model_input') f = x for i in range(4): f = keras.layers.Dense(2, name='nested_model_dense_%d' % (i,))(f) # This layer name will make the `weights_name` # HDF5 attribute blow out of proportion. f = keras.layers.Dense(2, name='nested_model_output' + ('x' * (2**14)))(f) nested_model = keras.Model(inputs=[x], outputs=[f], name='nested_model') x = keras.Input(shape=(2,), name='outer_model_input') f = nested_model(x) f = keras.layers.Dense(2, name='outer_model_output')(f) model = keras.Model(inputs=[x], outputs=[f]) model.compile(loss='mse', optimizer='adam', metrics=['acc']) x = np.random.random((1, 2)) y = np.random.random((1, 2)) model.train_on_batch(x, y) out = model.predict(x) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) if save_format in ['h5', 'hdf5', 'keras']: # Check that the HDF5 files contains chunked array # of weight names. with h5py.File(saved_model_dir, 'r') as h5file: num_weight_arrays = len( [attr for attr in h5file['model_weights']['nested_model'].attrs if attr.startswith('weight_names')]) # The chunking of layer names array should have happened. self.assertGreater(num_weight_arrays, 0) out2 = model.predict(x) self.assertAllClose(out, out2, atol=1e-05) def test_model_saving_to_pre_created_h5py_file(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with tf.Graph().as_default(), self.cached_session(): inputs = keras.Input(shape=(3,)) x = keras.layers.Dense(2)(inputs) outputs = keras.layers.Dense(3)(x) model = keras.Model(inputs, outputs) model.compile( loss=keras.losses.MSE, optimizer=optimizer_v1.Adam(), metrics=[ keras.metrics.categorical_accuracy, keras.metrics.CategoricalAccuracy() ]) x = np.random.random((1, 3)) y = np.random.random((1, 3)) model.train_on_batch(x, y) out = model.predict(x) keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded_model = keras.models.load_model(saved_model_dir) out1 = loaded_model.predict(x) self.assertAllClose(out, out1, atol=1e-05) if save_format in ['tf', 'tensorflow']: return # Test h5 format specifically fd, fname = tempfile.mkstemp('.h5') with h5py.File(fname, mode='r+') as h5file: keras.models.save_model(model, h5file) loaded_model = keras.models.load_model(h5file) out2 = loaded_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) # Test non-default options in h5 with h5py.File( '_', driver='core', mode='w', backing_store=False) as h5file: keras.models.save_model(model, h5file) loaded_model = keras.models.load_model(h5file) out2 = loaded_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) # Cleanup os.close(fd) os.remove(fname) def test_model_saving_to_new_dir_path(self): saved_model_dir = os.path.join(self._save_model_dir(), 'newdir', 'saved_model') save_format = testing_utils.get_save_format() with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) x = np.random.random((1, 3)) out = model.predict(x) keras.models.save_model(model, saved_model_dir, save_format=save_format) new_model = keras.models.load_model(saved_model_dir) self._assert_same_weights_and_metrics(model, new_model) out2 = new_model.predict(x) self.assertAllClose(out, out2, atol=1e-05) def test_model_raise_exception_with_failed_saving(self): if h5py is None: self.skipTest('h5py required to run this test') saved_model_dir = self._save_model_dir() saved_model_path = os.path.join(saved_model_dir, 'saved_model.h5') with self.cached_session(): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) with self.assertRaisesRegex(OSError, 'Unable to create file'): with h5py.File(saved_model_path, 'w'): keras.models.save_model(model, saved_model_path) def test_saving_constant_initializer_with_numpy(self): saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() model = keras.models.Sequential() model.add( keras.layers.Dense( 2, input_shape=(3,), kernel_initializer=keras.initializers.Constant(np.ones((3, 2))))) model.add(keras.layers.Dense(3)) model.compile(loss='mse', optimizer='sgd', metrics=['acc']) keras.models.save_model(model, saved_model_dir, save_format=save_format) model = keras.models.load_model(saved_model_dir) def test_saving_group_naming_h5py(self): # Test saving model with layer which name is prefix to a previous layer # name. temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir) h5_path = os.path.join(temp_dir, 'test.h5') input_layer = keras.layers.Input((None, None, 3), name='test_input') x = keras.layers.Conv2D(1, 1, name='conv1/conv')(input_layer) x = keras.layers.Activation('relu', name='conv1')(x) model = keras.models.Model(inputs=input_layer, outputs=x) model.save_weights(h5_path) model.load_weights(h5_path) def test_primitive_attrs_contain_no_extraneous_strings(self): if h5py is None: self.skipTest('h5py required to run this test') saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() model = keras.models.Sequential() model.add(keras.layers.Dense(1, input_shape=[2])) model.save(saved_model_dir, save_format=save_format) if save_format in ['tf', 'tensorflow']: return h5file = h5py.File(saved_model_dir, 'r') self.assertRegex(h5file.attrs['keras_version'], r'^[\d]+\.[\d]+\.[\S]+$') @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_functional_model_with_custom_loss_and_metric(self): def _make_model(): inputs = keras.Input(shape=(4,)) x = keras.layers.Dense(8, activation='relu')(inputs) outputs = keras.layers.Dense(3, activation='softmax')(x) model = keras.Model(inputs=inputs, outputs=outputs) custom_loss = keras.layers.Lambda(lambda x: keras.backend.sum(x * x))(x) model.add_loss(custom_loss) model.add_metric(custom_loss, aggregation='mean', name='custom_loss') return model saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() with self.cached_session(): model = _make_model() model.compile( loss=keras.losses.SparseCategoricalCrossentropy(), optimizer=optimizers.gradient_descent_v2.SGD(), metrics=[keras.metrics.SparseCategoricalCrossentropy()]) x = np.random.normal(size=(32, 4)) y = np.random.randint(0, 3, size=32) model.train_on_batch(x, y) evaluation_results = model.evaluate(x, y) # Save and reload model. model.save(saved_model_dir, save_format=save_format) del model # Prevent misuse. loaded_model = keras.models.load_model(saved_model_dir) loaded_model_eval_results = loaded_model.evaluate(x, y) # Assert all evaluation results are the same. self.assertAllClose(evaluation_results, loaded_model_eval_results, 1e-9) # Check correctness of the loss calculation. self.assertAllGreater(evaluation_results, 0.) evaluation_results = dict( zip(loaded_model.metrics_names, evaluation_results)) self.assertNear( evaluation_results['sparse_categorical_crossentropy'] + evaluation_results['custom_loss'], evaluation_results['loss'], 1e-6) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_save_uncompiled_model_with_optimizer(self): with self.cached_session() as session: saved_model_dir = self._save_model_dir() save_format = testing_utils.get_save_format() model = keras.models.Sequential([keras.layers.Dense(1, input_shape=(3,))]) # Set the model's optimizer but don't compile. This can happen if the # model is trained with a custom training loop. model.optimizer = keras.optimizer_v2.rmsprop.RMSprop(lr=0.0001) if not tf.executing_eagerly(): session.run([v.initializer for v in model.variables]) model.save(saved_model_dir, save_format=save_format) if save_format in ['tf', 'tensorflow']: loaded = keras.models.load_model(saved_model_dir) self.assertIsInstance(loaded.optimizer, keras.optimizer_v2.optimizer_v2.OptimizerV2) @combinations.generate(combinations.combine(mode=['eager'])) def test_functional_model_with_getitem_op_layer(self): inp = keras.Input(shape=(8)) out = inp[:] model = keras.Model( inputs=[inp], outputs=out) batch_size = 7 x = tf.stack([ tf.range(8) for _ in range(batch_size)]) args = [x] expected = x[:] self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded. save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded_model = keras.models.load_model(saved_model_dir) self.assertAllEqual(loaded_model(args), expected) self.assertAllEqual(loaded_model.predict(args, batch_size=batch_size), expected) @combinations.generate(combinations.combine(mode=['eager', 'graph'])) def test_custom_functional_registered(self): def _get_cls_definition(): class CustomModel(keras.Model): def c(self): return 'c' return CustomModel cls = _get_cls_definition() self.assertEqual(cls.__bases__[0], keras.Model) with self.cached_session() as sess: input_ = keras.layers.Input(shape=(1,)) output = keras.layers.Dense(1)(input_) model = cls(input_, output) # `cls` now inherits from `Functional` class. self.assertEqual(cls.__bases__[0], functional.Functional) if not tf.executing_eagerly(): sess.run([v.initializer for v in model.variables]) save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded_model = keras.models.load_model( saved_model_dir, custom_objects={'CustomModel': cls}) self.assertIsInstance(loaded_model, cls) # Check with "new" `CustomModel` class definition. new_cls = _get_cls_definition() # The new `CustomModel` class is *not* derived from `Functional`. self.assertEqual(new_cls.__bases__[0], keras.Model) reloaded_model = keras.models.load_model( saved_model_dir, custom_objects={'CustomModel': new_cls}) self.assertIsInstance(reloaded_model, new_cls) @combinations.generate(combinations.combine(mode=['eager'])) def test_shared_objects(self): class OuterLayer(keras.layers.Layer): def __init__(self, inner_layer): super(OuterLayer, self).__init__() self.inner_layer = inner_layer def call(self, inputs): return self.inner_layer(inputs) def get_config(self): return { 'inner_layer': generic_utils.serialize_keras_object( self.inner_layer) } @classmethod def from_config(cls, config): return cls(generic_utils.deserialize_keras_object( config['inner_layer'])) class InnerLayer(keras.layers.Layer): def __init__(self): super(InnerLayer, self).__init__() self.v = self.add_weight(name='v', shape=[], dtype=tf.float32) def call(self, inputs): return self.v + inputs @classmethod def from_config(cls, config): return cls() # Create a model with 2 output layers that share the same inner layer. inner_layer = InnerLayer() outer_layer_1 = OuterLayer(inner_layer) outer_layer_2 = OuterLayer(inner_layer) input_ = keras.Input(shape=(1,)) model = keras.Model( inputs=input_, outputs=[outer_layer_1(input_), outer_layer_2(input_)]) # Changes to the shared layer should affect both outputs. model.layers[1].inner_layer.v.assign(5) self.assertAllEqual(model(1), [6.0, 6.0]) model.layers[1].inner_layer.v.assign(3) self.assertAllEqual(model(1), [4.0, 4.0]) # After loading, changes to the shared layer should still affect both # outputs. def _do_assertions(loaded): loaded.layers[1].inner_layer.v.assign(5) self.assertAllEqual(loaded(1), [6.0, 6.0]) loaded.layers[1].inner_layer.v.assign(3) self.assertAllEqual(loaded(1), [4.0, 4.0]) loaded.layers[2].inner_layer.v.assign(5) self.assertAllEqual(loaded(1), [6.0, 6.0]) loaded.layers[2].inner_layer.v.assign(3) self.assertAllEqual(loaded(1), [4.0, 4.0]) # We'd like to make sure we only attach shared object IDs when strictly # necessary, so we'll recursively traverse the generated config to count # whether we have the exact number we expect. def _get_all_keys_recursive(dict_or_iterable): if isinstance(dict_or_iterable, dict): for key in dict_or_iterable.keys(): yield key for key in _get_all_keys_recursive(dict_or_iterable.values()): yield key elif isinstance(dict_or_iterable, str): return else: try: for item in dict_or_iterable: for key in _get_all_keys_recursive(item): yield key # Not an iterable or dictionary except TypeError: return with generic_utils.CustomObjectScope({ 'OuterLayer': OuterLayer, 'InnerLayer': InnerLayer}): # Test saving and loading to disk save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded = keras.models.load_model(saved_model_dir) _do_assertions(loaded) # Test recreating directly from config config = model.get_config() key_count = collections.Counter(_get_all_keys_recursive(config)) self.assertEqual(key_count[generic_utils.SHARED_OBJECT_KEY], 2) loaded = keras.Model.from_config(config) _do_assertions(loaded) @combinations.generate(combinations.combine(mode=['eager'])) def test_shared_objects_wrapper(self): """Tests that shared layers wrapped with `Wrapper` restore correctly.""" input_ = keras.Input(shape=(1,)) unwrapped = keras.layers.Layer(name='unwrapped') wrapped = keras.layers.Wrapper(unwrapped, name='wrapped') model = keras.Model(inputs=input_, outputs=[unwrapped(input_), wrapped(input_)]) # Test recreating directly from config config = model.get_config() loaded = keras.Model.from_config(config) self.assertIs(loaded.layers[1], loaded.layers[2].layer) # Test saving and loading to disk save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded = keras.models.load_model(saved_model_dir) self.assertIs(loaded.layers[1], loaded.layers[2].layer) @combinations.generate( combinations.combine(mode=['graph', 'eager'], fit=[True, False])) def test_multi_output_metrics_name_stay_same(self, fit): """Tests that metric names don't change with each save/load cycle. e.g. "head_0_accuracy" should not become "head_0_head_0_accuracy" after saving and loading a model. Arguments: fit: Whether the model should be fit before saving. """ # This doesn't work at all, so we can't check whether metric names are # correct. if not tf.executing_eagerly() and not fit: self.skipTest('b/181767784') input_ = keras.Input((4,)) model = keras.Model( input_, [keras.layers.Softmax(name='head_0')(keras.layers.Dense(3)(input_)), keras.layers.Softmax(name='head_1')(keras.layers.Dense(5)(input_))]) metric = keras.metrics.BinaryAccuracy() model.compile(optimizer='rmsprop', loss='mse', metrics={'head_0': [metric, 'accuracy']}) x = np.random.rand(2, 4) y = {'head_0': np.random.randint(2, size=(2, 3)), 'head_1': np.random.randint(2, size=(2, 5))} # Make sure metrix prefixing works the same regardless of whether the user # has fit the model before saving. if fit: model.fit(x, y, verbose=0) # Save and reload. save_format = testing_utils.get_save_format() saved_model_dir = self._save_model_dir() keras.models.save_model(model, saved_model_dir, save_format=save_format) loaded = keras.models.load_model(saved_model_dir) # Make sure the metrics names from the model before saving match the loaded # model. self.assertSequenceEqual(model.metrics_names, loaded.metrics_names) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_warning_when_saving_invalid_custom_mask_layer(self): class MyMasking(keras.layers.Layer): def call(self, inputs): return inputs def compute_mask(self, inputs, mask=None): mask = tf.not_equal(inputs, 0) return mask class MyLayer(keras.layers.Layer): def call(self, inputs, mask=None): return tf.identity(inputs) samples = np.random.random((2, 2)) model = keras.Sequential([MyMasking(), MyLayer()]) model.predict(samples) with warnings.catch_warnings(record=True) as w: model.save(self._save_model_dir(), testing_utils.get_save_format()) self.assertIn(generic_utils.CustomMaskWarning, {warning.category for warning in w}) # Test that setting up a custom mask correctly does not issue a warning. class MyCorrectMasking(keras.layers.Layer): def call(self, inputs): return inputs def compute_mask(self, inputs, mask=None): mask = tf.not_equal(inputs, 0) return mask # This get_config doesn't actually do anything because our mask is # static and doesn't need any external information to work. We do need a # dummy get_config method to prevent the warning from appearing, however. def get_config(self, *args, **kwargs): return {} model = keras.Sequential([MyCorrectMasking(), MyLayer()]) model.predict(samples) with warnings.catch_warnings(record=True) as w: model.save(self._save_model_dir(), testing_utils.get_save_format()) self.assertNotIn(generic_utils.CustomMaskWarning, {warning.category for warning in w}) # Factory functions to create models that will be serialized inside a Network. def _make_graph_network(input_size, output_size): inputs = keras.Input(input_size) x = keras.layers.Dense(8, activation='relu')(inputs) y = keras.layers.Dense(output_size)(x) return keras.Model(inputs=inputs, outputs=y) def _make_sequential(input_size, output_size): del input_size return keras.Sequential([ keras.layers.Dense(8, activation='relu'), keras.layers.Dense(output_size), ]) def _make_sequential_built(input_size, output_size): model = _make_sequential(input_size, output_size) model.build((None, input_size)) return model def _make_sequential_graph_network(input_size, output_size): return keras.Sequential([ keras.layers.InputLayer(input_size), keras.layers.Dense(8, activation='relu'), keras.layers.Dense(output_size), ]) def _make_sequential_input_shape(input_size, output_size): return keras.Sequential([ keras.layers.Dense(8, activation='relu', input_shape=(input_size,)), keras.layers.Dense(output_size), ]) class _make_subclassed(keras.Model): # pylint: disable=invalid-name def __init__(self, input_size, output_size): super(_make_subclassed, self).__init__() self._config = {'input_size': input_size, 'output_size': output_size} self._hidden_layer = keras.layers.Dense(8, activation='relu', name='hidden') self._logits_layer = keras.layers.Dense(output_size, name='logits') def call(self, inputs): x = self._hidden_layer(inputs) return self._logits_layer(x) def get_config(self): return self._config @classmethod def from_config(cls, config): return cls(**config) class _make_subclassed_built(_make_subclassed): # pylint: disable=invalid-name def __init__(self, input_size, output_size): super(_make_subclassed_built, self).__init__(input_size, output_size) self.build((None, input_size)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class TestWholeModelSavingWithNesting(tf.test.TestCase, parameterized.TestCase): """Tests saving a whole model that contains other models.""" @parameterized.named_parameters([ ('graph_network', _make_graph_network), ('sequential', _make_sequential), ('sequential_built', _make_sequential_built), ('sequential_graph_network', _make_sequential_graph_network), ('sequential_input_shape', _make_sequential_input_shape), ('subclassed', _make_subclassed), ('subclassed_built', _make_subclassed_built), ]) def test_functional(self, model_fn): """Tests serializing a model that uses a nested model to share weights.""" if h5py is None: self.skipTest('h5py required to run this test') def _make_model(): inputs = (keras.Input(shape=(4,), name='examples'), keras.Input(shape=(4,), name='neighbors')) base_model = model_fn(inputs[0].shape.as_list()[-1], 2) outputs = keras.layers.add([base_model(inputs[0]), base_model(inputs[1])]) return keras.Model(inputs=inputs, outputs=outputs) with self.cached_session(): x = (np.random.normal(size=(16, 4)).astype(np.float32), np.random.normal(size=(16, 4)).astype(np.float32)) model = _make_model() predictions = model(x) # Save and reload. model_path = os.path.join(self.get_temp_dir(), 'model.h5') model.save(model_path) del model loaded_model = keras.models.load_model( model_path, custom_objects={ '_make_subclassed': _make_subclassed, '_make_subclassed_built': _make_subclassed_built, }, compile=False) self.assertAllClose(loaded_model(x), predictions, 1e-9) if __name__ == '__main__': tf.test.main()
45,530
36.198529
80
py
keras
keras-master/keras/saving/hdf5_format.py
# 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. # ============================================================================== # pylint: disable=protected-access """Functions for saving and loading a Keras Model from HDF5 format.""" import tensorflow.compat.v2 as tf import json import os import numpy as np from keras import backend from keras import optimizer_v1 from keras.saving import model_config as model_config_lib from keras.saving import saving_utils from keras.saving.saved_model import json_utils from keras.utils.generic_utils import LazyLoader from keras.utils.io_utils import ask_to_proceed_with_overwrite from tensorflow.python.platform import tf_logging as logging # pylint: disable=g-import-not-at-top try: import h5py HDF5_OBJECT_HEADER_LIMIT = 64512 except ImportError: h5py = None # pylint: enable=g-import-not-at-top # TODO(b/134426265): Switch back to single-quotes to match the rest of the file # once the issue with copybara is fixed. # pylint:disable=g-inconsistent-quotes sequential_lib = LazyLoader( "sequential_lib", globals(), "keras.engine.sequential") # pylint:enable=g-inconsistent-quotes def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): """Saves a model to a HDF5 file. The saved model contains: - the model's configuration (topology) - the model's weights - the model's optimizer's state (if any) Thus the saved model can be reinstantiated in the exact same state, without any of the code used for model definition or training. Args: model: Keras model instance to be saved. filepath: One of the following: - String, path where to save the model - `h5py.File` object where to save the model overwrite: Whether we should overwrite any existing model at the target location, or instead ask the user with a manual prompt. include_optimizer: If True, save optimizer's state together. Raises: ImportError: if h5py is not available. """ if h5py is None: raise ImportError('`save_model()` using h5 format requires h5py. Could not ' 'import h5py.') # TODO(psv) Add warning when we save models that contain non-serializable # entities like metrics added using `add_metric` and losses added using # `add_loss.` if len(model.weights) != len(model._undeduplicated_weights): logging.warning('Found duplicated `Variable`s in Model\'s `weights`. ' 'This is usually caused by `Variable`s being shared by ' 'Layers in the Model. These `Variable`s will be treated ' 'as separate `Variable`s when the Model is restored. To ' 'avoid this, please save with `save_format="tf"`.') if not isinstance(filepath, h5py.File): # If file exists and should not be overwritten. if not overwrite and os.path.isfile(filepath): proceed = ask_to_proceed_with_overwrite(filepath) if not proceed: return # Try creating dir if not exist dirpath = os.path.dirname(filepath) if not os.path.exists(dirpath): tf.io.gfile.makedirs(dirpath) f = h5py.File(filepath, mode='w') opened_new_file = True else: f = filepath opened_new_file = False try: model_metadata = saving_utils.model_metadata(model, include_optimizer) for k, v in model_metadata.items(): if isinstance(v, (dict, list, tuple)): f.attrs[k] = json.dumps( v, default=json_utils.get_json_type).encode('utf8') else: f.attrs[k] = v model_weights_group = f.create_group('model_weights') save_weights_to_hdf5_group(model_weights_group, model) # TODO(b/128683857): Add integration tests between tf.keras and external # Keras, to avoid breaking TF.js users. if (include_optimizer and model.optimizer and not isinstance(model.optimizer, optimizer_v1.TFOptimizer)): save_optimizer_weights_to_hdf5_group(f, model.optimizer) f.flush() finally: if opened_new_file: f.close() def load_model_from_hdf5(filepath, custom_objects=None, compile=True): # pylint: disable=redefined-builtin """Loads a model saved via `save_model_to_hdf5`. Args: filepath: One of the following: - String, path to the saved model - `h5py.File` object from which to load the model custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. compile: Boolean, whether to compile the model after loading. Returns: A Keras model instance. If an optimizer was found as part of the saved model, the model is already compiled. Otherwise, the model is uncompiled and a warning will be displayed. When `compile` is set to False, the compilation is omitted without any warning. Raises: ImportError: if h5py is not available. ValueError: In case of an invalid savefile. """ if h5py is None: raise ImportError('`load_model()` using h5 format requires h5py. Could not ' 'import h5py.') if not custom_objects: custom_objects = {} opened_new_file = not isinstance(filepath, h5py.File) if opened_new_file: f = h5py.File(filepath, mode='r') else: f = filepath model = None try: # instantiate model model_config = f.attrs.get('model_config') if model_config is None: raise ValueError(f'No model config found in the file at {filepath}.') if hasattr(model_config, 'decode'): model_config = model_config.decode('utf-8') model_config = json_utils.decode(model_config) model = model_config_lib.model_from_config(model_config, custom_objects=custom_objects) # set weights load_weights_from_hdf5_group(f['model_weights'], model) if compile: # instantiate optimizer training_config = f.attrs.get('training_config') if hasattr(training_config, 'decode'): training_config = training_config.decode('utf-8') if training_config is None: logging.warning('No training configuration found in the save file, so ' 'the model was *not* compiled. Compile it manually.') return model training_config = json_utils.decode(training_config) # Compile model. model.compile(**saving_utils.compile_args_from_training_config( training_config, custom_objects), from_serialized=True) saving_utils.try_build_compiled_arguments(model) # Set optimizer weights. if 'optimizer_weights' in f: try: model.optimizer._create_all_weights(model.trainable_variables) except (NotImplementedError, AttributeError): logging.warning( 'Error when creating the weights of optimizer {}, making it ' 'impossible to restore the saved optimizer state. As a result, ' 'your model is starting with a freshly initialized optimizer.') optimizer_weight_values = load_optimizer_weights_from_hdf5_group(f) try: model.optimizer.set_weights(optimizer_weight_values) except ValueError: logging.warning('Error in loading the saved optimizer ' 'state. As a result, your model is ' 'starting with a freshly initialized ' 'optimizer.') finally: if opened_new_file: f.close() return model def preprocess_weights_for_loading(layer, weights, original_keras_version=None, original_backend=None): """Preprocess layer weights between different Keras formats. Converts layers weights from Keras 1 format to Keras 2 and also weights of cuDNN layers in Keras 2. Args: layer: Layer instance. weights: List of weights values (Numpy arrays). original_keras_version: Keras version for the weights, as a string. original_backend: Keras backend the weights were trained with, as a string. Returns: A list of weights values (Numpy arrays). """ def convert_nested_bidirectional(weights): """Converts layers nested in `Bidirectional` wrapper. This function uses `preprocess_weights_for_loading()` for converting layers. Args: weights: List of weights values (Numpy arrays). Returns: A list of weights values (Numpy arrays). """ num_weights_per_layer = len(weights) // 2 forward_weights = preprocess_weights_for_loading( layer.forward_layer, weights[:num_weights_per_layer], original_keras_version, original_backend) backward_weights = preprocess_weights_for_loading( layer.backward_layer, weights[num_weights_per_layer:], original_keras_version, original_backend) return forward_weights + backward_weights def convert_nested_time_distributed(weights): """Converts layers nested in `TimeDistributed` wrapper. This function uses `preprocess_weights_for_loading()` for converting nested layers. Args: weights: List of weights values (Numpy arrays). Returns: A list of weights values (Numpy arrays). """ return preprocess_weights_for_loading( layer.layer, weights, original_keras_version, original_backend) def convert_nested_model(weights): """Converts layers nested in `Model` or `Sequential`. This function uses `preprocess_weights_for_loading()` for converting nested layers. Args: weights: List of weights values (Numpy arrays). Returns: A list of weights values (Numpy arrays). """ trainable_weights = weights[:len(layer.trainable_weights)] non_trainable_weights = weights[len(layer.trainable_weights):] new_trainable_weights = [] new_non_trainable_weights = [] for sublayer in layer.layers: num_trainable_weights = len(sublayer.trainable_weights) num_non_trainable_weights = len(sublayer.non_trainable_weights) if sublayer.weights: preprocessed = preprocess_weights_for_loading( layer=sublayer, weights=(trainable_weights[:num_trainable_weights] + non_trainable_weights[:num_non_trainable_weights]), original_keras_version=original_keras_version, original_backend=original_backend) new_trainable_weights.extend(preprocessed[:num_trainable_weights]) new_non_trainable_weights.extend(preprocessed[num_trainable_weights:]) trainable_weights = trainable_weights[num_trainable_weights:] non_trainable_weights = non_trainable_weights[ num_non_trainable_weights:] new_trainable_weights += layer._trainable_weights new_non_trainable_weights += layer._non_trainable_weights return new_trainable_weights + new_non_trainable_weights # Convert layers nested in Bidirectional/Model/Sequential. # Both transformation should be ran for both Keras 1->2 conversion # and for conversion of cuDNN layers. if layer.__class__.__name__ == 'Bidirectional': weights = convert_nested_bidirectional(weights) if layer.__class__.__name__ == 'TimeDistributed': weights = convert_nested_time_distributed(weights) elif layer.__class__.__name__ in ['Model', 'Sequential', 'Functional']: weights = convert_nested_model(weights) if original_keras_version == '1': if layer.__class__.__name__ == 'TimeDistributed': weights = preprocess_weights_for_loading( layer.layer, weights, original_keras_version, original_backend) if layer.__class__.__name__ == 'Conv1D': shape = weights[0].shape # Handle Keras 1.1 format if shape[:2] != (layer.kernel_size[0], 1) or shape[3] != layer.filters: # Legacy shape: # (filters, input_dim, filter_length, 1) assert shape[0] == layer.filters and shape[2:] == (layer.kernel_size[0], 1) weights[0] = np.transpose(weights[0], (2, 3, 1, 0)) weights[0] = weights[0][:, 0, :, :] if layer.__class__.__name__ == 'Conv2D': if layer.data_format == 'channels_first': # old: (filters, stack_size, kernel_rows, kernel_cols) # new: (kernel_rows, kernel_cols, stack_size, filters) weights[0] = np.transpose(weights[0], (2, 3, 1, 0)) if layer.__class__.__name__ == 'Conv2DTranspose': if layer.data_format == 'channels_last': # old: (kernel_rows, kernel_cols, stack_size, filters) # new: (kernel_rows, kernel_cols, filters, stack_size) weights[0] = np.transpose(weights[0], (0, 1, 3, 2)) if layer.data_format == 'channels_first': # old: (filters, stack_size, kernel_rows, kernel_cols) # new: (kernel_rows, kernel_cols, filters, stack_size) weights[0] = np.transpose(weights[0], (2, 3, 0, 1)) if layer.__class__.__name__ == 'Conv3D': if layer.data_format == 'channels_first': # old: (filters, stack_size, ...) # new: (..., stack_size, filters) weights[0] = np.transpose(weights[0], (2, 3, 4, 1, 0)) if layer.__class__.__name__ == 'GRU': if len(weights) == 9: kernel = np.concatenate([weights[0], weights[3], weights[6]], axis=-1) recurrent_kernel = np.concatenate( [weights[1], weights[4], weights[7]], axis=-1) bias = np.concatenate([weights[2], weights[5], weights[8]], axis=-1) weights = [kernel, recurrent_kernel, bias] if layer.__class__.__name__ == 'LSTM': if len(weights) == 12: # old: i, c, f, o # new: i, f, c, o kernel = np.concatenate( [weights[0], weights[6], weights[3], weights[9]], axis=-1) recurrent_kernel = np.concatenate( [weights[1], weights[7], weights[4], weights[10]], axis=-1) bias = np.concatenate( [weights[2], weights[8], weights[5], weights[11]], axis=-1) weights = [kernel, recurrent_kernel, bias] if layer.__class__.__name__ == 'ConvLSTM2D': if len(weights) == 12: kernel = np.concatenate( [weights[0], weights[6], weights[3], weights[9]], axis=-1) recurrent_kernel = np.concatenate( [weights[1], weights[7], weights[4], weights[10]], axis=-1) bias = np.concatenate( [weights[2], weights[8], weights[5], weights[11]], axis=-1) if layer.data_format == 'channels_first': # old: (filters, stack_size, kernel_rows, kernel_cols) # new: (kernel_rows, kernel_cols, stack_size, filters) kernel = np.transpose(kernel, (2, 3, 1, 0)) recurrent_kernel = np.transpose(recurrent_kernel, (2, 3, 1, 0)) weights = [kernel, recurrent_kernel, bias] conv_layers = ['Conv1D', 'Conv2D', 'Conv3D', 'Conv2DTranspose', 'ConvLSTM2D'] if layer.__class__.__name__ in conv_layers: if backend.int_shape(layer.weights[0]) != weights[0].shape: weights[0] = np.transpose(weights[0], (3, 2, 0, 1)) if layer.__class__.__name__ == 'ConvLSTM2D': weights[1] = np.transpose(weights[1], (3, 2, 0, 1)) # convert cuDNN layers return _convert_rnn_weights(layer, weights) def _convert_rnn_weights(layer, weights): """Converts weights for RNN layers between native and cuDNN format. Input kernels for each gate are transposed and converted between Fortran and C layout, recurrent kernels are transposed. For LSTM biases are summed/ split in half, for GRU biases are reshaped. Weights can be converted in both directions between `LSTM` and`CuDNNSLTM` and between `CuDNNGRU` and `GRU(reset_after=True)`. Default `GRU` is not compatible with `CuDNNGRU`. For missing biases in `LSTM`/`GRU` (`use_bias=False`) no conversion is made. Args: layer: Target layer instance. weights: List of source weights values (input kernels, recurrent kernels, [biases]) (Numpy arrays). Returns: A list of converted weights values (Numpy arrays). Raises: ValueError: for incompatible GRU layer/weights or incompatible biases """ def transform_kernels(kernels, func, n_gates): """Transforms kernel for each gate separately using given function. Args: kernels: Stacked array of kernels for individual gates. func: Function applied to kernel of each gate. n_gates: Number of gates (4 for LSTM, 3 for GRU). Returns: Stacked array of transformed kernels. """ return np.hstack([func(k) for k in np.hsplit(kernels, n_gates)]) def transpose_input(from_cudnn): """Makes a function that transforms input kernels from/to cuDNN format. It keeps the shape, but changes between the layout (Fortran/C). Eg.: ``` Keras cuDNN [[0, 1, 2], <---> [[0, 2, 4], [3, 4, 5]] [1, 3, 5]] ``` It can be passed to `transform_kernels()`. Args: from_cudnn: `True` if source weights are in cuDNN format, `False` if they're in plain Keras format. Returns: Function that converts input kernel to the other format. """ order = 'F' if from_cudnn else 'C' def transform(kernel): return kernel.T.reshape(kernel.shape, order=order) return transform target_class = layer.__class__.__name__ # convert the weights between CuDNNLSTM and LSTM if target_class in ['LSTM', 'CuDNNLSTM'] and len(weights) == 3: # determine if we're loading a CuDNNLSTM layer # from the number of bias weights: # CuDNNLSTM has (units * 8) weights; while LSTM has (units * 4) # if there's no bias weight in the file, skip this conversion units = weights[1].shape[0] bias_shape = weights[2].shape n_gates = 4 if bias_shape == (2 * units * n_gates,): source = 'CuDNNLSTM' elif bias_shape == (units * n_gates,): source = 'LSTM' else: raise ValueError('Invalid bias shape: ' + str(bias_shape)) def convert_lstm_weights(weights, from_cudnn=True): """Converts the weights between CuDNNLSTM and LSTM. Args: weights: Original weights. from_cudnn: Indicates whether original weights are from cuDNN layer. Returns: Updated weights compatible with LSTM. """ # Transpose (and reshape) input and recurrent kernels kernels = transform_kernels(weights[0], transpose_input(from_cudnn), n_gates) recurrent_kernels = transform_kernels(weights[1], lambda k: k.T, n_gates) if from_cudnn: # merge input and recurrent biases into a single set biases = np.sum(np.split(weights[2], 2, axis=0), axis=0) else: # Split single set of biases evenly to two sets. The way of # splitting doesn't matter as long as the two sets sum is kept. biases = np.tile(0.5 * weights[2], 2) return [kernels, recurrent_kernels, biases] if source != target_class: weights = convert_lstm_weights(weights, from_cudnn=source == 'CuDNNLSTM') # convert the weights between CuDNNGRU and GRU(reset_after=True) if target_class in ['GRU', 'CuDNNGRU'] and len(weights) == 3: # We can determine the source of the weights from the shape of the bias. # If there is no bias we skip the conversion since # CuDNNGRU always has biases. units = weights[1].shape[0] bias_shape = weights[2].shape n_gates = 3 def convert_gru_weights(weights, from_cudnn=True): """Converts the weights between CuDNNGRU and GRU. Args: weights: Original weights. from_cudnn: Indicates whether original weights are from cuDNN layer. Returns: Updated weights compatible with GRU. """ kernels = transform_kernels(weights[0], transpose_input(from_cudnn), n_gates) recurrent_kernels = transform_kernels(weights[1], lambda k: k.T, n_gates) biases = np.array(weights[2]).reshape((2, -1) if from_cudnn else -1) return [kernels, recurrent_kernels, biases] if bias_shape == (2 * units * n_gates,): source = 'CuDNNGRU' elif bias_shape == (2, units * n_gates): source = 'GRU(reset_after=True)' elif bias_shape == (units * n_gates,): source = 'GRU(reset_after=False)' else: raise ValueError('Invalid bias shape: ' + str(bias_shape)) if target_class == 'CuDNNGRU': target = 'CuDNNGRU' elif layer.reset_after: target = 'GRU(reset_after=True)' else: target = 'GRU(reset_after=False)' # only convert between different types if source != target: types = (source, target) if 'GRU(reset_after=False)' in types: raise ValueError('%s is not compatible with %s' % types) if source == 'CuDNNGRU': weights = convert_gru_weights(weights, from_cudnn=True) elif source == 'GRU(reset_after=True)': weights = convert_gru_weights(weights, from_cudnn=False) return weights def save_optimizer_weights_to_hdf5_group(hdf5_group, optimizer): """Saves optimizer weights of a optimizer to a HDF5 group. Args: hdf5_group: HDF5 group. optimizer: optimizer instance. """ symbolic_weights = getattr(optimizer, 'weights') if symbolic_weights: weights_group = hdf5_group.create_group('optimizer_weights') weight_names = [str(w.name).encode('utf8') for w in symbolic_weights] save_attributes_to_hdf5_group(weights_group, 'weight_names', weight_names) weight_values = backend.batch_get_value(symbolic_weights) for name, val in zip(weight_names, weight_values): param_dset = weights_group.create_dataset( name, val.shape, dtype=val.dtype) if not val.shape: # scalar param_dset[()] = val else: param_dset[:] = val def load_optimizer_weights_from_hdf5_group(hdf5_group): """Load optimizer weights from a HDF5 group. Args: hdf5_group: A pointer to a HDF5 group. Returns: data: List of optimizer weight names. """ weights_group = hdf5_group['optimizer_weights'] optimizer_weight_names = load_attributes_from_hdf5_group( weights_group, 'weight_names') return [weights_group[weight_name] for weight_name in optimizer_weight_names] def save_subset_weights_to_hdf5_group(f, weights): """Save top-level weights of a model to a HDF5 group. Args: f: HDF5 group. weights: List of weight variables. """ weight_values = backend.batch_get_value(weights) weight_names = [w.name.encode('utf8') for w in weights] save_attributes_to_hdf5_group(f, 'weight_names', weight_names) for name, val in zip(weight_names, weight_values): param_dset = f.create_dataset(name, val.shape, dtype=val.dtype) if not val.shape: # scalar param_dset[()] = val else: param_dset[:] = val def save_weights_to_hdf5_group(f, model): """Saves the weights of a list of layers to a HDF5 group. Args: f: HDF5 group. model: Model instance. """ from keras import __version__ as keras_version # pylint: disable=g-import-not-at-top save_attributes_to_hdf5_group( f, 'layer_names', [layer.name.encode('utf8') for layer in model.layers]) f.attrs['backend'] = backend.backend().encode('utf8') f.attrs['keras_version'] = str(keras_version).encode('utf8') # Sort model layers by layer name to ensure that group names are strictly # growing to avoid prefix issues. for layer in sorted(model.layers, key=lambda x: x.name): g = f.create_group(layer.name) weights = _legacy_weights(layer) save_subset_weights_to_hdf5_group(g, weights) weights = model._trainable_weights + model._non_trainable_weights g = f.create_group('top_level_model_weights') save_subset_weights_to_hdf5_group(g, weights) def load_subset_weights_from_hdf5_group(f): """Load layer weights of a model from hdf5. Args: f: A pointer to a HDF5 group. Returns: List of NumPy arrays of the weight values. Raises: ValueError: in case of mismatch between provided model and weights file. """ weight_names = load_attributes_from_hdf5_group(f, 'weight_names') return [np.asarray(f[weight_name]) for weight_name in weight_names] def load_weights_from_hdf5_group(f, model): """Implements topological (order-based) weight loading. Args: f: A pointer to a HDF5 group. model: Model instance. Raises: ValueError: in case of mismatch between provided layers and weights file. """ if 'keras_version' in f.attrs: original_keras_version = f.attrs['keras_version'] if hasattr(original_keras_version, 'decode'): original_keras_version = original_keras_version.decode('utf8') else: original_keras_version = '1' if 'backend' in f.attrs: original_backend = f.attrs['backend'] if hasattr(original_backend, 'decode'): original_backend = original_backend.decode('utf8') else: original_backend = None filtered_layers = [] for layer in model.layers: weights = _legacy_weights(layer) if weights: filtered_layers.append(layer) layer_names = load_attributes_from_hdf5_group(f, 'layer_names') filtered_layer_names = [] for name in layer_names: g = f[name] weight_names = load_attributes_from_hdf5_group(g, 'weight_names') if weight_names: filtered_layer_names.append(name) layer_names = filtered_layer_names if len(layer_names) != len(filtered_layers): raise ValueError( f'Layer count mismatch when loading weights from file. ' f'Model expected {len(filtered_layers)} layers, found ' f'{len(layer_names)} saved layers.') # We batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for k, name in enumerate(layer_names): g = f[name] layer = filtered_layers[k] symbolic_weights = _legacy_weights(layer) weight_values = load_subset_weights_from_hdf5_group(g) weight_values = preprocess_weights_for_loading(layer, weight_values, original_keras_version, original_backend) if len(weight_values) != len(symbolic_weights): raise ValueError( f'Weight count mismatch for layer #{k} (named {layer.name} in the ' f'current model, {name} in the save file). ' f'Layer expects {len(symbolic_weights)} weight(s). Received ' f'{len(weight_values)} saved weight(s)') weight_value_tuples += zip(symbolic_weights, weight_values) if 'top_level_model_weights' in f: symbolic_weights = model._trainable_weights + model._non_trainable_weights weight_values = load_subset_weights_from_hdf5_group( f['top_level_model_weights']) if len(weight_values) != len(symbolic_weights): raise ValueError( f'Weight count mismatch for top-level weights when loading weights ' f'from file. ' f'Model expects {len(symbolic_weights)} top-level weight(s). ' f'Received {len(weight_values)} saved top-level weight(s)') weight_value_tuples += zip(symbolic_weights, weight_values) backend.batch_set_value(weight_value_tuples) def load_weights_from_hdf5_group_by_name(f, model, skip_mismatch=False): """Implements name-based weight loading (instead of topological loading). Layers that have no matching name are skipped. Args: f: A pointer to a HDF5 group. model: Model instance. skip_mismatch: Boolean, whether to skip loading of layers where there is a mismatch in the number of weights, or a mismatch in the shape of the weights. Raises: ValueError: in case of mismatch between provided layers and weights file and skip_match=False. """ if 'keras_version' in f.attrs: original_keras_version = f.attrs['keras_version'] if hasattr(original_keras_version, 'decode'): original_keras_version = original_keras_version.decode('utf8') else: original_keras_version = '1' if 'backend' in f.attrs: original_backend = f.attrs['backend'] if hasattr(original_backend, 'decode'): original_backend = original_backend.decode('utf8') else: original_backend = None # New file format. layer_names = load_attributes_from_hdf5_group(f, 'layer_names') # Reverse index of layer name to list of layers with name. index = {} for layer in model.layers: if layer.name: index.setdefault(layer.name, []).append(layer) # We batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for k, name in enumerate(layer_names): g = f[name] weight_values = load_subset_weights_from_hdf5_group(g) for layer in index.get(name, []): symbolic_weights = _legacy_weights(layer) weight_values = preprocess_weights_for_loading( layer, weight_values, original_keras_version, original_backend) if len(weight_values) != len(symbolic_weights): if skip_mismatch: logging.warning( f'Skipping loading of weights for layer #{k} (named ' f'{layer.name}) due to mismatch in number of weights. ' f'Layer expects {len(symbolic_weights)} weight(s). Received ' f'{len(weight_values)} saved weight(s)') continue raise ValueError( f'Weight count mismatch for layer #{k} (named {layer.name}). ' f'Layer expects {len(symbolic_weights)} weight(s). Received ' f'{len(weight_values)} saved weight(s)') # Set values. for i in range(len(weight_values)): expected_shape = backend.int_shape(symbolic_weights[i]) received_shape = weight_values[i].shape if expected_shape != received_shape: if skip_mismatch: logging.warning( f'Skipping loading weights for layer #{k} (named ' f'{layer.name}) due to mismatch in shape for weight ' f'{symbolic_weights[i].name}. ' f'Weight expects shape {expected_shape}. Received saved weight ' f'with shape {received_shape}') continue raise ValueError( f'Shape mismatch in layer #{k} (named {layer.name}) for weight ' f'{symbolic_weights[i].name}. ' f'Weight expects shape {expected_shape}. Received saved weight ' f'with shape {received_shape}') else: weight_value_tuples.append((symbolic_weights[i], weight_values[i])) if 'top_level_model_weights' in f: symbolic_weights = model._trainable_weights + model._non_trainable_weights weight_values = load_subset_weights_from_hdf5_group( f['top_level_model_weights']) if len(weight_values) != len(symbolic_weights): if skip_mismatch: logging.warning( f'Skipping loading top-level weights for model due to mismatch ' f'in number of weights. ' f'Model expects {len(symbolic_weights)} top-level weight(s). ' f'Received {len(weight_values)} saved top-level weight(s)') else: raise ValueError( f'Weight count mismatch for top-level weights of model. ' f'Model expects {len(symbolic_weights)} top-level weight(s). ' f'Received {len(weight_values)} saved top-level weight(s)') else: for i in range(len(weight_values)): expected_shape = backend.int_shape(symbolic_weights[i]) received_shape = weight_values[i].shape if expected_shape != received_shape: if skip_mismatch: logging.warning( f'Skipping loading top-level weight for model due to ' f'mismatch in shape for weight {symbolic_weights[i].name}. ' f'Weight expects shape {expected_shape}. Received saved weight ' f'with shape {received_shape}') else: raise ValueError( f'Shape mismatch in model for top-level weight ' f'{symbolic_weights[i].name}. ' f'Weight expects shape {expected_shape}. Received saved weight ' f'with shape {received_shape}') else: weight_value_tuples.append((symbolic_weights[i], weight_values[i])) backend.batch_set_value(weight_value_tuples) def save_attributes_to_hdf5_group(group, name, data): """Saves attributes (data) of the specified name into the HDF5 group. This method deals with an inherent problem of HDF5 file which is not able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes. Args: group: A pointer to a HDF5 group. name: A name of the attributes to save. data: Attributes data to store. Raises: RuntimeError: If any single attribute is too large to be saved. """ # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. bad_attributes = [x for x in data if len(x) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because they ' f'are larger than {HDF5_OBJECT_HEADER_LIMIT} bytes: {bad_attributes}') data_npy = np.asarray(data) num_chunks = 1 chunked_data = np.array_split(data_npy, num_chunks) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data): num_chunks += 1 chunked_data = np.array_split(data_npy, num_chunks) if num_chunks > 1: for chunk_id, chunk_data in enumerate(chunked_data): group.attrs['%s%d' % (name, chunk_id)] = chunk_data else: group.attrs[name] = data def load_attributes_from_hdf5_group(group, name): """Loads attributes of the specified name from the HDF5 group. This method deals with an inherent problem of HDF5 file which is not able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes. Args: group: A pointer to a HDF5 group. name: A name of the attributes to load. Returns: data: Attributes data. """ if name in group.attrs: data = [ n.decode('utf8') if hasattr(n, 'decode') else n for n in group.attrs[name] ] else: data = [] chunk_id = 0 while '%s%d' % (name, chunk_id) in group.attrs: data.extend([ n.decode('utf8') if hasattr(n, 'decode') else n for n in group.attrs['%s%d' % (name, chunk_id)] ]) chunk_id += 1 return data def _legacy_weights(layer): """DO NOT USE. For legacy reason, the layer.weights was in the order of [self.trainable_weights + self.non_trainable_weights], and this order was used for preserving the weights in h5 format. The new order of layer.weights are the same as layer.get_weights() which is more intuitive for user. To keep supporting the existing saved h5 file, this method should be used to save/load weights. In future version, we will delete this method and introduce a breaking change for h5 and stay with the new order for weights. Args: layer: a `tf.keras.Model` or `tf.keras.layers.Layer` instance. Returns: A list of variables with the order of trainable_weights, followed by non_trainable_weights. """ weights = layer.trainable_weights + layer.non_trainable_weights if any(not isinstance(w, tf.Variable) for w in weights): raise NotImplementedError( f'Save or restore weights that is not an instance of `tf.Variable` is ' f'not supported in h5, use `save_format=\'tf\'` instead. Received a ' f'model or layer {layer.__class__.__name__} with weights {weights}') return weights
36,507
36.405738
107
py
keras
keras-master/keras/saving/utils_v1/export_utils.py
# Copyright 2017 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. # ============================================================================== # LINT.IfChange """Utilities for creating SavedModels.""" import collections import os import time from keras.saving.utils_v1 import export_output as export_output_lib from keras.saving.utils_v1 import mode_keys from keras.saving.utils_v1 import unexported_constants from keras.saving.utils_v1.mode_keys import KerasModeKeys as ModeKeys import tensorflow.compat.v2 as tf from tensorflow.python.platform import tf_logging as logging # Mapping of the modes to appropriate MetaGraph tags in the SavedModel. EXPORT_TAG_MAP = mode_keys.ModeKeyMap(**{ ModeKeys.PREDICT: [tf.saved_model.SERVING], ModeKeys.TRAIN: [tf.saved_model.TRAINING], ModeKeys.TEST: [unexported_constants.EVAL]}) # For every exported mode, a SignatureDef map should be created using the # functions `export_outputs_for_mode` and `build_all_signature_defs`. By # default, this map will contain a single Signature that defines the input # tensors and output predictions, losses, and/or metrics (depending on the mode) # The default keys used in the SignatureDef map are defined below. SIGNATURE_KEY_MAP = mode_keys.ModeKeyMap(**{ ModeKeys.PREDICT: tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY, ModeKeys.TRAIN: unexported_constants.DEFAULT_TRAIN_SIGNATURE_DEF_KEY, ModeKeys.TEST: unexported_constants.DEFAULT_EVAL_SIGNATURE_DEF_KEY}) # Default names used in the SignatureDef input map, which maps strings to # TensorInfo protos. SINGLE_FEATURE_DEFAULT_NAME = 'feature' SINGLE_RECEIVER_DEFAULT_NAME = 'input' SINGLE_LABEL_DEFAULT_NAME = 'label' ### Below utilities are specific to SavedModel exports. def build_all_signature_defs(receiver_tensors, export_outputs, receiver_tensors_alternatives=None, serving_only=True): """Build `SignatureDef`s for all export outputs. Args: receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying input nodes where this receiver expects to be fed by default. Typically, this is a single placeholder expecting serialized `tf.Example` protos. export_outputs: a dict of ExportOutput instances, each of which has an as_signature_def instance method that will be called to retrieve the signature_def for all export output tensors. receiver_tensors_alternatives: a dict of string to additional groups of receiver tensors, each of which may be a `Tensor` or a dict of string to `Tensor`. These named receiver tensor alternatives generate additional serving signatures, which may be used to feed inputs at different points within the input receiver subgraph. A typical usage is to allow feeding raw feature `Tensor`s *downstream* of the tf.io.parse_example() op. Defaults to None. serving_only: boolean; if true, resulting signature defs will only include valid serving signatures. If false, all requested signatures will be returned. Returns: signature_def representing all passed args. Raises: ValueError: if export_outputs is not a dict """ if not isinstance(receiver_tensors, dict): receiver_tensors = {SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors} if export_outputs is None or not isinstance(export_outputs, dict): raise ValueError('`export_outputs` must be a dict. Received ' f'{export_outputs} with type ' f'{type(export_outputs).__name__}.') signature_def_map = {} excluded_signatures = {} for output_key, export_output in export_outputs.items(): signature_name = '{}'.format(output_key or 'None') try: signature = export_output.as_signature_def(receiver_tensors) signature_def_map[signature_name] = signature except ValueError as e: excluded_signatures[signature_name] = str(e) if receiver_tensors_alternatives: for receiver_name, receiver_tensors_alt in ( receiver_tensors_alternatives.items()): if not isinstance(receiver_tensors_alt, dict): receiver_tensors_alt = { SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors_alt } for output_key, export_output in export_outputs.items(): signature_name = '{}:{}'.format(receiver_name or 'None', output_key or 'None') try: signature = export_output.as_signature_def(receiver_tensors_alt) signature_def_map[signature_name] = signature except ValueError as e: excluded_signatures[signature_name] = str(e) _log_signature_report(signature_def_map, excluded_signatures) # The above calls to export_output_lib.as_signature_def should return only # valid signatures; if there is a validity problem, they raise a ValueError, # in which case we exclude that signature from signature_def_map above. # The is_valid_signature check ensures that the signatures produced are # valid for serving, and acts as an additional sanity check for export # signatures produced for serving. We skip this check for training and eval # signatures, which are not intended for serving. if serving_only: signature_def_map = { k: v for k, v in signature_def_map.items() if tf.compat.v1.saved_model.is_valid_signature(v) } return signature_def_map _FRIENDLY_METHOD_NAMES = { tf.saved_model.CLASSIFY_METHOD_NAME: 'Classify', tf.saved_model.REGRESS_METHOD_NAME: 'Regress', tf.saved_model.PREDICT_METHOD_NAME: 'Predict', unexported_constants.SUPERVISED_TRAIN_METHOD_NAME: 'Train', unexported_constants.SUPERVISED_EVAL_METHOD_NAME: 'Eval', } def _log_signature_report(signature_def_map, excluded_signatures): """Log a report of which signatures were produced.""" sig_names_by_method_name = collections.defaultdict(list) # We'll collect whatever method_names are present, but also we want to make # sure to output a line for each of the three standard methods even if they # have no signatures. for method_name in _FRIENDLY_METHOD_NAMES: sig_names_by_method_name[method_name] = [] for signature_name, sig in signature_def_map.items(): sig_names_by_method_name[sig.method_name].append(signature_name) # TODO(b/67733540): consider printing the full signatures, not just names for method_name, sig_names in sig_names_by_method_name.items(): if method_name in _FRIENDLY_METHOD_NAMES: method_name = _FRIENDLY_METHOD_NAMES[method_name] logging.info('Signatures INCLUDED in export for {}: {}'.format( method_name, sig_names if sig_names else 'None')) if excluded_signatures: logging.info('Signatures EXCLUDED from export because they cannot be ' 'be served via TensorFlow Serving APIs:') for signature_name, message in excluded_signatures.items(): logging.info('\'{}\' : {}'.format(signature_name, message)) if not signature_def_map: logging.warning('Export includes no signatures!') elif (tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in signature_def_map): logging.warning('Export includes no default signature!') # When we create a timestamped directory, there is a small chance that the # directory already exists because another process is also creating these # directories. In this case we just wait one second to get a new timestamp and # try again. If this fails several times in a row, then something is seriously # wrong. MAX_DIRECTORY_CREATION_ATTEMPTS = 10 def get_timestamped_export_dir(export_dir_base): """Builds a path to a new subdirectory within the base directory. Each export is written into a new subdirectory named using the current time. This guarantees monotonically increasing version numbers even across multiple runs of the pipeline. The timestamp used is the number of seconds since epoch UTC. Args: export_dir_base: A string containing a directory to write the exported graph and checkpoints. Returns: The full path of the new subdirectory (which is not actually created yet). Raises: RuntimeError: if repeated attempts fail to obtain a unique timestamped directory name. """ attempts = 0 while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS: timestamp = int(time.time()) result_dir = os.path.join( tf.compat.as_bytes(export_dir_base), tf.compat.as_bytes(str(timestamp))) if not tf.compat.v1.gfile.Exists(result_dir): # Collisions are still possible (though extremely unlikely): this # directory is not actually created yet, but it will be almost # instantly on return from this function. return result_dir time.sleep(1) attempts += 1 logging.warning( 'Directory {} already exists; retrying (attempt {}/{})'.format( tf.compat.as_str(result_dir), attempts, MAX_DIRECTORY_CREATION_ATTEMPTS)) raise RuntimeError('Failed to obtain a unique export directory name after ' f'{MAX_DIRECTORY_CREATION_ATTEMPTS} attempts.') def get_temp_export_dir(timestamped_export_dir): """Builds a directory name based on the argument but starting with 'temp-'. This relies on the fact that TensorFlow Serving ignores subdirectories of the base directory that can't be parsed as integers. Args: timestamped_export_dir: the name of the eventual export directory, e.g. /foo/bar/<timestamp> Returns: A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-<timestamp>. """ (dirname, basename) = os.path.split(timestamped_export_dir) if isinstance(basename, bytes): str_name = basename.decode('utf-8') else: str_name = str(basename) temp_export_dir = os.path.join( tf.compat.as_bytes(dirname), tf.compat.as_bytes('temp-{}'.format(str_name))) return temp_export_dir def export_outputs_for_mode( mode, serving_export_outputs=None, predictions=None, loss=None, metrics=None): """Util function for constructing a `ExportOutput` dict given a mode. The returned dict can be directly passed to `build_all_signature_defs` helper function as the `export_outputs` argument, used for generating a SignatureDef map. Args: mode: A `ModeKeys` specifying the mode. serving_export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict or None. predictions: A dict of Tensors or single Tensor representing model predictions. This argument is only used if serving_export_outputs is not set. loss: A dict of Tensors or single Tensor representing calculated loss. metrics: A dict of (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op Returns: Dictionary mapping the a key to an `tf.estimator.export.ExportOutput` object The key is the expected SignatureDef key for the mode. Raises: ValueError: if an appropriate ExportOutput cannot be found for the mode. """ if mode not in SIGNATURE_KEY_MAP: raise ValueError( f'Export output type not found for `mode`: {mode}. Expected one of: ' f'{list(SIGNATURE_KEY_MAP.keys())}.\n' 'One likely error is that V1 Estimator Modekeys were somehow passed to ' 'this function. Please ensure that you are using the new ModeKeys.') signature_key = SIGNATURE_KEY_MAP[mode] if mode_keys.is_predict(mode): return get_export_outputs(serving_export_outputs, predictions) elif mode_keys.is_train(mode): return {signature_key: export_output_lib.TrainOutput( loss=loss, predictions=predictions, metrics=metrics)} else: return {signature_key: export_output_lib.EvalOutput( loss=loss, predictions=predictions, metrics=metrics)} def get_export_outputs(export_outputs, predictions): """Validate export_outputs or create default export_outputs. Args: export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict or None. predictions: Predictions `Tensor` or dict of `Tensor`. Returns: Valid export_outputs dict Raises: TypeError: if export_outputs is not a dict or its values are not ExportOutput instances. """ if export_outputs is None: default_output = export_output_lib.PredictOutput(predictions) export_outputs = { tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: default_output} if not isinstance(export_outputs, dict): raise TypeError( f'`export_outputs` must be dict, received: {export_outputs}.') for v in export_outputs.values(): if not isinstance(v, export_output_lib.ExportOutput): raise TypeError( 'Values in `export_outputs` must be ExportOutput objects, ' f'received: {export_outputs}.') _maybe_add_default_serving_output(export_outputs) return export_outputs def _maybe_add_default_serving_output(export_outputs): """Add a default serving output to the export_outputs if not present. Args: export_outputs: Describes the output signatures to be exported to `SavedModel` and used during serving. Should be a dict. Returns: export_outputs dict with default serving signature added if necessary Raises: ValueError: if multiple export_outputs were provided without a default serving key. """ if len(export_outputs) == 1: (key, value), = export_outputs.items() if key != tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY: export_outputs[ tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = value if len(export_outputs) > 1: if (tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in export_outputs): raise ValueError( 'Multiple `export_outputs` were provided, but none of them are ' 'specified as the default. Use' '`tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY` to ' 'specify a default.') return export_outputs # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_utils.py)
14,704
40.075419
80
py
keras
keras-master/keras/saving/utils_v1/unexported_constants.py
# 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. # ============================================================================== """Signature constants for SavedModel save and restore operations. These are the private constants that have not been exported. """ # LINT.IfChange DEFAULT_TRAIN_SIGNATURE_DEF_KEY = "train" DEFAULT_EVAL_SIGNATURE_DEF_KEY = "eval" SUPERVISED_TRAIN_METHOD_NAME = "tensorflow/supervised/training" SUPERVISED_EVAL_METHOD_NAME = "tensorflow/supervised/eval" # LINT.ThenChange(//tensorflow/python/saved_model/signature_constants.py) # LINT.IfChange EVAL = "eval" # LINT.ThenChange(//tensorflow/python/saved_model/tag_constants.py)
1,220
36
80
py
keras
keras-master/keras/saving/utils_v1/signature_def_utils.py
# 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. # ============================================================================== """SignatureDef utility functions implementation.""" import tensorflow.compat.v2 as tf from keras.saving.utils_v1 import unexported_constants # LINT.IfChange def supervised_train_signature_def( inputs, loss, predictions=None, metrics=None): return _supervised_signature_def( unexported_constants.SUPERVISED_TRAIN_METHOD_NAME, inputs, loss=loss, predictions=predictions, metrics=metrics) def supervised_eval_signature_def( inputs, loss, predictions=None, metrics=None): return _supervised_signature_def( unexported_constants.SUPERVISED_EVAL_METHOD_NAME, inputs, loss=loss, predictions=predictions, metrics=metrics) def _supervised_signature_def( method_name, inputs, loss=None, predictions=None, metrics=None): """Creates a signature for training and eval data. This function produces signatures that describe the inputs and outputs of a supervised process, such as training or evaluation, that results in loss, metrics, and the like. Note that this function only requires inputs to be not None. Args: method_name: Method name of the SignatureDef as a string. inputs: dict of string to `Tensor`. loss: dict of string to `Tensor` representing computed loss. predictions: dict of string to `Tensor` representing the output predictions. metrics: dict of string to `Tensor` representing metric ops. Returns: A train- or eval-flavored signature_def. Raises: ValueError: If inputs or outputs is `None`. """ if inputs is None or not inputs: raise ValueError('f{method_name} `inputs` cannot be None or empty.') signature_inputs = {key: tf.compat.v1.saved_model.build_tensor_info(tensor) for key, tensor in inputs.items()} signature_outputs = {} for output_set in (loss, predictions, metrics): if output_set is not None: sig_out = {key: tf.compat.v1.saved_model.build_tensor_info(tensor) for key, tensor in output_set.items()} signature_outputs.update(sig_out) signature_def = tf.compat.v1.saved_model.build_signature_def( signature_inputs, signature_outputs, method_name) return signature_def # LINT.ThenChange(//keras/saving/utils_v1/signature_def_utils.py)
2,922
36.474359
80
py
keras
keras-master/keras/saving/utils_v1/mode_keys.py
# 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. # ============================================================================== # LINT.IfChange """Utils for managing different mode strings used by Keras and Estimator models. """ import collections class KerasModeKeys: """Standard names for model modes. The following standard keys are defined: * `TRAIN`: training/fitting mode. * `TEST`: testing/evaluation mode. * `PREDICT`: prediction/inference mode. """ TRAIN = 'train' TEST = 'test' PREDICT = 'predict' # TODO(kathywu): Remove copy in Estimator after nightlies class EstimatorModeKeys: """Standard names for Estimator model modes. The following standard keys are defined: * `TRAIN`: training/fitting mode. * `EVAL`: testing/evaluation mode. * `PREDICT`: predication/inference mode. """ TRAIN = 'train' EVAL = 'eval' PREDICT = 'infer' def is_predict(mode): return mode in [KerasModeKeys.PREDICT, EstimatorModeKeys.PREDICT] def is_eval(mode): return mode in [KerasModeKeys.TEST, EstimatorModeKeys.EVAL] def is_train(mode): return mode in [KerasModeKeys.TRAIN, EstimatorModeKeys.TRAIN] class ModeKeyMap(collections.abc.Mapping): """Map using ModeKeys as keys. This class creates an immutable mapping from modes to values. For example, SavedModel export of Keras and Estimator models use this to map modes to their corresponding MetaGraph tags/SignatureDef keys. Since this class uses modes, rather than strings, as keys, both "predict" (Keras's PREDICT ModeKey) and "infer" (Estimator's PREDICT ModeKey) map to the same value. """ def __init__(self, **kwargs): self._internal_dict = {} self._keys = [] for key in kwargs: self._keys.append(key) dict_key = self._get_internal_key(key) if dict_key in self._internal_dict: raise ValueError( 'Error creating ModeKeyMap. Multiple keys/values found for {} mode.' .format(dict_key)) self._internal_dict[dict_key] = kwargs[key] def _get_internal_key(self, key): """Return keys used for the internal dictionary.""" if is_train(key): return KerasModeKeys.TRAIN if is_eval(key): return KerasModeKeys.TEST if is_predict(key): return KerasModeKeys.PREDICT raise ValueError('Invalid mode key: {}.'.format(key)) def __getitem__(self, key): return self._internal_dict[self._get_internal_key(key)] def __iter__(self): return iter(self._keys) def __len__(self): return len(self._keys) # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/mode_keys.py)
3,167
28.333333
80
py
keras
keras-master/keras/saving/utils_v1/__init__.py
# 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. # ============================================================================== # LINT.IfChange """Utils for saving a Keras Model or Estimator to the SavedModel format.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from keras.saving.utils_v1.export_output import * from keras.saving.utils_v1.export_utils import build_all_signature_defs from keras.saving.utils_v1.export_utils import export_outputs_for_mode from keras.saving.utils_v1.export_utils import EXPORT_TAG_MAP from keras.saving.utils_v1.export_utils import get_export_outputs from keras.saving.utils_v1.export_utils import get_temp_export_dir from keras.saving.utils_v1.export_utils import get_timestamped_export_dir from keras.saving.utils_v1.export_utils import SIGNATURE_KEY_MAP # pylint: enable=wildcard-import # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/__init__.py)
1,560
47.78125
80
py
keras
keras-master/keras/saving/utils_v1/export_output.py
# Copyright 2017 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. # ============================================================================== # LINT.IfChange """Classes for different types of export output.""" import tensorflow.compat.v2 as tf import abc from keras.saving.utils_v1 import signature_def_utils as unexported_signature_utils class ExportOutput: """Represents an output of a model that can be served. These typically correspond to model heads. """ __metaclass__ = abc.ABCMeta _SEPARATOR_CHAR = '/' @abc.abstractmethod def as_signature_def(self, receiver_tensors): """Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs. Args: receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying input nodes that will be fed. """ pass def _check_output_key(self, key, error_label): # For multi-head models, the key can be a tuple. if isinstance(key, tuple): key = self._SEPARATOR_CHAR.join(key) if not isinstance(key, str): raise ValueError( '{} output key must be a string; got {}.'.format(error_label, key)) return key def _wrap_and_check_outputs( self, outputs, single_output_default_name, error_label=None): """Wraps raw tensors as dicts and checks type. Note that we create a new dict here so that we can overwrite the keys if necessary. Args: outputs: A `Tensor` or a dict of string to `Tensor`. single_output_default_name: A string key for use in the output dict if the provided `outputs` is a raw tensor. error_label: descriptive string for use in error messages. If none, single_output_default_name will be used. Returns: A dict of tensors Raises: ValueError: if the outputs dict keys are not strings or tuples of strings or the values are not Tensors. """ if not isinstance(outputs, dict): outputs = {single_output_default_name: outputs} output_dict = {} for key, value in outputs.items(): error_name = error_label or single_output_default_name key = self._check_output_key(key, error_name) if not isinstance(value, tf.Tensor): raise ValueError( '{} output value must be a Tensor; got {}.'.format( error_name, value)) output_dict[key] = value return output_dict class ClassificationOutput(ExportOutput): """Represents the output of a classification head. Either classes or scores or both must be set. The classes `Tensor` must provide string labels, not integer class IDs. If only classes is set, it is interpreted as providing top-k results in descending order. If only scores is set, it is interpreted as providing a score for every class in order of class ID. If both classes and scores are set, they are interpreted as zipped, so each score corresponds to the class at the same index. Clients should not depend on the order of the entries. """ def __init__(self, scores=None, classes=None): """Constructor for `ClassificationOutput`. Args: scores: A float `Tensor` giving scores (sometimes but not always interpretable as probabilities) for each class. May be `None`, but only if `classes` is set. Interpretation varies-- see class doc. classes: A string `Tensor` giving predicted class labels. May be `None`, but only if `scores` is set. Interpretation varies-- see class doc. Raises: ValueError: if neither classes nor scores is set, or one of them is not a `Tensor` with the correct dtype. """ if (scores is not None and not (isinstance(scores, tf.Tensor) and scores.dtype.is_floating)): raise ValueError('Classification scores must be a float32 Tensor; ' 'got {}'.format(scores)) if (classes is not None and not (isinstance(classes, tf.Tensor) and tf.as_dtype(classes.dtype) == tf.string)): raise ValueError('Classification classes must be a string Tensor; ' 'got {}'.format(classes)) if scores is None and classes is None: raise ValueError('Cannot create a ClassificationOutput with empty ' 'arguments. At least one of `scores` and `classes` ' 'must be defined.') self._scores = scores self._classes = classes @property def scores(self): return self._scores @property def classes(self): return self._classes def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( 'Classification signatures can only accept a single tensor input of ' 'type tf.string. Please check to make sure that you have structured ' 'the serving_input_receiver_fn so that it creates a single string ' 'placeholder. If your model function expects multiple inputs, then ' 'use `tf.io.parse_example()` to parse the string into multiple ' f'tensors.\n Received: {receiver_tensors}') (_, examples), = receiver_tensors.items() if tf.as_dtype(examples.dtype) != tf.string: raise ValueError( 'Classification signatures can only accept a single tensor input of ' 'type tf.string. Please check to make sure that you have structured ' 'the serving_input_receiver_fn so that it creates a single string ' 'placeholder. If your model function expects multiple inputs, then ' 'use `tf.io.parse_example()` to parse the string into multiple ' f'tensors.\n Received: {receiver_tensors}') return tf.compat.v1.saved_model.classification_signature_def( examples, self.classes, self.scores) class RegressionOutput(ExportOutput): """Represents the output of a regression head.""" def __init__(self, value): """Constructor for `RegressionOutput`. Args: value: a float `Tensor` giving the predicted values. Required. Raises: ValueError: if the value is not a `Tensor` with dtype tf.float32. """ if not (isinstance(value, tf.Tensor) and value.dtype.is_floating): raise ValueError('Regression output value must be a float32 Tensor; ' 'got {}'.format(value)) self._value = value @property def value(self): return self._value def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( 'Regression signatures can only accept a single tensor input of ' 'type tf.string. Please check to make sure that you have structured ' 'the serving_input_receiver_fn so that it creates a single string ' 'placeholder. If your model function expects multiple inputs, then ' 'use `tf.io.parse_example()` to parse the string into multiple ' f'tensors.\n Received: {receiver_tensors}') (_, examples), = receiver_tensors.items() if tf.as_dtype(examples.dtype) != tf.string: raise ValueError( 'Regression signatures can only accept a single tensor input of ' 'type tf.string. Please check to make sure that you have structured ' 'the serving_input_receiver_fn so that it creates a single string ' 'placeholder. If your model function expects multiple inputs, then ' 'use `tf.io.parse_example()` to parse the string into multiple ' f'tensors.\n Received: {receiver_tensors}') return tf.compat.v1.saved_model.regression_signature_def(examples, self.value) class PredictOutput(ExportOutput): """Represents the output of a generic prediction head. A generic prediction need not be either a classification or a regression. Named outputs must be provided as a dict from string to `Tensor`, """ _SINGLE_OUTPUT_DEFAULT_NAME = 'output' def __init__(self, outputs): """Constructor for PredictOutput. Args: outputs: A `Tensor` or a dict of string to `Tensor` representing the predictions. Raises: ValueError: if the outputs is not dict, or any of its keys are not strings, or any of its values are not `Tensor`s. """ self._outputs = self._wrap_and_check_outputs( outputs, self._SINGLE_OUTPUT_DEFAULT_NAME, error_label='Prediction') @property def outputs(self): return self._outputs def as_signature_def(self, receiver_tensors): return tf.compat.v1.saved_model.predict_signature_def(receiver_tensors, self.outputs) class _SupervisedOutput(ExportOutput): """Represents the output of a supervised training or eval process.""" __metaclass__ = abc.ABCMeta LOSS_NAME = 'loss' PREDICTIONS_NAME = 'predictions' METRICS_NAME = 'metrics' METRIC_VALUE_SUFFIX = 'value' METRIC_UPDATE_SUFFIX = 'update_op' _loss = None _predictions = None _metrics = None def __init__(self, loss=None, predictions=None, metrics=None): """Constructor for SupervisedOutput (ie, Train or Eval output). Args: loss: dict of Tensors or single Tensor representing calculated loss. predictions: dict of Tensors or single Tensor representing model predictions. metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Raises: ValueError: if any of the outputs' dict keys are not strings or tuples of strings or the values are not Tensors (or Operations in the case of update_op). """ if loss is not None: loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME) self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME) if predictions is not None: pred_dict = self._wrap_and_check_outputs( predictions, self.PREDICTIONS_NAME) self._predictions = self._prefix_output_keys( pred_dict, self.PREDICTIONS_NAME) if metrics is not None: self._metrics = self._wrap_and_check_metrics(metrics) def _prefix_output_keys(self, output_dict, output_name): """Prepend output_name to the output_dict keys if it doesn't exist. This produces predictable prefixes for the pre-determined outputs of SupervisedOutput. Args: output_dict: dict of string to Tensor, assumed valid. output_name: prefix string to prepend to existing keys. Returns: dict with updated keys and existing values. """ new_outputs = {} for key, val in output_dict.items(): key = self._prefix_key(key, output_name) new_outputs[key] = val return new_outputs def _prefix_key(self, key, output_name): if key.find(output_name) != 0: key = output_name + self._SEPARATOR_CHAR + key return key def _wrap_and_check_metrics(self, metrics): """Handle the saving of metrics. Metrics is either a tuple of (value, update_op), or a dict of such tuples. Here, we separate out the tuples and create a dict with names to tensors. Args: metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Returns: dict of output_names to tensors Raises: ValueError: if the dict key is not a string, or the metric values or ops are not tensors. """ if not isinstance(metrics, dict): metrics = {self.METRICS_NAME: metrics} outputs = {} for key, value in metrics.items(): if isinstance(value, tuple): metric_val, metric_op = value else: # value is a keras.Metrics object metric_val = value.result() assert len(value.updates) == 1 # We expect only one update op. metric_op = value.updates[0] key = self._check_output_key(key, self.METRICS_NAME) key = self._prefix_key(key, self.METRICS_NAME) val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX if not isinstance(metric_val, tf.Tensor): raise ValueError( '{} output value must be a Tensor; got {}.'.format( key, metric_val)) if not (tf.is_tensor(metric_op) or isinstance(metric_op, tf.Operation)): raise ValueError( '{} update_op must be a Tensor or Operation; got {}.'.format( key, metric_op)) # We must wrap any ops (or variables) in a Tensor before export, as the # SignatureDef proto expects tensors only. See b/109740581 metric_op_tensor = metric_op if not isinstance(metric_op, tf.Tensor): with tf.control_dependencies([metric_op]): metric_op_tensor = tf.constant([], name='metric_op_wrapper') outputs[val_name] = metric_val outputs[op_name] = metric_op_tensor return outputs @property def loss(self): return self._loss @property def predictions(self): return self._predictions @property def metrics(self): return self._metrics @abc.abstractmethod def _get_signature_def_fn(self): """Returns a function that produces a SignatureDef given desired outputs.""" pass def as_signature_def(self, receiver_tensors): signature_def_fn = self._get_signature_def_fn() return signature_def_fn( receiver_tensors, self.loss, self.predictions, self.metrics) class TrainOutput(_SupervisedOutput): """Represents the output of a supervised training process. This class generates the appropriate signature def for exporting training output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_train_signature_def class EvalOutput(_SupervisedOutput): """Represents the output of a supervised eval process. This class generates the appropriate signature def for exporting eval output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_eval_signature_def # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_output.py)
15,194
35.007109
83
py
keras
keras-master/keras/saving/saved_model/base_serialization.py
# 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. # ============================================================================== """Helper classes that list&validate all attributes to serialize to SavedModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf import abc from keras.saving.saved_model import json_utils from keras.saving.saved_model import utils class SavedModelSaver(object, metaclass=abc.ABCMeta): """Saver defining the methods and properties used to serialize Keras objects. """ def __init__(self, obj): self.obj = obj @abc.abstractproperty def object_identifier(self): """String stored in object identifier field in the SavedModel proto. Returns: A string with the object identifier, which is used at load time. """ raise NotImplementedError @property def tracking_metadata(self): """String stored in metadata field in the SavedModel proto. Returns: A serialized JSON storing information necessary for recreating this layer. """ # TODO(kathywu): check that serialized JSON can be loaded (e.g., if an # object is in the python property) return json_utils.Encoder().encode(self.python_properties) def list_extra_dependencies_for_serialization(self, serialization_cache): """Lists extra dependencies to serialize to SavedModel. By overriding this method, extra dependencies can be attached to the serialized Layer. For example, this is used to save the list of `variables` and `trainable_variables`, which are python properties in a Layer object, but are represented as a static list in the SavedModel. Args: serialization_cache: A dictionary shared between all objects in the same object graph. This object is passed to both `_list_extra_dependencies_for_serialization` and `_list_functions_for_serialization`. Returns: A dictionary mapping attribute names to trackable objects. The entire list of attributes are listed in the `saved_model._LayerAttributes` class. """ if not utils.should_save_traces(): return {} return self.objects_to_serialize(serialization_cache) def list_functions_for_serialization(self, serialization_cache): """Lists extra functions to serialize to the SavedModel. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to `Function` or `ConcreteFunction`. """ if not utils.should_save_traces(): return {} fns = self.functions_to_serialize(serialization_cache) # The parent AutoTrackable class saves all user-defined tf.functions, and # returns them in _list_functions_for_serialization(). Add these functions # to the dict. fns.update( tf.__internal__.tracking.AutoTrackable._list_functions_for_serialization( # pylint:disable=protected-access self.obj, serialization_cache)) return fns @abc.abstractproperty def python_properties(self): """Returns dictionary of python properties to save in the metadata. This dictionary must be serializable and deserializable to/from JSON. When loading, the items in this dict are used to initialize the object and define attributes in the revived object. """ raise NotImplementedError @abc.abstractmethod def objects_to_serialize(self, serialization_cache): """Returns dictionary of extra checkpointable objects to serialize. See `functions_to_serialize` for an explanation of this function's effects. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to checkpointable objects. """ raise NotImplementedError @abc.abstractmethod def functions_to_serialize(self, serialization_cache): """Returns extra functions to include when serializing a Keras object. Normally, when calling exporting an object to SavedModel, only the functions and objects defined by the user are saved. For example: ``` obj = tf.Module() obj.v = tf.Variable(1.) @tf.function def foo(...): ... obj.foo = foo w = tf.Variable(1.) tf.saved_model.save(obj, 'path/to/saved/model') loaded = tf.saved_model.load('path/to/saved/model') loaded.v # Variable with the same value as obj.v loaded.foo # Equivalent to obj.foo loaded.w # AttributeError ``` Assigning trackable objects to attributes creates a graph, which is used for both checkpointing and SavedModel serialization. When the graph generated from attribute tracking is insufficient, extra objects and functions may be added at serialization time. For example, most models do not have their call function wrapped with a @tf.function decorator. This results in `model.call` not being saved. Since Keras objects should be revivable from the SavedModel format, the call function is added as an extra function to serialize. This function and `objects_to_serialize` is called multiple times when exporting to SavedModel. Please use the cache to avoid generating new functions and objects. A fresh cache is created for each SavedModel export. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to `Function` or `ConcreteFunction`. """ raise NotImplementedError
6,262
33.988827
116
py
keras
keras-master/keras/saving/saved_model/json_utils_test.py
# 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. # ============================================================================== # pylint: disable=protected-access """Tests the JSON encoder and decoder.""" import tensorflow.compat.v2 as tf import enum from keras.saving.saved_model import json_utils class JsonUtilsTest(tf.test.TestCase): def test_encode_decode_tensor_shape(self): metadata = { 'key1': tf.TensorShape(None), 'key2': [tf.TensorShape([None]), tf.TensorShape([3, None, 5])]} string = json_utils.Encoder().encode(metadata) loaded = json_utils.decode(string) self.assertEqual(set(loaded.keys()), {'key1', 'key2'}) self.assertAllEqual(loaded['key1'].rank, None) self.assertAllEqual(loaded['key2'][0].as_list(), [None]) self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5]) def test_encode_decode_tuple(self): metadata = { 'key1': (3, 5), 'key2': [(1, (3, 4)), (1,)]} string = json_utils.Encoder().encode(metadata) loaded = json_utils.decode(string) self.assertEqual(set(loaded.keys()), {'key1', 'key2'}) self.assertAllEqual(loaded['key1'], (3, 5)) self.assertAllEqual(loaded['key2'], [(1, (3, 4)), (1,)]) def test_encode_decode_type_spec(self): spec = tf.TensorSpec((1, 5), tf.float32) string = json_utils.Encoder().encode(spec) loaded = json_utils.decode(string) self.assertEqual(spec, loaded) invalid_type_spec = {'class_name': 'TypeSpec', 'type_spec': 'Invalid Type', 'serialized': None} string = json_utils.Encoder().encode(invalid_type_spec) with self.assertRaisesRegexp(ValueError, 'No TypeSpec has been registered'): loaded = json_utils.decode(string) def test_encode_decode_enum(self): class Enum(enum.Enum): CLASS_A = 'a' CLASS_B = 'b' config = {'key': Enum.CLASS_A, 'key2': Enum.CLASS_B} string = json_utils.Encoder().encode(config) loaded = json_utils.decode(string) self.assertAllEqual({'key': 'a', 'key2': 'b'}, loaded) if __name__ == '__main__': tf.test.main()
2,669
35.575342
80
py
keras
keras-master/keras/saving/saved_model/json_utils.py
# 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. # ============================================================================== """Utils for creating and loading the Layer metadata for SavedModel. These are required to retain the original format of the build input shape, since layers and models may have different build behaviors depending on if the shape is a list, tuple, or TensorShape. For example, Network.build() will create separate inputs if the given input_shape is a list, and will create a single input if the given shape is a tuple. """ import tensorflow.compat.v2 as tf import collections import enum import json import numpy as np import wrapt from tensorflow.python.framework import type_spec class Encoder(json.JSONEncoder): """JSON encoder and decoder that handles TensorShapes and tuples.""" def default(self, obj): # pylint: disable=method-hidden """Encodes objects for types that aren't handled by the default encoder.""" if isinstance(obj, tf.TensorShape): items = obj.as_list() if obj.rank is not None else None return {'class_name': 'TensorShape', 'items': items} return get_json_type(obj) def encode(self, obj): return super(Encoder, self).encode(_encode_tuple(obj)) def _encode_tuple(x): if isinstance(x, tuple): return {'class_name': '__tuple__', 'items': tuple(_encode_tuple(i) for i in x)} elif isinstance(x, list): return [_encode_tuple(i) for i in x] elif isinstance(x, dict): return {key: _encode_tuple(value) for key, value in x.items()} else: return x def decode(json_string): return json.loads(json_string, object_hook=_decode_helper) def _decode_helper(obj): """A decoding helper that is TF-object aware.""" if isinstance(obj, dict) and 'class_name' in obj: if obj['class_name'] == 'TensorShape': return tf.TensorShape(obj['items']) elif obj['class_name'] == 'TypeSpec': return type_spec.lookup(obj['type_spec'])._deserialize( # pylint: disable=protected-access _decode_helper(obj['serialized'])) elif obj['class_name'] == '__tuple__': return tuple(_decode_helper(i) for i in obj['items']) elif obj['class_name'] == '__ellipsis__': return Ellipsis return obj def get_json_type(obj): """Serializes any object to a JSON-serializable structure. Args: obj: the object to serialize Returns: JSON-serializable structure representing `obj`. Raises: TypeError: if `obj` cannot be serialized. """ # if obj is a serializable Keras class instance # e.g. optimizer, layer if hasattr(obj, 'get_config'): return {'class_name': obj.__class__.__name__, 'config': obj.get_config()} # if obj is any numpy type if type(obj).__module__ == np.__name__: if isinstance(obj, np.ndarray): return obj.tolist() else: return obj.item() # misc functions (e.g. loss function) if callable(obj): return obj.__name__ # if obj is a python 'type' if type(obj).__name__ == type.__name__: return obj.__name__ if isinstance(obj, tf.compat.v1.Dimension): return obj.value if isinstance(obj, tf.TensorShape): return obj.as_list() if isinstance(obj, tf.DType): return obj.name if isinstance(obj, collections.abc.Mapping): return dict(obj) if obj is Ellipsis: return {'class_name': '__ellipsis__'} if isinstance(obj, wrapt.ObjectProxy): return obj.__wrapped__ if isinstance(obj, tf.TypeSpec): try: type_spec_name = type_spec.get_name(type(obj)) return {'class_name': 'TypeSpec', 'type_spec': type_spec_name, 'serialized': obj._serialize()} # pylint: disable=protected-access except ValueError: raise ValueError( f'Unable to serialize {obj} to JSON, because the TypeSpec ' f'class {type(obj)} has not been registered.') if isinstance(obj, enum.Enum): return obj.value raise TypeError( f'Unable to serialize {obj} to JSON. Unrecognized type {type(obj)}.')
4,560
30.673611
97
py
keras
keras-master/keras/saving/saved_model/constants.py
# 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. # ============================================================================== """Constants for Keras SavedModel serialization.""" # Namespace used to store all attributes added during serialization. # e.g. the list of layers can be accessed using `loaded.keras_api.layers`, in an # object loaded from `tf.saved_model.load()`. KERAS_ATTR = 'keras_api' # Keys for the serialization cache. # Maps to the keras serialization dict {Layer --> SerializedAttributes object} KERAS_CACHE_KEY = 'keras_serialized_attributes' # Name of Keras metadata file stored in the SavedModel. SAVED_METADATA_PATH = 'keras_metadata.pb' # Names of SavedObject Keras identifiers. INPUT_LAYER_IDENTIFIER = '_tf_keras_input_layer' LAYER_IDENTIFIER = '_tf_keras_layer' METRIC_IDENTIFIER = '_tf_keras_metric' MODEL_IDENTIFIER = '_tf_keras_model' NETWORK_IDENTIFIER = '_tf_keras_network' RNN_LAYER_IDENTIFIER = '_tf_keras_rnn_layer' SEQUENTIAL_IDENTIFIER = '_tf_keras_sequential' KERAS_OBJECT_IDENTIFIERS = ( INPUT_LAYER_IDENTIFIER, LAYER_IDENTIFIER, METRIC_IDENTIFIER, MODEL_IDENTIFIER, NETWORK_IDENTIFIER, RNN_LAYER_IDENTIFIER, SEQUENTIAL_IDENTIFIER, )
1,769
35.875
80
py
keras
keras-master/keras/saving/saved_model/revive_test.py
# 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. # ============================================================================== # pylint: disable=protected-access """Tests reviving models from config and SavedModel. These tests ensure that a model revived from a combination of config and SavedModel have the expected structure. """ import tensorflow.compat.v2 as tf # TODO(kathywu): Move relevant tests from saved_model_test to import shutil from absl.testing import parameterized import numpy as np import keras from keras import backend from keras import keras_parameterized from keras import testing_utils from keras.saving.saved_model import load as keras_load from keras.utils import generic_utils class SubclassedModelNoConfig(keras.Model): def __init__(self, a, b): super(SubclassedModelNoConfig, self).__init__() self.a = a self.b = b self.shared = CustomLayerNoConfig(a, b) self.all_layers = [] def build(self, input_shape): self.all_layers.extend([ self.shared, CustomLayerWithConfig(self.a + 1, self.b + 2), CustomLayerNoConfig(self.a + 3, self.b + 4), keras.Sequential([ # TODO(b/145029112): Bug with losses when there are shared layers. # self.shared, <-- Enable when bug is fixed. CustomLayerNoConfig(self.a + 5, self.b + 6)])]) super(SubclassedModelNoConfig, self).build(input_shape) def call(self, inputs): x = inputs for layer in self.all_layers: x = layer(x) return x class SparseDense(keras.layers.Dense): def call(self, inputs): input_shape = tf.stack( (tf.reduce_prod(tf.shape(inputs)[:-1]), self.kernel.shape[0])) output_shape = tf.concat( (tf.shape(inputs)[:-1], [self.kernel.shape[1]]), -1) x = tf.sparse.reshape(inputs, input_shape) return tf.reshape( self.activation( tf.sparse.sparse_dense_matmul(x, self.kernel) + self.bias), output_shape) class SubclassedSparseModelNoConfig(keras.Model): def __init__(self, a, b): super(SubclassedSparseModelNoConfig, self).__init__() self.a = a self.shared = CustomLayerNoConfig(a, b) self.all_layers = [SparseDense(4)] def call(self, inputs): x = inputs for layer in self.all_layers: x = layer(x) return self.shared(x + self.a) class SubclassedModelWithConfig(SubclassedModelNoConfig): def get_config(self): return {'a': self.a, 'b': self.b} @classmethod def from_config(cls, config): return cls(**config) class CustomLayerNoConfig(keras.layers.Layer): def __init__(self, a, b, name=None): super(CustomLayerNoConfig, self).__init__(name=name) self.a = tf.Variable(a, name='a') self.b = b def a_regularizer(): return self.a * 2 self.add_loss(a_regularizer) self.sum_metric = keras.metrics.Sum(name='inputs_sum') self.unused_metric = keras.metrics.Sum(name='not_added_to_metrics') def build(self, input_shape): self.c = tf.Variable( tf.constant(1.0, shape=input_shape[1:]), name=self.name+'_c') def call(self, inputs): self.add_loss(tf.reduce_sum(inputs), inputs=inputs) self.add_metric(self.sum_metric(inputs)) self.add_metric(inputs, aggregation='mean', name='mean') return inputs + self.c class CustomLayerWithConfig(CustomLayerNoConfig): def get_config(self): return {'a': backend.get_value(self.a), 'b': self.b, 'name': self.name} class CustomNetworkDefaultConfig(keras.Model): def __init__(self, num_classes, name=None): inputs = keras.Input((2, 3), name='inputs') x = keras.layers.Flatten(name='flatten')(inputs) y = keras.layers.Dense(num_classes, name='outputs')(x) super(CustomNetworkDefaultConfig, self).__init__(inputs, y, name=name) class CustomNetworkWithConfig(CustomNetworkDefaultConfig): def __init__(self, num_classes, name=None): super(CustomNetworkWithConfig, self).__init__(num_classes, name=name) self._config_dict = dict(num_classes=num_classes) def get_config(self): return self._config_dict @classmethod def from_config(cls, config): return cls(config['num_classes'], name=config.get('name')) class CustomNetworkWithConfigName(CustomNetworkWithConfig): def __init__(self, num_classes, name=None): super(CustomNetworkWithConfigName, self).__init__(num_classes, name=name) self._config_dict['name'] = self.name class UnregisteredCustomSequentialModel(keras.Sequential): # This class is *not* registered in the CustomObjectScope. def __init__(self, **kwargs): super(UnregisteredCustomSequentialModel, self).__init__(**kwargs) self.add(keras.layers.InputLayer(input_shape=(2, 3))) class ReviveTestBase(keras_parameterized.TestCase): def setUp(self): super(ReviveTestBase, self).setUp() self.path = self.get_temp_dir() self.addCleanup(shutil.rmtree, self.path, ignore_errors=True) def _assert_revived_correctness(self, model, revived): self.assertAllEqual(model.input_names, revived.input_names) self.assertAllEqual(model.output_names, revived.output_names) if model.inputs is not None: self.assertTrue( all([ i.shape.as_list() == r.shape.as_list() and i.dtype == r.dtype for (i, r) in zip(model.inputs, revived.inputs) ])) self.assertTrue( all([ i.shape.as_list() == r.shape.as_list() and i.dtype == r.dtype for (i, r) in zip(model.outputs, revived.outputs) ])) self.assertAllClose(self.evaluate(model.weights), self.evaluate(revived.weights)) input_arr = tf.constant( np.random.random((2, 2, 3)).astype(np.float32)) if isinstance(revived.save_spec()[0][0], tf.SparseTensorSpec): input_arr = tf.sparse.from_dense(input_arr) self.assertAllClose(model(input_arr), revived(input_arr)) self.assertAllClose(sum(model.losses), sum(revived.losses)) self.assertAllClose(len(model.losses), len(revived.losses)) self.assertEqual(len(model.metrics), len(revived.metrics)) # TODO(b/150403085): Investigate why the metric order changes when running # this test in tf-nightly. self.assertAllClose(sorted([m.result() for m in model.metrics]), sorted([m.result() for m in revived.metrics])) model_layers = {layer.name: layer for layer in model.layers} revived_layers = {layer.name: layer for layer in revived.layers} self.assertAllEqual(model_layers.keys(), revived_layers.keys()) for name in model_layers: model_layer = model_layers[name] revived_layer = revived_layers[name] self.assertEqual(model_layer.name, revived_layer.name) self.assertEqual(model_layer.dtype, revived_layer.dtype) self.assertEqual(model_layer.trainable, revived_layer.trainable) if 'WithConfig' in type(model_layer).__name__: self.assertEqual(type(model_layer), type(revived_layer)) else: # When loading layers from SavedModel, a new class is dynamically # created with the same name. self.assertEqual(type(model_layer).__name__, type(revived_layer).__name__) # These tests take a while to run, so each should run in a separate shard # (putting them in the same TestCase resolves this). class TestBigModelRevive(ReviveTestBase): @keras_parameterized.run_with_all_model_types def test_revive(self): input_shape = None if testing_utils.get_model_type() == 'functional': input_shape = (2, 3) layer_with_config = CustomLayerWithConfig(1., 2) layer_without_config = CustomLayerNoConfig(3., 4) subclassed_with_config = SubclassedModelWithConfig(4., 6.) subclassed_without_config = SubclassedModelNoConfig(7., 8.) inputs = keras.Input((2, 3)) x = CustomLayerWithConfig(1., 2)(inputs) x = CustomLayerNoConfig(3., 4)(x) x = SubclassedModelWithConfig(4., 6.)(x) x = SubclassedModelNoConfig(7., 8.)(x) inner_model_functional = keras.Model(inputs, x) inner_model_sequential = keras.Sequential( [CustomLayerWithConfig(1., 2), CustomLayerNoConfig(3., 4), SubclassedModelWithConfig(4., 6.), SubclassedModelNoConfig(7., 8.)]) class SubclassedModel(keras.Model): def __init__(self): super(SubclassedModel, self).__init__() self.all_layers = [CustomLayerWithConfig(1., 2), CustomLayerNoConfig(3., 4), SubclassedModelWithConfig(4., 6.), SubclassedModelNoConfig(7., 8.)] def call(self, inputs): x = inputs for layer in self.all_layers: x = layer(x) return x inner_model_subclassed = SubclassedModel() layers = [layer_with_config, layer_without_config, subclassed_with_config, subclassed_without_config, inner_model_functional, inner_model_sequential, inner_model_subclassed] model = testing_utils.get_model_from_layers( layers, input_shape=input_shape) # Run data through the Model to create save spec and weights. model.predict(np.ones((10, 2, 3)), batch_size=10) # Test that the correct checkpointed values are loaded, whether the layer is # created from the config or SavedModel. layer_with_config.c.assign(2 * layer_with_config.c) layer_without_config.c.assign(3 * layer_without_config.c) model.save(self.path, save_format='tf') revived = keras_load.load(self.path) self._assert_revived_correctness(model, revived) class TestModelRevive(ReviveTestBase): def test_revive_subclassed_with_nested_model(self): model = SubclassedModelNoConfig(1., 2.) # Run data through the Model to create save spec and weights. model.predict(np.ones((10, 2, 3)), batch_size=10) model.save(self.path, save_format='tf') revived = keras_load.load(self.path) self._assert_revived_correctness(model, revived) def test_revive_subclassed_with_sparse_model(self): model = SubclassedSparseModelNoConfig(1., 2.) # Run data through the Model to create save spec and weights. x = tf.sparse.from_dense(np.ones((10, 2, 3), dtype=np.float32)) model.predict(x, batch_size=10) model.save(self.path, save_format='tf') revived = keras_load.load(self.path) self._assert_revived_correctness(model, revived) def test_revive_unregistered_sequential(self): model = UnregisteredCustomSequentialModel() x = np.random.random((2, 2, 3)).astype(np.float32) model(x) model.save(self.path, save_format='tf') revived = keras_load.load(self.path) self._assert_revived_correctness(model, revived) def test_revive_sequential_inputs(self): model = keras.models.Sequential([ keras.Input((None,), dtype=tf.string), keras.layers.Lambda(tf.strings.lower) ]) model.save(self.path, save_format='tf') revived = keras_load.load(self.path) revived_layers = list( revived._flatten_layers(include_self=False, recursive=False)) self.assertEqual(tf.string, revived_layers[0].dtype) @parameterized.named_parameters( ('default_config', CustomNetworkDefaultConfig), ('with_config', CustomNetworkWithConfig), ('with_config_name', CustomNetworkWithConfigName)) def test_revive_network(self, model_cls): model = model_cls(8) model.save(self.path, include_optimizer=False, save_format='tf') revived = keras_load.load(self.path, compile=False) self._assert_revived_correctness(model, revived) def test_load_compiled_metrics(self): model = testing_utils.get_small_sequential_mlp(1, 3) # Compile with dense categorical accuracy model.compile('rmsprop', 'mse', 'acc') x = np.random.random((5, 10)).astype(np.float32) y_true = np.random.random((5, 3)).astype(np.float32) model.train_on_batch(x, y_true) model.save(self.path, include_optimizer=True, save_format='tf') revived = keras_load.load(self.path, compile=True) self.assertAllClose(model.test_on_batch(x, y_true), revived.test_on_batch(x, y_true)) # Compile with sparse categorical accuracy model.compile('rmsprop', 'mse', 'acc') y_true = np.random.randint(0, 3, (5, 1)).astype(np.float32) model.train_on_batch(x, y_true) model.save(self.path, include_optimizer=True, save_format='tf') revived = keras_load.load(self.path, compile=True) self.assertAllClose(model.test_on_batch(x, y_true), revived.test_on_batch(x, y_true)) def test_revived_model_has_save_spec(self): model = SubclassedModelWithConfig(2, 3) model.predict(np.random.random((5, 10)).astype(np.float32)) model.save(self.path, save_format='tf') revived = keras_load.load(self.path, compile=True) self.assertAllEqual( model._get_save_spec(dynamic_batch=False), revived._get_save_spec(dynamic_batch=False)) if __name__ == '__main__': tf.compat.v1.enable_eager_execution() with generic_utils.CustomObjectScope({ 'CustomLayerWithConfig': CustomLayerWithConfig, 'CustomNetworkWithConfig': CustomNetworkWithConfig, 'CustomNetworkWithConfigName': CustomNetworkWithConfigName, 'SubclassedModelWithConfig': SubclassedModelWithConfig }): tf.test.main()
13,977
34.749361
80
py
keras
keras-master/keras/saving/saved_model/layer_serialization.py
# 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. # ============================================================================== """Classes and functions implementing Layer SavedModel serialization.""" from keras.mixed_precision import policy from keras.saving.saved_model import base_serialization from keras.saving.saved_model import constants from keras.saving.saved_model import save_impl from keras.saving.saved_model import serialized_attributes from keras.utils import generic_utils import tensorflow.compat.v2 as tf class LayerSavedModelSaver(base_serialization.SavedModelSaver): """Implements Layer SavedModel serialization.""" @property def object_identifier(self): return constants.LAYER_IDENTIFIER @property def python_properties(self): # TODO(kathywu): Add python property validator return self._python_properties_internal() def _python_properties_internal(self): """Returns dictionary of all python properties.""" # TODO(kathywu): Add support for metrics serialization. # TODO(kathywu): Synchronize with the keras spec (go/keras-json-spec) once # the python config serialization has caught up. metadata = dict( name=self.obj.name, trainable=self.obj.trainable, expects_training_arg=self.obj._expects_training_arg, # pylint: disable=protected-access dtype=policy.serialize(self.obj._dtype_policy), # pylint: disable=protected-access batch_input_shape=getattr(self.obj, '_batch_input_shape', None), stateful=self.obj.stateful, must_restore_from_config=self.obj._must_restore_from_config, # pylint: disable=protected-access ) metadata.update(get_serialized(self.obj)) if self.obj.input_spec is not None: # Layer's input_spec has already been type-checked in the property setter. metadata['input_spec'] = tf.nest.map_structure( lambda x: generic_utils.serialize_keras_object(x) if x else None, self.obj.input_spec) if (self.obj.activity_regularizer is not None and hasattr(self.obj.activity_regularizer, 'get_config')): metadata['activity_regularizer'] = generic_utils.serialize_keras_object( self.obj.activity_regularizer) if self.obj._build_input_shape is not None: # pylint: disable=protected-access metadata['build_input_shape'] = self.obj._build_input_shape # pylint: disable=protected-access return metadata def objects_to_serialize(self, serialization_cache): return (self._get_serialized_attributes( serialization_cache).objects_to_serialize) def functions_to_serialize(self, serialization_cache): return (self._get_serialized_attributes( serialization_cache).functions_to_serialize) def _get_serialized_attributes(self, serialization_cache): """Generates or retrieves serialized attributes from cache.""" keras_cache = serialization_cache.setdefault(constants.KERAS_CACHE_KEY, {}) if self.obj in keras_cache: return keras_cache[self.obj] serialized_attr = keras_cache[self.obj] = ( serialized_attributes.SerializedAttributes.new(self.obj)) if (save_impl.should_skip_serialization(self.obj) or self.obj._must_restore_from_config): # pylint: disable=protected-access return serialized_attr object_dict, function_dict = self._get_serialized_attributes_internal( serialization_cache) serialized_attr.set_and_validate_objects(object_dict) serialized_attr.set_and_validate_functions(function_dict) return serialized_attr def _get_serialized_attributes_internal(self, serialization_cache): """Returns dictionary of serialized attributes.""" objects = save_impl.wrap_layer_objects(self.obj, serialization_cache) functions = save_impl.wrap_layer_functions(self.obj, serialization_cache) # Attribute validator requires that the default save signature is added to # function dict, even if the value is None. functions['_default_save_signature'] = None return objects, functions # TODO(kathywu): Move serialization utils (and related utils from # generic_utils.py) to a separate file. def get_serialized(obj): with generic_utils.skip_failed_serialization(): # Store the config dictionary, which may be used when reviving the object. # When loading, the program will attempt to revive the object from config, # and if that fails, the object will be revived from the SavedModel. return generic_utils.serialize_keras_object(obj) class InputLayerSavedModelSaver(base_serialization.SavedModelSaver): """InputLayer serialization.""" @property def object_identifier(self): return constants.INPUT_LAYER_IDENTIFIER @property def python_properties(self): return dict( class_name=type(self.obj).__name__, name=self.obj.name, dtype=self.obj.dtype, sparse=self.obj.sparse, ragged=self.obj.ragged, batch_input_shape=self.obj._batch_input_shape, # pylint: disable=protected-access config=self.obj.get_config()) def objects_to_serialize(self, serialization_cache): return {} def functions_to_serialize(self, serialization_cache): return {} class RNNSavedModelSaver(LayerSavedModelSaver): """RNN layer serialization.""" @property def object_identifier(self): return constants.RNN_LAYER_IDENTIFIER def _get_serialized_attributes_internal(self, serialization_cache): objects, functions = ( super(RNNSavedModelSaver, self)._get_serialized_attributes_internal( serialization_cache)) states = tf.__internal__.tracking.wrap(self.obj.states) # SaveModel require all the objects to be Trackable when saving. # If the states is still a tuple after wrap_or_unwrap, it means it doesn't # contain any trackable item within it, eg empty tuple or (None, None) for # stateless ConvLSTM2D. We convert them to list so that wrap_or_unwrap can # make it a Trackable again for saving. When loaded, ConvLSTM2D is # able to handle the tuple/list conversion. if isinstance(states, tuple): states = tf.__internal__.tracking.wrap(list(states)) objects['states'] = states return objects, functions class IndexLookupLayerSavedModelSaver(LayerSavedModelSaver): """Index lookup layer serialization.""" @property def python_properties(self): # TODO(kathywu): Add python property validator metadata = self._python_properties_internal() # Clear the vocabulary from the config during saving. The vocab will be # saved as part of the lookup table directly, which correctly handle saving # vocabulary files as a SavedModel asset. metadata['config']['vocabulary'] = None # Keep a separate config property to track that a vocabulary was passed in # and not adapted. metadata['config']['has_input_vocabulary'] = self.obj._has_input_vocabulary # pylint: disable=protected-access return metadata
7,495
40.644444
115
py
keras
keras-master/keras/saving/saved_model/save_impl.py
# 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 serialization. TODO (kathywu): Move to layer_serialization.py. Some model-specific logic should go to model_serialization.py. """ import functools import threading import weakref from keras import backend as K from keras.engine import base_layer_utils from keras.engine import input_spec from keras.mixed_precision import autocast_variable from keras.saving import saving_utils from keras.saving.saved_model import constants from keras.saving.saved_model import load as keras_load from keras.saving.saved_model import serialized_attributes from keras.saving.saved_model import utils from keras.utils import tf_contextlib from keras.utils import tf_inspect from keras.utils import tf_utils from keras.utils import version_utils from keras.utils.generic_utils import LazyLoader import tensorflow.compat.v1.logging as logging import tensorflow.compat.v2 as tf # 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. # pylint:disable=g-inconsistent-quotes base_layer = LazyLoader( "base_layer", globals(), "keras.engine.base_layer") metrics = LazyLoader("metrics", globals(), "keras.metrics") input_layer = LazyLoader( "input_layer", globals(), "keras.engine.input_layer") training_lib = LazyLoader( "training_lib", globals(), "keras.engine.training") sequential_lib = LazyLoader( "sequential_lib", globals(), "keras.engine.sequential") # pylint:enable=g-inconsistent-quotes def should_skip_serialization(layer): """Skip serializing extra objects and functions if layer inputs aren't set.""" saved_model_input_spec_set = (isinstance(layer, training_lib.Model) and layer._saved_model_inputs_spec is not None) # pylint: disable=protected-access if not layer.built and not saved_model_input_spec_set: logging.warning('Skipping full serialization of Keras layer {}, because ' 'it is not built.'.format(layer)) return True return False def wrap_layer_objects(layer, serialization_cache): """Returns extra trackable objects to attach to the serialized layer. Args: layer: Keras Layer object. serialization_cache: Dictionary shared between all objects during serialization. Returns: A dictionary containing all checkpointable objects from a SerializedAttributes object. See LayerAttributes and ModelAttributes for entire list of objects """ # Wrap all regularization losses as tf.functions. # First, generate list of all regularization losses in this layer and # sublayers. all_losses = layer._callable_losses[:] # pylint: disable=protected-access for child_layer in utils.list_all_layers(layer): all_losses.extend(child_layer._callable_losses) # pylint: disable=protected-access # Next, wrap all loss functions as tf.functions. Use the serialization cache # to store already-wrapped functions. keras_loss_cache = serialization_cache.setdefault('keras_losses', {}) wrapped_loss_functions = [] for loss_fn in all_losses: if loss_fn in keras_loss_cache: wrapped_loss_functions.append(keras_loss_cache[loss_fn]) else: wrapped_loss = _wrap_unconditional_loss(loss_fn, len(keras_loss_cache)) keras_loss_cache[loss_fn] = wrapped_loss wrapped_loss_functions.append(wrapped_loss) wrapped_layer_losses = [keras_loss_cache[fn] for fn in layer._callable_losses[:]] # pylint: disable=protected-access layer_metrics = tf.__internal__.tracking.wrap( {m.name: m for m in layer._metrics}) # pylint: disable=protected-access return dict( variables=tf.__internal__.tracking.wrap(layer.variables), trainable_variables=tf.__internal__.tracking.wrap( layer.trainable_variables), non_trainable_variables=tf.__internal__.tracking.wrap( layer.non_trainable_variables), layers=tf.__internal__.tracking.wrap(utils.list_all_layers(layer)), metrics=tf.__internal__.tracking.wrap(layer.metrics), regularization_losses=tf.__internal__.tracking.wrap( wrapped_loss_functions), layer_regularization_losses=tf.__internal__.tracking.wrap( wrapped_layer_losses), layer_metrics=layer_metrics) # pylint: disable=protected-access def wrap_layer_functions(layer, serialization_cache): """Returns dict of wrapped layer call function and losses in tf.functions. Args: layer: Keras Layer object. serialization_cache: Dictionary shared between all objects during serialization. Returns: A dictionary containing all keras tf.functions to serialize. See LayerAttributes and ModelAttributes for the list of all attributes. """ # Since Sequential models may be modified in place using model.add() or # model.pop(), don't use saved functions. if (isinstance(layer, keras_load.RevivedLayer) and not isinstance(layer, sequential_lib.Sequential)): return {fn_name: getattr(layer.keras_api, fn_name, None) for fn_name in serialized_attributes.LayerAttributes.all_functions} # Reset the losses of the layer and its children. The call function in each # child layer is replaced with tf.functions. original_fns = _replace_child_layer_functions(layer, serialization_cache) original_losses = _reset_layer_losses(layer) # Wrap all the layer call and activity regularizer functions. # Use LayerCallCollection to ensure that all layer call functions (__call__, # call with losses) are traced with the same inputs. call_collection = LayerCallCollection(layer) call_fn_with_losses = call_collection.add_function( _wrap_call_and_conditional_losses(layer), '{}_layer_call_and_return_conditional_losses'.format(layer.name), # If any of this layer's child layers use the training arg, the traced # call functions of this layer will have a training keyword argument. If # the original layer does not expect the training arg, then it will have # to be removed (by setting `match_layer_training_arg`). match_layer_training_arg=True) call_fn = call_collection.add_function( _extract_outputs_from_fn(layer, call_fn_with_losses), '{}_layer_call_fn'.format(layer.name), # Since `call_fn` wraps call_fn_with_losses and not the original call # function, `match_layer_training_arg` should be set to False. match_layer_training_arg=False) fns = {'call_and_return_conditional_losses': call_fn_with_losses, '__call__': call_fn} if layer._activity_regularizer is not None: # pylint: disable=protected-access fns['activity_regularizer_fn'] = _wrap_activity_regularizer(layer) fns['call_and_return_all_conditional_losses'] = ( call_collection.add_function( _append_activity_regularizer_loss( layer, call_fn_with_losses, fns['activity_regularizer_fn']), '{}_layer_call_and_return_all_conditional_losses'.format( layer.name), match_layer_training_arg=False)) else: fns['activity_regularizer_fn'] = None fns['call_and_return_all_conditional_losses'] = call_fn_with_losses # Manually trigger traces before restoring the overwritten functions. The # functions are traced within the layer call context to ensure that layer # functions (e.g. add_loss) behave as though running in graph mode. with tracing_scope(): call_collection.trace_with_input_signature() with base_layer_utils.call_context().enter( layer, inputs=None, build_graph=True, training=None, saving=True): for fn in fns.values(): if fn is not None and not isinstance(fn, LayerCall): fn.get_concrete_function() # Restore overwritten functions and losses _restore_child_layer_functions(original_fns) _restore_layer_losses(original_losses) return fns def default_save_signature(layer): original_losses = _reset_layer_losses(layer) fn = saving_utils.trace_model_call(layer) _restore_layer_losses(original_losses) return fn def _replace_child_layer_functions(layer, serialization_cache): """Replaces functions in the children layers with wrapped tf.functions. This step allows functions from parent layers to reference the wrapped functions from their children layers instead of retracing the ops. This function also resets all losses stored in the layer. These are stored in the returned dictionary. Use `_restore_child_layer_functions` to restore the original attributes. Args: layer: Keras Layer object. serialization_cache: Dictionary shared between all objects during serialization. Returns: Dictionary mapping layer objects -> original functions and losses: { Child layer 1: { 'losses': Original losses, 'call': Original call function '_activity_regularizer': Original activity regularizer}, Child layer 2: ... } """ # pylint: disable=protected-access original_fns = {} def replace_layer_functions(child_layer, serialized_fns): """Replaces layer call and activity regularizer with wrapped functions.""" original_fns[child_layer] = { 'call': child_layer.call, '_activity_regularizer': child_layer._activity_regularizer } with utils.no_automatic_dependency_tracking_scope(child_layer): try: child_layer._activity_regularizer = serialized_fns.get( 'activity_regularizer_fn') except AttributeError: # Some layers have an unsettable activity regularizer. pass child_layer.call = utils.use_wrapped_call( child_layer, serialized_fns['call_and_return_conditional_losses'], default_training_value=False) def replace_metric_functions(child_layer, serialized_fns): """Replaces metric functions with wrapped functions.""" original_fns[child_layer] = { '__call__': child_layer.__call__, 'result': child_layer.result, 'update_state': child_layer.update_state } with utils.no_automatic_dependency_tracking_scope(child_layer): child_layer.__call__ = serialized_fns['__call__'] child_layer.result = serialized_fns['result'] child_layer.update_state = serialized_fns['update_state'] for child_layer in utils.list_all_layers(layer): if isinstance(child_layer, input_layer.InputLayer): continue if child_layer not in serialization_cache[constants.KERAS_CACHE_KEY]: serialized_functions = ( child_layer._trackable_saved_model_saver._get_serialized_attributes( serialization_cache).functions) else: serialized_functions = ( serialization_cache[constants.KERAS_CACHE_KEY][child_layer].functions) if not serialized_functions: # This indicates either: # - circular dependency, which means the current layer's functions # should be wrapped first. # - Child layer's inputs are not defined, so its functions have not been # wrapped. In this case, no replacement is necessary so move on to the # next child. continue if isinstance(child_layer, metrics.Metric): replace_metric_functions(child_layer, serialized_functions) else: replace_layer_functions(child_layer, serialized_functions) return original_fns # pylint: enable=protected-access def _restore_child_layer_functions(original_fns): """Restores attributes replaced with `_replace_child_layer_functions`.""" for child_layer, fns in original_fns.items(): with utils.no_automatic_dependency_tracking_scope(child_layer): for fn_name, fn in fns.items(): try: setattr(child_layer, fn_name, fn) # pylint: disable=protected-access except AttributeError: pass # In the case of _activity_regularizer, setting the attribute # may be disallowed. # pylint: disable=protected-access def _reset_layer_losses(parent_layer): """Resets losses of layer and its sublayers, and returns original losses.""" losses_dict = {} for layer in utils.list_all_layers_and_sublayers(parent_layer): losses_dict[layer] = {'losses': layer._losses[:], 'eager_losses': layer._eager_losses[:]} with utils.no_automatic_dependency_tracking_scope(layer): layer._losses = [] layer._eager_losses = [] return losses_dict def _restore_layer_losses(losses_dict): for layer in losses_dict: with utils.no_automatic_dependency_tracking_scope(layer): layer._losses = losses_dict[layer]['losses'] layer._eager_losses = losses_dict[layer]['eager_losses'] # pylint: enable=protected-access class LayerTracingContext(threading.local): def __init__(self): super(LayerTracingContext, self).__init__() self.enable_call_tracing = False self.trace_queue = [] _thread_local_data = LayerTracingContext() @tf_contextlib.contextmanager def tracing_scope(): """Enables tracing scope.""" # This enables the LayerCallCollection's tracing mechanism to trace all call # functions in the collection. previous_value = _thread_local_data.enable_call_tracing previous_queue = _thread_local_data.trace_queue try: _thread_local_data.enable_call_tracing = True _thread_local_data.trace_queue = [] yield finally: # Run traces from the queue. while _thread_local_data.trace_queue: fn, args, kwargs, training = _thread_local_data.trace_queue.pop() if training is not None: with K.deprecated_internal_learning_phase_scope(training): fn.get_concrete_function(*args, **kwargs) else: fn.get_concrete_function(*args, **kwargs) _thread_local_data.trace_queue = previous_queue _thread_local_data.enable_call_tracing = previous_value def add_trace_to_queue(fn, args, kwargs, training=None): if tracing_enabled(): _thread_local_data.trace_queue.append( (fn, args[:], kwargs.copy(), training)) def tracing_enabled(): """Whether to add extra traces to the queue.""" return _thread_local_data.enable_call_tracing class LayerCallCollection: """Groups wrapped layer call functions. This is used to ensure that all layer call functions are traced with the same inputs- - call - call_and_return_conditional_losses - call_and_return_all_conditional_losses """ def __init__(self, layer): self.layer = layer self.layer_call_method = _get_layer_call_method(layer) self._expects_training_arg = utils.layer_uses_training_bool(layer) self._training_arg_index = utils.get_training_arg_index( self.layer_call_method) self._layer_inputs = self._get_layer_inputs(layer) self._functions = weakref.WeakValueDictionary() # Get the input argument name from the args. arg_spec = tf_inspect.getfullargspec(self.layer_call_method) args = arg_spec.args if tf_inspect.ismethod(self.layer_call_method): args = args[1:] self._input_arg_name = args[0] if args else 'inputs' def _get_layer_inputs(self, layer): """Inspects layer object and returns the inferred input signature. Args: layer: Layer object. Returns: List of possibly nested TensorSpecs of the layer call function inputs in the form of `(args, kwargs)` """ if (isinstance(layer.call, tf.__internal__.function.Function) and layer.call.input_signature is not None): return layer.call.input_signature, {} elif isinstance(layer, training_lib.Model): return saving_utils.model_call_inputs(layer) elif (layer.input_spec is not None and layer._use_input_spec_as_call_signature): # pylint: disable=protected-access def to_tensor_spec_or_none(x): spec = input_spec.to_tensor_spec(x, layer._compute_dtype) # pylint: disable=protected-access # If the shape is too general (e.g. multiple dimensions are allowed), # return None so that separate functions can be generated for each # inferred input signature. # TODO(b/134962016): currently partial signatures are not supported. if spec.shape == tf.TensorShape(None): return None, None return spec input_signature = [tf.nest.map_structure( to_tensor_spec_or_none, layer.input_spec)] return input_signature, {} else: return None, None def add_trace(self, *args, **kwargs): """Traces all functions with the same args and kwargs. Args: *args: Positional args passed to the original function. **kwargs: Keyword args passed to the original function. """ args = list(args) kwargs = kwargs.copy() for fn in self._functions.values(): # TODO(kathywu): Replace arguments with broader shapes defined in the # input signature. if self._expects_training_arg: def trace_with_training(value, fn=fn): utils.set_training_arg(value, self._training_arg_index, args, kwargs) add_trace_to_queue(fn, args, kwargs, value) trace_with_training(True) trace_with_training(False) else: add_trace_to_queue(fn, args, kwargs) def training_arg_was_passed(self, args, kwargs): if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access return (utils.get_training_arg(self._training_arg_index, args, kwargs) is not None) else: return self.layer._call_arg_was_passed( # pylint: disable=protected-access 'training', args, kwargs, inputs_in_args=True) def get_training_arg_value(self, args, kwargs): if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access return utils.get_training_arg(self._training_arg_index, args, kwargs) else: return self.layer._get_call_arg_value( # pylint: disable=protected-access 'training', args, kwargs, inputs_in_args=True) def get_input_arg_value(self, args, kwargs): return self.layer._get_call_arg_value( # pylint: disable=protected-access self._input_arg_name, args, kwargs, inputs_in_args=True) def _maybe_wrap_with_training_arg(self, call_fn, match_layer_training_arg): """Wraps call function with added training argument if necessary.""" if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access # Add training arg to wrapper function. arg_spec = tf_inspect.getfullargspec(call_fn) args = arg_spec.args + ['training'] defaults = list(arg_spec.defaults or []) defaults.append(False) new_arg_spec = tf_inspect.FullArgSpec( args=args, varargs=arg_spec.varargs, varkw=arg_spec.varkw, defaults=defaults, kwonlyargs=arg_spec.kwonlyargs, kwonlydefaults=arg_spec.kwonlydefaults, annotations=arg_spec.annotations) # Set new training arg index self._training_arg_index = len(args) - 1 if tf_inspect.ismethod(call_fn): self._training_arg_index -= 1 def wrap_with_training_arg(*args, **kwargs): if match_layer_training_arg: # Remove the training value, since the original call_fn does not # expect a training arg. Instead, the training value will be # propagated using the call context created in LayerCall. args = list(args) kwargs = kwargs.copy() utils.remove_training_arg(self._training_arg_index, args, kwargs) return call_fn(*args, **kwargs) return tf.__internal__.decorator.make_decorator( target=call_fn, decorator_func=wrap_with_training_arg, decorator_argspec=new_arg_spec) return call_fn def add_function(self, call_fn, name, match_layer_training_arg): """Adds a layer call function to the collection. Args: call_fn: a python function name: Name of call function match_layer_training_arg: If True, removes the `training` from the function arguments when calling `call_fn`. Returns: LayerCall (tf.function) """ fn = LayerCall( self, self._maybe_wrap_with_training_arg(call_fn, match_layer_training_arg), name) self._functions[name] = fn.wrapped_call return fn def trace_with_input_signature(self): """Trace with the layer/models inferred input signature if possible.""" if None not in tf.nest.flatten(self._layer_inputs): # Manually add traces for layers that have keyword arguments and have # a fully defined input signature. args, kwargs = self._layer_inputs self.add_trace(*args, **kwargs) def _filtered_inputs(inputs): return list(filter(tf_utils.is_tensor_or_variable, tf.nest.flatten(inputs))) def layer_call_wrapper(call_collection, method, name): """Ensures layer losses are kept the same, and runs method in call context.""" # Create wrapper that deals with losses and call context. def wrapper(*args, **kwargs): """Calls method within call context.""" layer = call_collection.layer training = None inputs = _filtered_inputs([args, kwargs]) # pylint: disable=protected-access if (args or kwargs) and call_collection.training_arg_was_passed( args, kwargs): training = call_collection.get_training_arg_value(args, kwargs) # pylint: enable=protected-access original_losses = _reset_layer_losses(layer) with base_layer_utils.call_context().enter( layer, inputs=inputs, build_graph=False, training=training, saving=True): with autocast_variable.enable_auto_cast_variables( layer._compute_dtype_object): # pylint: disable=protected-access ret = method(*args, **kwargs) _restore_layer_losses(original_losses) return ret # Rename to `name`, since tf.function doesn't have a name argument. Without # this, all functions returned by this method will be named "call", which # would be a nightmare to debug. fn = tf.__internal__.decorator.make_decorator( target=method, decorator_func=wrapper) fn.__name__ = name return fn class LayerCall: """Function that triggers traces of other functions in the same collection.""" def __init__(self, call_collection, call_fn, name): """Initializes a LayerCall object. Args: call_collection: a LayerCallCollection, which contains the other layer call functions (e.g. call_with_conditional_losses, call). These functions should be traced with the same arguments. call_fn: A call function. name: Name of the call function. """ self.call_collection = call_collection self.wrapped_call = tf.function( layer_call_wrapper(call_collection, call_fn, name)) self.original_layer_call = call_collection.layer_call_method def _maybe_trace(self, args, kwargs): # Trigger traces of other call functions + extra training-arg traces. if tracing_enabled(): self.call_collection.add_trace(*args, **kwargs) def __call__(self, *args, **kwargs): self._maybe_trace(args, kwargs) return self.wrapped_call(*args, **kwargs) def get_concrete_function(self, *args, **kwargs): self._maybe_trace(args, kwargs) return self.wrapped_call.get_concrete_function(*args, **kwargs) def _wrap_call_and_conditional_losses(layer): """Wraps call function that returns a tuple of (outputs, losses). The losses returned are conditional on the inputs passed to the call function. Unconditional losses (e.g. weight regularizeration) are wrapped separately. Args: layer: a Keras layer object Returns: python call function that returns outputs and conditional losses -- excludes activity regularizer """ # Create function that generates both outputs and losses layer_call = _get_layer_call_method(layer) def call_and_return_conditional_losses(*args, **kwargs): """Returns layer (call_output, conditional losses) tuple.""" call_output = layer_call(*args, **kwargs) if version_utils.is_v1_layer_or_model(layer): conditional_losses = layer.get_losses_for( _filtered_inputs([args, kwargs])) else: conditional_losses = [ l for l in layer.losses if not hasattr(l, '_unconditional_loss') ] return call_output, conditional_losses return _create_call_fn_decorator(layer, call_and_return_conditional_losses) def _extract_outputs_from_fn(layer, call_and_return_conditional_losses): """Returns a function that returns only call function outputs.""" if isinstance(layer, keras_load.RevivedLayer): return layer.keras_api.__call__ # pylint: disable=protected-access def call(inputs, *args, **kwargs): return call_and_return_conditional_losses(inputs, *args, **kwargs)[0] return _create_call_fn_decorator(layer, call) def _append_activity_regularizer_loss( layer, call_fn_with_losses, activity_regularizer_fn): """Appends activity regularizer loss to losses returned by the wrapped fn.""" def fn(inputs, *args, **kwargs): outputs, losses = call_fn_with_losses(inputs, *args, **kwargs) losses.append(activity_regularizer_fn(outputs)) return outputs, losses return _create_call_fn_decorator(layer, fn) def _create_call_fn_decorator(layer, wrapped_call): call_fn = _get_layer_call_method(layer) fn, arg_spec = utils.maybe_add_training_arg( call_fn, wrapped_call, layer._expects_training_arg, # pylint: disable=protected-access default_training_value=False) return tf.__internal__.decorator.make_decorator( target=call_fn, decorator_func=fn, decorator_argspec=arg_spec) def _wrap_unconditional_loss(loss_fn, index): """Wraps callable/unconditional loss, returning a serializable function.""" # Extract original loss function from partial function fn = loss_fn.args[0] if isinstance(loss_fn, functools.partial) else loss_fn if isinstance(fn, tf.__internal__.function.Function): return fn else: return tf.__internal__.function.Function( fn, 'loss_fn_{}'.format(index), input_signature=[]) def _wrap_activity_regularizer(layer): """Wraps the activity regularizer.""" # pylint: disable=protected-access if isinstance(layer._activity_regularizer, tf.__internal__.function.Function): return layer._activity_regularizer return tf.__internal__.function.Function( layer._activity_regularizer, '{}_activity_regularizer'.format(layer.name), input_signature=[ tf.TensorSpec(None, layer._compute_dtype or K.floatx()) ]) # pylint: enable=protected-access def _get_layer_call_method(layer): if isinstance(layer.call, (tf.__internal__.function.Function)): return layer.call.python_function return layer.call
27,556
38.032578
111
py
keras
keras-master/keras/saving/saved_model/utils.py
# 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. # ============================================================================== """Utility functions shared between SavedModel saving/loading implementations.""" import tensorflow.compat.v2 as tf import itertools import threading import types from keras import backend as K from keras.engine import base_layer_utils from keras.utils import control_flow_util from keras.utils import tf_contextlib from keras.utils import tf_inspect from keras.utils.generic_utils import LazyLoader # pylint:disable=g-inconsistent-quotes training_lib = LazyLoader( "training_lib", globals(), "keras.engine.training") # pylint:enable=g-inconsistent-quotes def use_wrapped_call(layer, call_fn, default_training_value=None, return_method=False): """Creates fn that adds the losses returned by call_fn & returns the outputs. Args: layer: A Keras layer object call_fn: tf.function that takes layer inputs (and possibly a training arg), and returns a tuple of (outputs, list of losses). default_training_value: Default value of the training kwarg. If `None`, the default is `K.learning_phase()`. return_method: Whether to return a method bound to the layer. Returns: function that calls call_fn and returns the outputs. Losses returned by call_fn are added to the layer losses. """ expects_training_arg = layer_uses_training_bool(layer) if hasattr(call_fn, 'original_layer_call'): # call_fn is a LayerCall object original_call = call_fn.original_layer_call # In Python 3, callable objects are not compatible with inspect.getargspec call_fn = call_fn.__call__ else: original_call = call_fn fn, arg_spec = maybe_add_training_arg( original_call, call_fn, expects_training_arg, default_training_value) def return_outputs_and_add_losses(*args, **kwargs): """Returns the outputs from the layer call function, and adds the losses.""" if return_method: args = args[1:] outputs, losses = fn(*args, **kwargs) layer.add_loss(losses, inputs=True) # 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. # pylint: disable=protected-access if tf.executing_eagerly(): for i in layer._flatten_layers(): if i is not layer: i._eager_losses = [base_layer_utils.REVIVED_LOSS_PLACEHOLDER] # pylint: enable=protected-access return outputs decorated = tf.__internal__.decorator.make_decorator( target=call_fn, decorator_func=return_outputs_and_add_losses, decorator_argspec=arg_spec) if return_method: return types.MethodType(decorated, layer) else: return decorated def layer_uses_training_bool(layer): """Returns whether this layer or any of its children uses the training arg.""" if layer._expects_training_arg: # pylint: disable=protected-access return True visited = {layer} to_visit = list_all_layers(layer) while to_visit: layer = to_visit.pop() if layer in visited: continue if getattr(layer, '_expects_training_arg', True): return True visited.add(layer) to_visit.extend(list_all_layers(layer)) return False def list_all_layers(obj): if isinstance(obj, training_lib.Model): # Handle special case of Sequential, which doesn't return # the `Input` layer. return obj.layers else: return list(obj._flatten_layers(include_self=False, recursive=False)) # pylint: disable=protected-access def list_all_layers_and_sublayers(obj): s = set([obj]) s.update(itertools.chain.from_iterable( list_all_layers_and_sublayers(layer) for layer in list_all_layers(obj))) return s def maybe_add_training_arg( original_call, wrapped_call, expects_training_arg, default_training_value): """Decorate call and optionally adds training argument. If a layer expects a training argument, this function ensures that 'training' is present in the layer args or kwonly args, with the default training value. Args: original_call: Original call function. wrapped_call: Wrapped call function. expects_training_arg: Whether to include 'training' argument. default_training_value: Default value of the training kwarg to include in the arg spec. If `None`, the default is `K.learning_phase()`. Returns: Tuple of ( function that calls `wrapped_call` and sets the training arg, Argspec of returned function or `None` if the argspec is unchanged) """ if not expects_training_arg: return wrapped_call, None def wrap_with_training_arg(*args, **kwargs): """Wrap the `wrapped_call` function, and set training argument.""" training_arg_index = get_training_arg_index(original_call) training = get_training_arg(training_arg_index, args, kwargs) if training is None: training = default_training_value or K.learning_phase() args = list(args) kwargs = kwargs.copy() def replace_training_and_call(training): set_training_arg(training, training_arg_index, args, kwargs) return wrapped_call(*args, **kwargs) return control_flow_util.smart_cond( training, lambda: replace_training_and_call(True), lambda: replace_training_and_call(False)) # Create arg spec for decorated function. If 'training' is not defined in the # args of the original arg spec, then add it to kwonlyargs. arg_spec = tf_inspect.getfullargspec(original_call) defaults = list(arg_spec.defaults) if arg_spec.defaults is not None else [] kwonlyargs = arg_spec.kwonlyargs kwonlydefaults = arg_spec.kwonlydefaults or {} # Add training arg if it does not exist, or set the default training value. if 'training' not in arg_spec.args: kwonlyargs.append('training') kwonlydefaults['training'] = default_training_value else: index = arg_spec.args.index('training') training_default_index = len(arg_spec.args) - index if (arg_spec.defaults and len(arg_spec.defaults) >= training_default_index and defaults[-training_default_index] is None): defaults[-training_default_index] = default_training_value decorator_argspec = tf_inspect.FullArgSpec( args=arg_spec.args, varargs=arg_spec.varargs, varkw=arg_spec.varkw, defaults=defaults, kwonlyargs=kwonlyargs, kwonlydefaults=kwonlydefaults, annotations=arg_spec.annotations) return wrap_with_training_arg, decorator_argspec def get_training_arg_index(call_fn): """Returns the index of 'training' in the layer call function arguments. Args: call_fn: Call function. Returns: - n: index of 'training' in the call function arguments. - -1: if 'training' is not found in the arguments, but layer.call accepts variable keyword arguments - None: if layer doesn't expect a training argument. """ argspec = tf_inspect.getfullargspec(call_fn) if argspec.varargs: # When there are variable args, training must be a keyword arg. if 'training' in argspec.kwonlyargs or argspec.varkw: return -1 return None else: # Try to find 'training' in the list of args or kwargs. arg_list = argspec.args if tf_inspect.ismethod(call_fn): arg_list = arg_list[1:] if 'training' in arg_list: return arg_list.index('training') elif 'training' in argspec.kwonlyargs or argspec.varkw: return -1 return None def set_training_arg(training, index, args, kwargs): if index is None or index < 0 or len(args) <= index: # index is invalid kwargs['training'] = training else: args[index] = training return args, kwargs def get_training_arg(index, args, kwargs): if index is None or index < 0 or len(args) <= index: # index is invalid return kwargs.get('training', None) else: return args[index] def remove_training_arg(index, args, kwargs): if index is None or index < 0 or len(args) <= index: # index is invalid kwargs.pop('training', None) else: args.pop(index) class SaveOptionsContext(threading.local): def __init__(self): super(SaveOptionsContext, self).__init__() self.save_traces = True _save_options_context = SaveOptionsContext() @tf_contextlib.contextmanager def keras_option_scope(save_traces): previous_value = _save_options_context.save_traces try: _save_options_context.save_traces = save_traces yield finally: _save_options_context.save_traces = previous_value def should_save_traces(): """Whether to trace layer functions-can be disabled in the save_traces arg.""" return _save_options_context.save_traces @tf_contextlib.contextmanager def no_automatic_dependency_tracking_scope(obj): """A context that disables automatic dependency tracking when assigning attrs. Objects that inherit from Autotrackable automatically creates dependencies to trackable objects through attribute assignments, and wraps data structures (lists or dicts) with trackable classes. This scope may be used to temporarily disable this behavior. This works similar to the decorator `no_automatic_dependency_tracking`. Example usage: ``` model = tf.keras.Model() model.arr1 = [] # Creates a ListWrapper object with no_automatic_dependency_tracking_scope(model): model.arr2 = [] # Creates a regular, untracked python list ``` Args: obj: A trackable object. Yields: a scope in which the object doesn't track dependencies. """ previous_value = getattr(obj, '_setattr_tracking', True) obj._setattr_tracking = False # pylint: disable=protected-access try: yield finally: obj._setattr_tracking = previous_value # pylint: disable=protected-access
10,620
33.70915
109
py
keras
keras-master/keras/saving/saved_model/save.py
# 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 serialization.""" import tensorflow.compat.v2 as tf import os from keras import backend as K from keras.protobuf import saved_metadata_pb2 from keras.protobuf import versions_pb2 from keras.saving import saving_utils from keras.saving.saved_model import constants from keras.saving.saved_model import save_impl from keras.saving.saved_model import utils from keras.utils.generic_utils import LazyLoader from keras.utils.io_utils import ask_to_proceed_with_overwrite from tensorflow.python.saved_model import save as save_lib # To avoid circular dependencies between keras/engine and keras/saving, # code in keras/saving must delay imports. base_layer = LazyLoader( "base_layer", globals(), "keras.engine.base_layer") training_lib = LazyLoader( "training_lib", globals(), "keras.engine.training") def save(model, filepath, overwrite, include_optimizer, signatures=None, options=None, save_traces=True): """Saves a model as a SavedModel to the filepath. Args: model: Keras model instance to be saved. filepath: String path to save the model. overwrite: whether to overwrite the existing filepath. include_optimizer: If True, save the model's optimizer state. signatures: Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the `signatures` argument in `tf.saved_model.save` for details. options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` object that specifies options for saving to SavedModel. save_traces: (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to `True`. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a `get_config()` method. Raises: ValueError: if the model's inputs have not been defined. """ # If file exists and should not be overwritten. if not overwrite and os.path.exists(filepath): proceed = ask_to_proceed_with_overwrite(filepath) if not proceed: return if save_traces: if save_impl.should_skip_serialization(model): saving_utils.raise_model_input_error(model) if not include_optimizer: orig_optimizer = model.optimizer model.optimizer = None # TODO(b/180760306) Change to del model.optimizer if Layer's __delattr__ # calls AutoTrackable's __delattr__. model._delete_tracking("optimizer") # pylint: disable=protected-access # Trace all functions and signatures with `training=0` instead of using an # already-set learning phase placeholder. # This is needed for compatibility reasons until learning phase setting # is removed from the public apis. with K.deprecated_internal_learning_phase_scope(0): with utils.keras_option_scope(save_traces): saved_nodes, node_paths = save_lib.save_and_return_nodes( model, filepath, signatures, options) # Save all metadata to a separate file in the SavedModel directory. metadata = generate_keras_metadata(saved_nodes, node_paths) with tf.io.gfile.GFile( os.path.join(filepath, constants.SAVED_METADATA_PATH), "wb") as w: w.write(metadata.SerializeToString(deterministic=True)) if not include_optimizer: model.optimizer = orig_optimizer def generate_keras_metadata(saved_nodes, node_paths): """Constructs a KerasMetadata proto with the metadata of each keras object.""" metadata = saved_metadata_pb2.SavedMetadata() for node_id, node in enumerate(saved_nodes): if isinstance(node, base_layer.Layer): path = node_paths[node] if not path: node_path = "root" else: node_path = "root.{}".format( ".".join([ref.name for ref in path])) metadata.nodes.add( node_id=node_id, node_path=node_path, version=versions_pb2.VersionDef( producer=2, min_consumer=1, bad_consumers=[]), identifier=node._object_identifier, # pylint: disable=protected-access metadata=node._tracking_metadata) # pylint: disable=protected-access return metadata
4,944
38.246032
81
py
keras
keras-master/keras/saving/saved_model/serialized_attributes.py
# 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. # ============================================================================== """Helper classes that list&validate all attributes to serialize to SavedModel. """ from keras.saving.saved_model import constants from keras.saving.saved_model import order_preserving_set as ops from keras.saving.saved_model import save_impl from keras.utils.generic_utils import LazyLoader import tensorflow.compat.v2 as tf # TODO(b/134426265): Switch back to single-quotes to match the rest of the file # once the issue with copybara is fixed. # pylint:disable=g-inconsistent-quotes base_layer = LazyLoader( "base_layer", globals(), "keras.engine.base_layer") training_lib = LazyLoader( "training_lib", globals(), "keras.engine.training") metrics = LazyLoader("metrics", globals(), "keras.metrics") recurrent = LazyLoader( "recurrent", globals(), "keras.layers.recurrent") # pylint:enable=g-inconsistent-quotes class SerializedAttributes: """Class that tracks and validates all serialization attributes. Keras models contain many Python-defined components. For example, the trainable_variable property lists the model's trainable variables by recursively retrieving the trainable variables from each of the child layers. Another example is model.call, a python function that calls child layers and adds ops to the backend graph. Only Tensorflow checkpointable objects and functions can be serialized to SavedModel. Serializing a Keras model as-is results in a checkpointable object that does not resemble a Keras model at all. Thus, extra checkpointable objects and functions must be created during serialization. **Defining new serialized attributes** Child classes should be defined using: SerializedAttributes.with_attributes( 'name', checkpointable_objects=[...], functions=[...], copy_from=[...]) This class is used to cache generated checkpointable objects and functions, ensuring that new objects and functions are generated a single time. **Usage during serialization** Each Layer/Model object should have a corresponding instance of SerializedAttributes. Create a new instance by calling `SerializedAttributes.new(obj)`. Objects and functions may be saved using `.set_and_validate_checkpointable_objects`/`.set_and_and_validate_functions`. The properties `.checkpointable_objects` and `.functions` returns the cached values. **Adding/changing attributes to save to SavedModel** 1. Change the call to `SerializedAttributes.with_attributes` in the correct class: - CommonEndpoints: Base attributes to be added during serialization. If these attributes are present in a Trackable object, it can be deserialized to a Keras Model. - LayerAttributes: Attributes to serialize for Layer objects. - ModelAttributes: Attributes to serialize for Model objects. 2. Update class docstring 3. Update arguments to any calls to `set_and_validate_*`. For example, if `call_raw_tensors` is added to the ModelAttributes function list, then a `call_raw_tensors` function should be passed to `set_and_validate_functions`. **Common endpoints vs other attributes** Only common endpoints are attached directly to the root object. Keras-specific attributes are saved to a separate trackable object with the name "keras_api". The number of objects attached to the root is limited because any naming conflicts will cause user code to break. Another reason is that this will only affect users who call `tf.saved_model.load` instead of `tf.keras.models.load_model`. These are advanced users who are likely to have defined their own tf.functions and trackable objects. The added Keras-specific attributes are kept out of the way in the "keras_api" namespace. Properties defined in this class may be used to filter out keras-specific attributes: - `functions_to_serialize`: Returns dict of functions to attach to the root object. - `checkpointable_objects_to_serialize`: Returns dict of objects to attach to the root object (including separate trackable object containing keras-specific attributes) All changes to the serialized attributes must be backwards-compatible, so attributes should not be removed or modified without sufficient justification. """ @staticmethod def with_attributes( name, checkpointable_objects=None, functions=None, copy_from=None): """Creates a subclass with all attributes as specified in the arguments. Args: name: Name of subclass checkpointable_objects: List of checkpointable objects to be serialized in the SavedModel. functions: List of functions to be serialized in the SavedModel. copy_from: List of other SerializedAttributes subclasses. The returned class will copy checkpoint objects/functions from each subclass. Returns: Child class with attributes as defined in the `checkpointable_objects` and `functions` lists. """ checkpointable_objects = checkpointable_objects or [] functions = functions or [] if copy_from is not None: for cls in copy_from: checkpointable_objects.extend(cls.all_checkpointable_objects) functions.extend(cls.all_functions) # OrderPreservingSets are used here to guarantee serialization determinism # of Keras objects. classdict = { 'all_checkpointable_objects': ops.OrderPreservingSet(checkpointable_objects), 'all_functions': ops.OrderPreservingSet(functions), } return type(name, (SerializedAttributes,), classdict) @staticmethod def new(obj): """Returns a new SerializedAttribute object.""" if isinstance(obj, training_lib.Model): return ModelAttributes() elif isinstance(obj, metrics.Metric): return MetricAttributes() elif isinstance(obj, recurrent.RNN): return RNNAttributes() elif isinstance(obj, base_layer.Layer): return LayerAttributes() else: raise TypeError('Internal error during serialization. Expected Keras ' f'Layer object. Received: {obj} ' f'(of type {type(obj)})') def __init__(self): self._object_dict = {} self._function_dict = {} self._keras_trackable = tf.__internal__.tracking.AutoTrackable() @property def functions(self): """Returns dictionary of all functions.""" return {key: value for key, value in self._function_dict.items() if value is not None} @property def checkpointable_objects(self): """Returns dictionary of all checkpointable objects.""" return {key: value for key, value in self._object_dict.items() if value is not None} @property def functions_to_serialize(self): """Returns functions to attach to the root object during serialization.""" functions = {} for key, v in self.functions.items(): if key in CommonEndpoints.all_functions: functions[key] = (v.wrapped_call if isinstance(v, save_impl.LayerCall) else v) return functions @property def objects_to_serialize(self): """Returns objects to attach to the root object during serialization.""" objects = {key: value for key, value in self.checkpointable_objects.items() if key in CommonEndpoints.all_checkpointable_objects} objects[constants.KERAS_ATTR] = self._keras_trackable return objects def set_and_validate_functions(self, function_dict): """Saves function dictionary, and validates dictionary values.""" for key in self.all_functions: if key in function_dict: if (function_dict[key] is not None and # Not all functions are required not isinstance(function_dict[key], (tf.__internal__.function.Function, tf.types.experimental.ConcreteFunction, save_impl.LayerCall))): raise ValueError( 'The tf.function dictionary contained a non-function object: ' f'{function_dict[key]} (for key {key}). Only tf.function ' 'instances or ConcreteFunction instances should be passed.') fn = function_dict[key] self._function_dict[key] = fn # Extract TensorFlow `Function` from LayerCall. tf_fn = fn.wrapped_call if isinstance(fn, save_impl.LayerCall) else fn setattr(self._keras_trackable, key, tf_fn) else: raise ValueError( f'Function {key} missing from serialized tf.function dictionary.') return self.functions def set_and_validate_objects(self, object_dict): """Saves objects to a dictionary, and validates the values.""" for key in self.all_checkpointable_objects: if key in object_dict: if not isinstance(object_dict[key], tf.__internal__.tracking.Trackable): raise ValueError( 'The object dictionary contained a non-trackable object: ' f'{object_dict[key]} (for key {key}). Only trackable objects are ' f'allowed, such as Keras layers/models or tf.Module instances.') self._object_dict[key] = object_dict[key] setattr(self._keras_trackable, key, object_dict[key]) else: raise ValueError( f'Object {key} missing from serialized object dictionary.') return self.checkpointable_objects class CommonEndpoints(SerializedAttributes.with_attributes( 'CommonEndpoints', checkpointable_objects=['variables', 'trainable_variables', 'regularization_losses'], functions=['__call__', 'call_and_return_all_conditional_losses', '_default_save_signature'])): """Common endpoints shared by all models loadable by Keras. List of all attributes: variables: List of all variables in the model and its sublayers. trainable_variables: List of all trainable variables in the model and its sublayers. regularization_losses: List of all unconditional losses (losses not dependent on the inputs) in the model and its sublayers. __call__: Function that takes inputs and returns the outputs of the model call function. call_and_return_all_conditional_losses: Function that returns a tuple of (call function outputs, list of all losses that depend on the inputs). _default_save_signature: Traced model call function. This is only included if the top level exported object is a Keras model. """ class LayerAttributes(SerializedAttributes.with_attributes( 'LayerAttributes', checkpointable_objects=['non_trainable_variables', 'layers', 'metrics', 'layer_regularization_losses', 'layer_metrics'], functions=['call_and_return_conditional_losses', 'activity_regularizer_fn'], copy_from=[CommonEndpoints] )): """Layer checkpointable objects + functions that are saved to the SavedModel. List of all attributes: All attributes from CommonEndpoints non_trainable_variables: List of non-trainable variables in the layer and its sublayers. layers: List of all sublayers. metrics: List of all metrics in the layer and its sublayers. call_and_return_conditional_losses: Function that takes inputs and returns a tuple of (outputs of the call function, list of input-dependent losses). The list of losses excludes the activity regularizer function, which is separate to allow the deserialized Layer object to define a different activity regularizer. activity_regularizer_fn: Callable that returns the activity regularizer loss layer_regularization_losses: List of losses owned only by this layer. layer_metrics: List of metrics owned by this layer. """ class ModelAttributes(SerializedAttributes.with_attributes( 'ModelAttributes', copy_from=[LayerAttributes])): """Model checkpointable objects + functions that are saved to the SavedModel. List of all attributes: All attributes from LayerAttributes (including CommonEndpoints) """ # TODO(kathywu): Add attributes `compile_losses` and `compile_metrics`, which # list all losses and metrics defined by `model.compile`. class MetricAttributes( SerializedAttributes.with_attributes( 'MetricAttributes', checkpointable_objects=['variables'], functions=[], )): """Attributes that are added to Metric objects when saved to SavedModel. List of all attributes: variables: list of all variables """ pass class RNNAttributes(SerializedAttributes.with_attributes( 'RNNAttributes', checkpointable_objects=['states'], copy_from=[LayerAttributes])): """RNN checkpointable objects + functions that are saved to the SavedModel. List of all attributes: All attributes from LayerAttributes (including CommonEndpoints) states: List of state variables """
13,540
41.315625
80
py
keras
keras-master/keras/saving/saved_model/order_preserving_set.py
# 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. # ============================================================================== """A set based on dict so that it preserves key insertion order. Python Dicts are order-preserving since 3.6 (https://mail.python.org/pipermail/python-dev/2017-December/151283.html), but sets are not. This class implements a set on top of a dict so that we get deterministic iteration order across runs. """ import collections.abc class OrderPreservingSet(collections.abc.MutableSet): """A set based on dict so that it preserves key insertion order.""" def __init__(self, iterable=None): self._dict = {item: None for item in (iterable or [])} # abstract from collections.MutableSet def __len__(self): return len(self._dict) # abstract from collections.MutableSet def __contains__(self, value): return value in self._dict # override from collections.MutableSet def __iter__(self): return iter(self._dict) # abstract from collections.MutableSet def add(self, item): self._dict[item] = None # abstract from collections.MutableSet def discard(self, value): del self._dict[value] # override from collections.MutableSet def clear(self): self._dict = {} # override from collections.Set def __eq__(self, other): if not isinstance(other, OrderPreservingSet): return NotImplemented return self._dict.keys() == other._dict.keys() # override from collections.Set def __le__(self, other): if not isinstance(other, OrderPreservingSet): return NotImplemented return self._dict.keys() <= other._dict.keys() # override from collections.Set def __ge__(self, other): if not isinstance(other, OrderPreservingSet): return NotImplemented return self._dict.keys() >= other._dict.keys() # override from collections.Set def __and__(self, other): # collections.Set defaults to the ordering in other, we want to use self return self._from_iterable(value for value in self if value in other) # override from collections.Set def __or__(self, other): # ensure that other is ordered before performing __or__ if not isinstance(other, OrderPreservingSet): raise TypeError( "cannot union an 'OrderPreservingSet' with an unordered iterable.") result = self._from_iterable(value for value in self) for value in other: result._dict[value] = None return result def union(self, other): return self | other
3,047
32.130435
80
py
keras
keras-master/keras/saving/saved_model/model_serialization.py
# 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. # ============================================================================== """Classes and functions implementing to Model SavedModel serialization.""" from keras.saving import saving_utils from keras.saving.saved_model import constants from keras.saving.saved_model import layer_serialization from keras.saving.saved_model import save_impl class ModelSavedModelSaver(layer_serialization.LayerSavedModelSaver): """Model SavedModel serialization.""" @property def object_identifier(self): return constants.MODEL_IDENTIFIER def _python_properties_internal(self): metadata = super(ModelSavedModelSaver, self)._python_properties_internal() # Network stateful property is dependent on the child layers. metadata.pop('stateful') metadata['is_graph_network'] = self.obj._is_graph_network # pylint: disable=protected-access spec = self.obj.save_spec(dynamic_batch=False) metadata['full_save_spec'] = spec # save_spec is saved for forward compatibility on older TF versions. metadata['save_spec'] = None if spec is None else spec[0][0] metadata.update( saving_utils.model_metadata( self.obj, include_optimizer=True, require_config=False)) return metadata def _get_serialized_attributes_internal(self, serialization_cache): default_signature = None # Create a default signature function if this is the only object in the # cache (i.e. this is the root level object). if len(serialization_cache[constants.KERAS_CACHE_KEY]) == 1: default_signature = save_impl.default_save_signature(self.obj) # Other than the default signature function, all other attributes match with # the ones serialized by Layer. objects, functions = ( super(ModelSavedModelSaver, self)._get_serialized_attributes_internal( serialization_cache)) functions['_default_save_signature'] = default_signature return objects, functions class SequentialSavedModelSaver(ModelSavedModelSaver): @property def object_identifier(self): return constants.SEQUENTIAL_IDENTIFIER
2,692
39.19403
97
py
keras
keras-master/keras/saving/saved_model/load.py
# 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 os import re import types from keras import backend from keras import regularizers from keras.engine import input_spec from keras.optimizer_v2 import optimizer_v2 from keras.protobuf import saved_metadata_pb2 from keras.protobuf import versions_pb2 from keras.saving import saving_utils from keras.saving.saved_model import constants from keras.saving.saved_model import json_utils from keras.saving.saved_model import utils from keras.saving.saved_model.serialized_attributes import CommonEndpoints from keras.utils import generic_utils from keras.utils import metrics_utils from keras.utils.generic_utils import LazyLoader import tensorflow.compat.v1.logging as logging import tensorflow.compat.v2 as tf from google.protobuf import message # 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. # pylint:disable=g-inconsistent-quotes models_lib = LazyLoader("models_lib", globals(), "keras.models") base_layer = LazyLoader( "base_layer", globals(), "keras.engine.base_layer") layers_module = LazyLoader( "layers_module", globals(), "keras.layers") input_layer = LazyLoader( "input_layer", globals(), "keras.engine.input_layer") functional_lib = LazyLoader( "functional_lib", globals(), "keras.engine.functional") training_lib = LazyLoader( "training_lib", globals(), "keras.engine.training") training_lib_v1 = LazyLoader( "training_lib_v1", globals(), "keras.engine.training_v1") metrics = LazyLoader("metrics", globals(), "keras.metrics") recurrent = LazyLoader( "recurrent", globals(), "keras.layers.recurrent") # pylint:enable=g-inconsistent-quotes PUBLIC_ATTRIBUTES = CommonEndpoints.all_functions.union( CommonEndpoints.all_checkpointable_objects) PUBLIC_ATTRIBUTES.add(constants.KERAS_ATTR) def load(path, compile=True, options=None): # pylint: disable=redefined-builtin """Loads Keras objects from a SavedModel. Any Keras layer or model saved to the SavedModel will be loaded back as Keras objects. Other objects are loaded as regular trackable objects (same as `tf.saved_model.load`). Currently, Keras saving/loading only retains the 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 = os.path.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) if not metadata.nodes: # When there are no 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 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'] # pylint: disable=protected-access 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.') # pylint: enable=protected-access # 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): """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 Keras model from this SavedModel. ' 'This SavedModel was created with ' '`tf.saved_model.save`, and lacks the Keras metadata.' 'Please save your Keras model by calling `model.save`' 'or `tf.keras.models.save_model`.') 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] = '{}.{}'.format(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.""" # pylint: disable=protected-access 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 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) # pylint: disable=protected-access 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) # pylint: disable=protected-access for name in dependencies: if re.match(r'^layer(_with_weights)?-[\d+]', name) is not None: node._delete_tracking(name) # pylint: disable=protected-access def _add_children_recreated_from_config(self, obj, proto, node_id): """Recursively records objects recreated from config.""" # pylint: disable=protected-access 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 # pylint: enable=protected-access 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' # pylint: disable=protected-access if isinstance(obj_child, tf.__internal__.tracking.TrackableDataStructure): setter = lambda *args: None child_path = '{}.{}'.format(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): # pylint: disable=redefined-builtin """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 generic_utils.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 generic_utils.validate_config(config): return None class_name = tf.compat.as_str(metadata['class_name']) if generic_utils.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 generic_utils.validate_config(config): return None try: obj = layers_module.deserialize( generic_utils.serialize_keras_class_and_config( class_name, config, shared_object_id=shared_object_id)) except ValueError: if must_restore_from_config: raise RuntimeError( f'Unable to restore a layer of class {class_name}. Layers of ' f'class {class_name} require that the class be provided to ' 'the model loading code, either by registering the ' 'class using `@keras.utils.register_keras_serializable` ' 'on the class def and including that file in your ' 'program, or by passing the class in a ' '`keras.utils.CustomObjectScope` that wraps this load call.') 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. # pylint: disable=protected-access 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'] # 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) # pylint: enable=protected-access 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 generic_utils.validate_config(config): return None try: obj = metrics.deserialize( generic_utils.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) # pylint: disable=protected-access 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 _load_edges(self): """Add edges for all nodes that are not waiting on initialization.""" for node_id, proto in enumerate(self._proto.nodes): if node_id not in self.model_layer_dependencies: self._add_object_graph_edges(proto, node_id) def get_path(self, node_id): return self._node_paths[node_id] def finalize_objects(self): """Finish setting up 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) or # Don't finalize models until all layers have finished loading. 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(f'Error loading model(s) in the SavedModel format. ' f'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) # pylint: disable=protected-access 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.""" coder = tf.__internal__.saved_model.StructureCoder() 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 = coder.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: # pylint: disable=protected-access setter(obj, name, value) return setattr_wrapper def _finalize_saved_model_layers(layers): """Runs the final steps of loading Keras Layers from SavedModel.""" # pylint: disable=protected-access # 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: layer.call = utils.use_wrapped_call( layer, layer_call, 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) # pylint: disable=protected-access # 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) # pylint: enable=protected-access 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. 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 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, recurrent.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', []) # pylint: disable=protected-access 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) if parent_classes is not None: parent_classes = revived_classes[identifier] revived_cls = type( tf.compat.as_str(metadata['class_name']), parent_classes, {}) return revived_cls._init_from_metadata(metadata) # pylint: disable=protected-access else: raise ValueError( f'Unable to restore custom object of type {identifier}. ' f'Please make sure that any custom layers are included in the ' f'`custom_objects` arg when calling `load_model()` and make sure that ' f'all layers implement `get_config` and `from_config`.') def _restore_layer_metrics(layer): metrics_list = getattr(_get_keras_attr(layer), 'layer_metrics', {}) layer_metrics = {m.name: m for m in layer._metrics} # pylint: disable=protected-access 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) # pylint: disable=protected-access # 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): # pylint:disable=protected-access revived_obj._expects_training_arg = metadata['expects_training_arg'] config = metadata.get('config') if generic_utils.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'] # pylint:enable=protected-access 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: # pylint: disable=protected-access if isinstance(value, tf.__internal__.tracking.Trackable): layer._track_trackable(value, name=name) layer._serialized_attributes[name] = value # pylint: enable=protected-access 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) # pylint: disable=protected-access 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'] # pylint:disable=protected-access return revived_obj, setattr def get_config(self): return self._config def recursively_deserialize_keras_object(config, module_objects=None): """Deserialize Keras object from a nested structure.""" if isinstance(config, dict): if 'class_name' in config: return generic_utils.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( f'Unable to decode Keras layer config. Config should be a dictionary, ' f'tuple or list. Received: config={config}') def get_common_shape(x, y): """Find a `TensorShape` that is compatible with both `x` and `y`.""" if x is None != y is None: raise RuntimeError( 'Cannot find a common shape when LHS shape is None but RHS shape ' 'is not (or vice versa): %s vs. %s' % (x, y)) if x is None: return None # The associated input was not a Tensor, no shape generated. if not isinstance(x, tf.TensorShape): raise TypeError( f'Expected x to be a TensorShape but received {x} with type {type(x)}') if not isinstance(y, tf.TensorShape): raise TypeError( f'Expected y to be a TensorShape but received {y} with type {type(y)}') if x.rank != y.rank or x.rank is None: return tf.TensorShape(None) dims = [] for dim_x, dim_y in zip(x.dims, y.dims): if (dim_x != dim_y or tf.compat.dimension_value(dim_x) is None or tf.compat.dimension_value(dim_y) is None): dims.append(None) else: dims.append(tf.compat.dimension_value(dim_x)) return tf.TensorShape(dims) def infer_inputs_from_restored_call_function(fn): """Returns TensorSpec 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: TensorSpec of call function inputs in the form of (args, kwargs) """ def common_spec(x, y): if not isinstance(x, tf.TensorSpec): # Doesn't particularly matter what is returned in this case because the # result will be filtered out in _set_input_shape. return x common_shape = get_common_shape(x.shape, y.shape) if isinstance(x, tf.SparseTensorSpec): return tf.SparseTensorSpec(common_shape, x.dtype) elif isinstance(x, tf.RaggedTensorSpec): return tf.RaggedTensorSpec( common_shape, x.dtype, ragged_rank=x.ragged_rank, row_splits_dtype=x.row_splits_dtype, flat_values_spec=x.flat_values_spec) return tf.TensorSpec(common_shape, x.dtype, x.name) 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): # pylint:disable=protected-access revived_obj._expects_training_arg = metadata['expects_training_arg'] config = metadata.get('config') if generic_utils.validate_config(config): revived_obj._config = config if metadata.get('activity_regularizer') is not None: revived_obj.activity_regularizer = regularizers.deserialize( metadata['activity_regularizer']) # pylint:enable=protected-access return revived_obj, _revive_setter # pylint:disable=protected-access def _set_network_attributes_from_metadata(revived_obj): """Sets attributes recorded in the metadata.""" with utils.no_automatic_dependency_tracking_scope(revived_obj): # pylint:disable=protected-access 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'] # pylint:enable=protected-access 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} # pylint: disable=protected-access def _get_keras_attr(layer): return getattr(layer, '_serialized_attributes', {}).get(constants.KERAS_ATTR, None)
51,728
40.716935
110
py
keras
keras-master/keras/saving/saved_model/metric_serialization.py
# 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. # ============================================================================== """Classes and functions implementing Metrics SavedModel serialization.""" from keras.saving.saved_model import constants from keras.saving.saved_model import layer_serialization from keras.utils import generic_utils import tensorflow.compat.v2 as tf class MetricSavedModelSaver(layer_serialization.LayerSavedModelSaver): """Metric serialization.""" @property def object_identifier(self): return constants.METRIC_IDENTIFIER def _python_properties_internal(self): metadata = dict( class_name=generic_utils.get_registered_name(type(self.obj)), name=self.obj.name, dtype=self.obj.dtype) metadata.update(layer_serialization.get_serialized(self.obj)) if self.obj._build_input_shape is not None: # pylint: disable=protected-access metadata['build_input_shape'] = self.obj._build_input_shape # pylint: disable=protected-access return metadata def _get_serialized_attributes_internal(self, unused_serialization_cache): return ( dict(variables=tf.__internal__.tracking.wrap(self.obj.variables)), # TODO(b/135550038): save functions to enable saving custom metrics. {}, )
1,851
39.26087
101
py
keras
keras-master/keras/saving/saved_model/determinism_test.py
"""Saves the same model twice and ensures that they are serialized the same.""" import subprocess from absl import flags import tensorflow.compat.v2 as tf # pylint: disable=g-direct-tensorflow-import from tensorflow.core.protobuf import saved_model_pb2 # pylint: enable=g-direct-tensorflow-import FLAGS = flags.FLAGS class DeterminismTest(tf.test.TestCase): def test_saving_is_deterministic(self): create_saved_model = f'{FLAGS.test_srcdir}/create_test_saved_model.par' saved_model_a_path = f'{FLAGS.test_tmpdir}/a' saved_model_b_path = f'{FLAGS.test_tmpdir}/b' save_a = subprocess.Popen( [create_saved_model, '--output_path', saved_model_a_path]) save_b = subprocess.Popen( [create_saved_model, '--output_path', saved_model_b_path]) save_a.wait() save_b.wait() saved_model_a = saved_model_pb2.SavedModel() with tf.io.gfile.GFile(f'{saved_model_a_path}/saved_model.pb') as f: saved_model_a.MergeFromString(f.read()) saved_model_b = saved_model_pb2.SavedModel() with tf.io.gfile.GFile(f'{saved_model_b_path}/saved_model.pb') as f: saved_model_b.MergeFromString(f.read()) self.assertProtoEquals(saved_model_a, saved_model_b)
1,210
32.638889
79
py
keras
keras-master/keras/saving/saved_model/saved_model_test.py
# 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. # ============================================================================== # pylint: disable=protected-access """Tests for saving and loading Keras models and layers from SavedModel. These should ensure that all layer properties are correctly assigned after loading from the SavedModel. Tests that focus on the model structure should go in revive_test.py """ import os import shutil import sys from absl.testing import parameterized import keras from keras import combinations from keras import keras_parameterized from keras import regularizers from keras import testing_utils from keras.feature_column.dense_features import DenseFeatures from keras.protobuf import saved_metadata_pb2 from keras.protobuf import versions_pb2 from keras.saving.saved_model import json_utils from keras.saving.saved_model import load as keras_load from keras.saving.saved_model import save_impl as keras_save from keras.utils import control_flow_util from keras.utils import generic_utils from keras.utils import tf_contextlib from keras.utils import tf_inspect import numpy as np import tensorflow.compat.v2 as tf from tensorflow.core.example import example_pb2 from tensorflow.core.example import feature_pb2 class LayerWithLearningPhase(keras.engine.base_layer.Layer): def build(self, input_shape): self.input_spec = keras.layers.InputSpec(shape=[None] * len(input_shape)) self.built = True def call(self, x, training=None): if training is None: training = keras.backend.learning_phase() output = control_flow_util.smart_cond(training, lambda: x * 0, lambda: tf.identity(x)) if not tf.executing_eagerly(): output._uses_learning_phase = True # pylint: disable=protected-access return output def compute_output_shape(self, input_shape): return input_shape @property def _use_input_spec_as_call_signature(self): return True class LayerWithLoss(keras.layers.Layer): def call(self, inputs): self.add_loss(tf.reduce_sum(inputs), inputs=inputs) return inputs * 2 class LayerWithUpdate(keras.layers.Layer): def build(self, _): self.v = self.add_weight( 'v', shape=[], initializer=keras.initializers.zeros, trainable=False, dtype=tf.float32) def call(self, inputs, training=True): if training: self.add_update(self.v.assign_add(1.)) return inputs * 2. @generic_utils.register_keras_serializable('Testing') class GlobalLayerThatShouldFailIfNotAdded(keras.layers.Layer): _must_restore_from_config = True @keras_parameterized.run_all_keras_modes class TestSavedModelFormatAllModes(keras_parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def _get_model(self): model = testing_utils.get_small_mlp(1, 4, input_dim=3) model.layers[-1].activity_regularizer = regularizers.get('l2') model.activity_regularizer = regularizers.get('l2') model.compile( loss='mse', optimizer='rmsprop') def callable_loss(): return tf.reduce_sum(model.weights[0]) model.add_loss(callable_loss) return model def _train_model(self, model, use_dataset=False): x = np.random.random((1, 3)) y = np.random.random((1, 4)) if not tf.__internal__.tf2.enabled(): # The layer autocast behavior only runs when autocast is enabled, so # in V1, the numpy inputs still need to be cast to float32. x = x.astype(np.float32) y = y.astype(np.float32) if use_dataset: dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(1) model.fit(dataset) else: model.train_on_batch(x, y) def _save_and_load(self, model): saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) return loaded def _test_evaluation(self, model, loaded): # Assert that original and loaded models have the same results when called. self.evaluate(tf.compat.v1.variables_initializer(loaded.variables)) self.assertAllClose(self.evaluate(model.weights), self.evaluate(loaded.weights)) input_arr = tf.constant( np.random.random((1, 3)).astype(np.float32)) self.assertAllClose(self.evaluate(model(input_arr)), self.evaluate(loaded(input_arr))) # Validate losses. The order of conditional losses may change between the # model and loaded model, so sort the losses first. if tf.executing_eagerly(): self.assertAllClose(sorted(self.evaluate(model.losses)), sorted(self.evaluate(loaded.losses))) else: self.assertAllClose(self.evaluate(model.get_losses_for(None)), self.evaluate(loaded.get_losses_for(None))) self.assertAllClose( sorted(self.evaluate(model.get_losses_for(input_arr))), sorted(self.evaluate(loaded.get_losses_for(input_arr)))) @keras_parameterized.run_with_all_model_types def test_model_save_and_load(self): model = self._get_model() self._train_model(model, use_dataset=False) loaded = self._save_and_load(model) self._test_evaluation(model, loaded) @keras_parameterized.run_with_all_model_types def test_model_save_and_load_dataset(self): model = self._get_model() self._train_model(model, use_dataset=True) loaded = self._save_and_load(model) self._test_evaluation(model, loaded) def test_trainable_weights(self): """Tests that trainable status of individual weights is preserved.""" layer = keras.layers.Dense(4, name='custom_layer') layer.build([None, 3]) layer.add_weight( 'extra_weight', shape=[], initializer=tf.compat.v1.constant_initializer(11), trainable=True) layer.add_weight( 'extra_weight_2', shape=[], initializer=tf.compat.v1.constant_initializer(12), trainable=False) model = keras.Sequential([keras.Input([3,]), layer]) saved_model_dir = self._save_model_dir() self.evaluate(tf.compat.v1.variables_initializer(layer.variables)) model.save(saved_model_dir, save_format='tf') loaded_model = keras_load.load(saved_model_dir) self.evaluate(tf.compat.v1.variables_initializer(loaded_model.variables)) loaded = loaded_model.layers[-1] equal_attrs = ['name', '_expects_training_arg', 'trainable'] for attr in equal_attrs: self.assertEqual(getattr(layer, attr), getattr(loaded, attr)) all_close = ['weights', 'trainable_weights', 'non_trainable_weights'] for attr in all_close: self.assertAllClose(self.evaluate(getattr(layer, attr)), self.evaluate(getattr(loaded, attr))) @keras_parameterized.run_with_all_model_types def test_trainable_layers(self): """Tests that trainable status of individual layers is preserved.""" model = model = self._get_model() # Set the last layer to *not* be trainable. model.layers[-1].trainable = False self._train_model(model, use_dataset=True) loaded = self._save_and_load(model) self._test_evaluation(model, loaded) self.assertFalse(model.layers[-1].trainable) self.assertFalse(loaded.layers[-1].trainable) def test_trainable_custom_model_false(self): """Tests that overall False trainable status of Model is preserved.""" # Set all layers to *not* be trainable. model = testing_utils.SmallSubclassMLP(1, 4, trainable=False) model.compile(loss='mse', optimizer='rmsprop') self._train_model(model, use_dataset=False) loaded = self._save_and_load(model) self._test_evaluation(model, loaded) self.assertEmpty(model.trainable_variables) self.assertEmpty(loaded.trainable_variables) def test_maintains_losses(self): """Tests that the layer losses do not change before and after export.""" model = keras.models.Sequential([LayerWithLoss()]) model.compile( loss='mse', optimizer='rmsprop') input_arr = np.random.random((1, 3)) target_arr = np.random.random((1, 3)) # Test that symbolic losses are maintained (train_on_batch saves symbolic # losses.) model.train_on_batch(input_arr, target_arr) previous_losses = model.losses[:] saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') with previous_losses[0].graph.as_default(): # If we try to compare symbolic Tensors in eager mode assertAllEqual will # return False even if they are the same Tensor. self.assertAllEqual(previous_losses, model.losses) if tf.executing_eagerly(): # Test that eager losses are maintained. model(input_arr) # Calls model eagerly, creating eager losses. previous_losses = model.losses[:] model.save(saved_model_dir, save_format='tf') self.assertAllEqual(previous_losses, model.losses) def test_layer_with_learning_phase(self): layer = LayerWithLearningPhase() layer.build([None, None]) saved_model_dir = self._save_model_dir() model = testing_utils.get_model_from_layers( [layer], input_shape=[None], model_type='functional') model.save(saved_model_dir, save_format='tf') loaded_model = keras_load.load(saved_model_dir) loaded = loaded_model.layers[-1] input_arr = tf.ones((4, 3)) # Run the layer, and use the keras backend learning phase keras.backend.set_learning_phase(0) self.assertAllEqual(input_arr, loaded(input_arr)) keras.backend.set_learning_phase(1) self.assertAllEqual(tf.zeros((4, 3)), loaded(input_arr)) # Run the layer while explicitly setting the training argument self.assertAllEqual( input_arr, loaded(input_arr, training=tf.constant(False))) self.assertAllEqual( tf.zeros((4, 3)), loaded(input_arr, training=tf.constant(True))) @keras_parameterized.run_with_all_model_types def test_standard_loader(self): model = testing_utils.get_small_mlp(1, 4, input_dim=3) model.activity_regularizer = regularizers.get('l2') def eager_loss(): return tf.reduce_sum(model.weights[0]) model.add_loss(eager_loss) # Call predict to ensure that all layers are built and inputs are set. model.predict(np.random.random((1, 3)).astype(np.float32)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = tf.saved_model.load(saved_model_dir) self.evaluate(tf.compat.v1.variables_initializer(loaded.variables)) all_close = ['variables', 'trainable_variables', 'non_trainable_variables'] for attr in all_close: self.assertAllClose(self.evaluate(getattr(model, attr)), self.evaluate(getattr(loaded.keras_api, attr))) self.assertLen(loaded.regularization_losses, 1) expected_layers = len(model.layers) self.assertEqual(expected_layers, len(loaded.keras_api.layers)) input_arr = tf.ones((4, 3)) self.assertAllClose(self.evaluate(model(input_arr)), self.evaluate(loaded(input_arr, training=False))) @keras_parameterized.run_with_all_model_types def test_compiled_model(self): # TODO(b/134519980): Issue with model.fit if the model call function uses # a tf.function (Graph mode only). if not tf.executing_eagerly(): return input_arr = np.random.random((1, 3)) target_arr = np.random.random((1, 4)) model = testing_utils.get_small_mlp(1, 4, input_dim=3) expected_predict = model.predict(input_arr) # Compile and save model. model.compile('rmsprop', 'mse') saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) actual_predict = loaded.predict(input_arr) self.assertAllClose(expected_predict, actual_predict) loss_before = loaded.evaluate(input_arr, target_arr) loaded.fit(input_arr, target_arr) loss_after = loaded.evaluate(input_arr, target_arr) self.assertLess(loss_after, loss_before) predict = loaded.predict(input_arr) ckpt_path = os.path.join(self.get_temp_dir(), 'weights') loaded.save_weights(ckpt_path) # Ensure that the checkpoint is compatible with the original model. model.load_weights(ckpt_path) self.assertAllClose(predict, model.predict(input_arr)) def test_metadata_input_spec(self): class LayerWithNestedSpec(keras.layers.Layer): def __init__(self): super(LayerWithNestedSpec, self).__init__() self.input_spec = { 'a': keras.layers.InputSpec(max_ndim=3, axes={-1: 2}), 'b': keras.layers.InputSpec(shape=(None, 2, 3), dtype='int32')} @property def _use_input_spec_as_call_signature(self): return True layer = LayerWithNestedSpec() saved_model_dir = self._save_model_dir() model = testing_utils.get_model_from_layers( [layer], model_type='subclass') model({'a': tf.constant([[2, 4]]), 'b': tf.ones([1, 2, 3], dtype=tf.int32)}) model.save(saved_model_dir, save_format='tf') loaded_model = keras_load.load(saved_model_dir) loaded = loaded_model.layers[-1] self.assertEqual(3, loaded.input_spec['a'].max_ndim) self.assertEqual({-1: 2}, loaded.input_spec['a'].axes) self.assertAllEqual([None, 2, 3], loaded.input_spec['b'].shape) self.assertEqual('int32', loaded.input_spec['b'].dtype) def test_must_restore_from_config_fails_if_layer_is_not_in_scope(self): class LayerThatShouldFailIfNotAdded(keras.layers.Layer): _must_restore_from_config = True layer = LayerThatShouldFailIfNotAdded() saved_model_dir = self._save_model_dir() model = testing_utils.get_model_from_layers( [layer], input_shape=[3], model_type='functional') model.save(saved_model_dir, save_format='tf') with self.assertRaisesRegex(RuntimeError, 'Unable to restore a layer of'): _ = keras_load.load(saved_model_dir) def test_must_restore_from_config_custom_object_scope(self): class LayerThatShouldFailIfNotAdded(keras.layers.Layer): _must_restore_from_config = True layer = LayerThatShouldFailIfNotAdded() model = testing_utils.get_model_from_layers( [layer], input_shape=[3], model_type='functional') saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') with generic_utils.CustomObjectScope( {'LayerThatShouldFailIfNotAdded': LayerThatShouldFailIfNotAdded}): _ = keras_load.load(saved_model_dir) def test_must_restore_from_config_registration(self): layer = GlobalLayerThatShouldFailIfNotAdded() saved_model_dir = self._save_model_dir() model = testing_utils.get_model_from_layers( [layer], input_shape=[3], model_type='functional') model.save(saved_model_dir, save_format='tf') _ = keras_load.load(saved_model_dir) def test_multi_input_model(self): input_1 = keras.layers.Input(shape=(3,)) input_2 = keras.layers.Input(shape=(5,)) model = keras.Model([input_1, input_2], [input_1, input_2]) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) input_arr_1 = np.random.random((1, 3)).astype('float32') input_arr_2 = np.random.random((1, 5)).astype('float32') outputs = loaded([input_arr_1, input_arr_2]) self.assertAllEqual(input_arr_1, outputs[0]) self.assertAllEqual(input_arr_2, outputs[1]) def test_revived_sequential(self): model = keras.models.Sequential() model.add(keras.layers.Dense(5, input_shape=(3,), kernel_regularizer=regularizers.get('l2'))) model.add(keras.layers.Dense(2, kernel_regularizer=regularizers.get('l2'))) self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertLen(loaded.layers, 2) self.assertLen(loaded.losses, 2) loaded.pop() self.assertLen(loaded.layers, 1) self.assertLen(loaded.losses, 1) loaded.add(keras.layers.Dense(2, kernel_regularizer=regularizers.get('l2'))) self.assertLen(loaded.layers, 2) self.assertLen(loaded.losses, 2) def testBatchNormUpdates(self): model = keras.models.Sequential( keras.layers.BatchNormalization(input_shape=(1,))) self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() with self.captureWritesToStream(sys.stderr) as captured_logs: model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) # Assert that saving does not log deprecation warnings # (even if it needs to set learning phase for compat reasons) if tf.executing_eagerly(): self.assertNotIn('deprecated', captured_logs.contents()) input_arr = tf.constant([[11], [12], [13]], dtype=tf.float32) input_arr2 = tf.constant([[14], [15], [16]], dtype=tf.float32) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0]) self.evaluate(loaded(input_arr, training=True)) if not tf.executing_eagerly(): self.evaluate(loaded.get_updates_for(input_arr)) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0.12]) self.evaluate(loaded(input_arr2, training=False)) if not tf.executing_eagerly(): self.evaluate(loaded.get_updates_for(input_arr2)) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0.12]) def testDisablingBatchNormTrainableBeforeSaving(self): # We disable trainable on the batchnorm layers before saving model = keras.models.Sequential( keras.layers.BatchNormalization(input_shape=(1,))) model.trainable = False self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.evaluate(tf.compat.v1.variables_initializer(loaded.variables)) input_arr = tf.constant([[11], [12], [13]], dtype=tf.float32) input_arr2 = tf.constant([[14], [15], [16]], dtype=tf.float32) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0]) # Trainable should still be disabled after loading self.evaluate(loaded(input_arr, training=True)) if not tf.executing_eagerly(): self.evaluate(loaded.get_updates_for(input_arr)) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0.0]) # Re-enabling trainable on the loaded model should cause the batchnorm # layer to start training again. # Note: this only works in v2. if tf.executing_eagerly(): loaded.trainable = True self.evaluate(loaded(input_arr, training=True)) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0.12]) self.evaluate(loaded(input_arr2, training=False)) self.assertAllClose(self.evaluate(loaded.layers[-1].moving_mean), [0.12]) def testSaveWithSignatures(self): model = keras.models.Sequential() model.add(keras.layers.Dense(5, input_shape=(3,), kernel_regularizer=regularizers.get('l2'))) model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(4, kernel_regularizer=regularizers.get('l2'))) input_arr = np.random.random((2, 3)) target_arr = np.random.random((2, 4)) model.compile( loss='mse', optimizer='rmsprop') model.train_on_batch(input_arr, target_arr) @tf.function(input_signature=[tf.TensorSpec((None, 3))]) def predict(inputs): return {'predictions': model(inputs)} feature_configs = { 'inputs': tf.io.FixedLenFeature( shape=[2, 3], dtype=tf.float32)} @tf.function( input_signature=[tf.TensorSpec([None], tf.string)]) def parse_and_predict(examples): features = tf.compat.v1.parse_single_example(examples[0], feature_configs) return {'predictions': model(features['inputs']), 'layer_1_outputs': model.layers[0](features['inputs'])} saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf', signatures={ 'predict': predict, 'parse_and_predict': parse_and_predict}) model.save('/tmp/saved', save_format='tf', signatures={ 'predict': predict, 'parse_and_predict': parse_and_predict}) loaded = keras_load.load(saved_model_dir) self.assertAllClose( model.predict(input_arr), loaded.signatures['predict'](tf.convert_to_tensor( input_arr.astype('float32')))['predictions']) feature = { 'inputs': feature_pb2.Feature( float_list=feature_pb2.FloatList( value=input_arr.astype('float32').flatten()))} example = example_pb2.Example( features=feature_pb2.Features(feature=feature)) outputs = loaded.signatures['parse_and_predict']( tf.convert_to_tensor([example.SerializeToString()])) self.assertAllClose(model.predict(input_arr), outputs['predictions']) self.assertAllClose(model.layers[0](input_arr), outputs['layer_1_outputs']) def testTrainingDefaults(self): def assert_training_default(fn, default_value): arg_spec = tf_inspect.getfullargspec(fn) index = len(arg_spec.args) - arg_spec.args.index('training') self.assertEqual(arg_spec.defaults[-index], default_value) class LayerWithTrainingRequiredArg(keras.engine.base_layer.Layer): def call(self, inputs, training): return control_flow_util.smart_cond(training, lambda: inputs * 0, lambda: tf.identity(inputs)) class LayerWithTrainingDefaultTrue(keras.engine.base_layer.Layer): def call(self, inputs, training=True): return control_flow_util.smart_cond(training, lambda: inputs * 0, lambda: tf.identity(inputs)) class Model(keras.models.Model): def __init__(self): super(Model, self).__init__() self.layer_with_training_default_none = LayerWithLearningPhase() self.layer_with_training_default_true = LayerWithTrainingDefaultTrue() self.layer_with_required_training_arg = LayerWithTrainingRequiredArg() def call(self, inputs): x = self.layer_with_training_default_none(inputs) x += self.layer_with_training_default_true(inputs) x += self.layer_with_required_training_arg(inputs, False) return x model = Model() # Build and set model inputs model.predict(np.ones([1, 3]).astype('float32')) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') load = tf.saved_model.load(saved_model_dir) # Ensure that the Keras loader is able to load and build the model. _ = keras_load.load(saved_model_dir) assert_training_default(load.__call__, False) assert_training_default( load.layer_with_training_default_none.__call__, False) assert_training_default( load.layer_with_training_default_true.__call__, True) # Assert that there are no defaults for layer with required training arg arg_spec = tf_inspect.getfullargspec( load.layer_with_required_training_arg.__call__) self.assertFalse(arg_spec.defaults) # defaults is None or empty def testTraceModelWithKwarg(self): class Model(keras.models.Model): def call(self, inputs, keyword=None): return tf.identity(inputs) model = Model() prediction = model.predict(np.ones([1, 3]).astype('float32')) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertAllClose(prediction, loaded.predict(np.ones([1, 3]).astype('float32'))) def testFeatureColumns(self): # TODO(b/120099662): Error with table initialization with Keras models in # graph mode. if tf.executing_eagerly(): numeric = tf.feature_column.numeric_column('a') bucketized = tf.feature_column.bucketized_column( numeric, boundaries=[5, 10, 15]) cat_vocab = tf.feature_column.categorical_column_with_vocabulary_list( 'b', ['1', '2', '3']) one_hot = tf.feature_column.indicator_column(cat_vocab) embedding = tf.feature_column.embedding_column(cat_vocab, dimension=8) feature_layer = DenseFeatures([bucketized, one_hot, embedding]) model = keras.models.Sequential(feature_layer) features = {'a': np.array([13, 15]), 'b': np.array(['1', '2'])} predictions = model.predict(features) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) loaded_predictions = loaded.predict(features) self.assertAllClose(predictions, loaded_predictions) def testSaveTensorKwarg(self): class LayerWithTensorKwarg(keras.layers.Layer): def call(self, inputs, tensor=None): if tensor is not None: return inputs * tf.cast(tensor, tf.float32) else: return inputs t = self.evaluate(tf.sequence_mask(1)) inputs = keras.layers.Input(shape=(3)) model = keras.models.Model(inputs, LayerWithTensorKwarg()(inputs, t)) input_arr = np.random.random((1, 3)) predictions = model.predict(input_arr) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) loaded_predictions = loaded.predict(input_arr) self.assertAllClose(predictions, loaded_predictions) def testModelWithTfFunctionCall(self): class Subclass(keras.models.Model): @tf.function def call(self, inputs, training=False): return inputs * tf.cast(training, tf.float32) model = Subclass() model.predict(tf.ones((1, 2)), steps=1) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertAllEqual( [[1, 5]], self.evaluate(loaded(tf.constant([[1, 5.]]), training=True))) self.assertAllEqual( [[0, 0]], self.evaluate(loaded(tf.constant([[1, 5.]]), training=False))) def testReviveFunctionalModel(self): class CustomAdd(keras.layers.Add): def build(self, input_shape): self.w = self.add_weight('w', shape=[]) super(CustomAdd, self).build(input_shape) def call(self, inputs): outputs = super(CustomAdd, self).call(inputs) return outputs * self.w input1 = keras.layers.Input(shape=(None, 3), name='input_1') input2 = keras.layers.Input(shape=(None, 3), name='input_2') d = keras.layers.Dense(4, name='dense_with_two_inbound_nodes') output1 = d(input1) output2 = d(input2) # Use a custom layer in this model to ensure that layers aren't being # recreated directly from the config. outputs = CustomAdd(name='custom')([output1, output2]) model = keras.models.Model([input1, input2], outputs, name='save_model') self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertEqual('save_model', loaded.name) self.assertLen( loaded.get_layer('dense_with_two_inbound_nodes')._inbound_nodes, 2) self.assertEqual('CustomAdd', type(loaded.get_layer('custom')).__name__) self.assertLen(loaded.get_layer('custom').weights, 1) def _testAddUpdate(self, scope): with scope: layer_with_update = LayerWithUpdate() model = testing_utils.get_model_from_layers([layer_with_update], input_shape=(3,)) x = np.ones((10, 3)) if testing_utils.get_model_type() == 'subclass': model.predict(x, batch_size=10) self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) loaded_layer = loaded.layers[-1] self.evaluate(tf.compat.v1.variables_initializer(loaded.variables)) self.assertEqual(self.evaluate(loaded_layer.v), 0.) loaded.compile('sgd', 'mse') loaded.fit(x, x, batch_size=10) self.assertEqual(self.evaluate(loaded_layer.v), 1.) @keras_parameterized.run_with_all_model_types def testSaveLayerWithUpdates(self): @tf_contextlib.contextmanager def nullcontextmanager(): yield self._testAddUpdate(nullcontextmanager()) @keras_parameterized.run_with_all_model_types def testSaveInStrategyScope(self): self._testAddUpdate(tf.distribute.MirroredStrategy().scope()) def testSaveTimeDistributedLayer(self): model = keras.Sequential([ keras.layers.TimeDistributed( keras.layers.Dense(1, kernel_regularizer=regularizers.get('l2')), input_shape=(None, 1))]) predictions = model.predict_on_batch(tf.ones((3, 2, 1))) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertAllClose(loaded.predict_on_batch(tf.ones((3, 2, 1))), predictions) @parameterized.named_parameters([ ('with_unrolling', True), ('no_unrolling', False) ]) def testSaveStatefulRNN(self, unroll): batch = 12 timesteps = 10 input_dim = 8 input_arr = np.ones((batch, timesteps, input_dim)).astype('float32') cells = [keras.layers.LSTMCell(32), keras.layers.LSTMCell(64)] if unroll: x = keras.Input(batch_shape=(batch, timesteps, input_dim)) else: x = keras.Input(batch_shape=(batch, None, input_dim)) layer = keras.layers.RNN(cells, stateful=True, unroll=unroll) y = layer(x) model = keras.Model(x, y) model.compile('rmsprop', 'mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, timesteps, input_dim)).astype('float32'), np.zeros((batch, 64)).astype('float32')) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) loaded_layer = loaded.layers[1] if not tf.executing_eagerly(): keras.backend.get_session() # force variable initialization self.assertAllClose(layer.states, loaded_layer.states) self.assertAllClose(model(input_arr), loaded(input_arr)) @parameterized.named_parameters([('stateful', True), ('stateless', False)]) def testSaveConvLSTM2D(self, stateful): data_format = 'channels_first' batch, timesteps, channels, rows, cols = 12, 10, 8, 4, 4 input_arr = np.ones( (batch, timesteps, channels, rows, cols)).astype('float32') layer = keras.layers.ConvLSTM2D( filters=16, kernel_size=(1, 1), data_format=data_format, stateful=stateful) x = keras.Input(batch_shape=(batch, timesteps, channels, rows, cols)) y = layer(x) model = keras.Model(x, y) predict_1 = model(input_arr) self.evaluate([v.initializer for v in model.variables]) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') del model loaded = keras_load.load(saved_model_dir) self.evaluate([v.initializer for v in loaded.variables]) if stateful: loaded.reset_states() predict_2 = loaded(input_arr) self.assertAllClose(predict_1, predict_2) def testSaveWithRaggedInputs(self): class EmbeddingMerger(keras.layers.Layer): def __init__(self, list_features, **kwargs): super().__init__(**kwargs) self._supports_ragged_inputs = True self.embeddings = { feature: keras.layers.Embedding(10, 3) for feature in list_features} self.mean = keras.layers.Lambda( tf.reduce_mean, arguments=dict(axis=1)) def call(self, inputs): tensors = [self.embeddings[col](inputs[col]) for col in inputs] tensors = [self.mean(inp) for inp in tensors] return keras.layers.Add()(tensors) list_features = ['feature_1', 'feature_2'] feature_1 = tf.ragged.constant([[0.], [1, 3]]) feature_2 = tf.ragged.constant([[1., 2], [4]]) f = {'feature_1': feature_1, 'feature_2': feature_2} f_inputs = { 'feature_1': keras.Input(shape=(None,), name='feature_1', ragged=True), 'feature_2': keras.Input(shape=(None,), name='feature_2', ragged=True)} out = EmbeddingMerger(list_features)(f_inputs) model = keras.Model(f_inputs, out) self.evaluate(tf.compat.v1.variables_initializer(model.variables)) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.evaluate(tf.compat.v1.variables_initializer(loaded.variables)) self.assertAllClose(model.predict(f), loaded.predict(f)) def testSaveMultipleInputs(self): class CustomLayer(keras.layers.Layer): def call(self, *input_list): self.add_loss(input_list[-2] * 2, inputs=True) return sum(input_list[:-1]) # The test's last input is a non-tensor arg class CustomModel(keras.Model): def build(self, _): self.layer = CustomLayer() def call(self, *inputs): inputs = list(inputs) inputs.append(object()) # Test that the layer handles non-tensor inputs return self.layer(*inputs) model = CustomModel() inp = [tf.constant(i, shape=[1, 1], dtype=tf.float32) for i in range(1, 5)] expected = model(*inp) expected_loss = model.get_losses_for(inp) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) actual = loaded(*inp) actual_loss = loaded.get_losses_for(inp) self.assertAllEqual(self.evaluate(expected), self.evaluate(actual)) self.assertAllEqual(self.evaluate(expected_loss), self.evaluate(actual_loss)) def test_wrapped_layer_training(self): class Custom(keras.models.Model): def __init__(self): super(Custom, self).__init__() self.layer = LayerWithLearningPhase() def call(self, inputs): return self.layer(inputs) model = Custom() x = tf.constant(1., shape=[1, 1]) expected_default = model(x) expected_training_true = model(x, training=True) expected_training_false = model(x, training=False) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') def assert_loaded_model(loaded): actual_default = loaded(x) actual_training_true = loaded(x, training=True) actual_training_false = loaded(x, training=False) self.assertAllClose( [expected_default, expected_training_true, expected_training_false], [actual_default, actual_training_true, actual_training_false]) assert_loaded_model(keras_load.load(saved_model_dir)) assert_loaded_model(tf.saved_model.load(saved_model_dir)) class TestSavedModelFormat(tf.test.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def test_load_with_partially_failed_serialization(self): class BadCustomLayer(keras.layers.Layer): def __call__(self, inputs): return inputs class Model(keras.models.Model): def __init__(self): super(Model, self).__init__() self.layer = BadCustomLayer() @tf.function( input_signature=[tf.TensorSpec([None, 1])]) def call(self, inputs): return self.layer(inputs) model = Model() inp = tf.constant([[1.0]]) model(inp) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') loaded = keras_load.load(saved_model_dir) self.assertAllEqual([[1.0]], self.evaluate(loaded(inp))) with self.assertRaisesRegex(ValueError, 'call function was not serialized'): loaded.layer(inp) def test_save_without_tracing(self): class DoNotTrace(keras.layers.Layer): def __init__(self): super(DoNotTrace, self).__init__() self.input_spec = keras.layers.InputSpec(shape=[None]) self.built = True def call(self, inputs): raise ValueError('I said do not trace') def get_config(self): return {} @property def _use_input_spec_as_call_signature(self): return True root = keras.models.Sequential() root.add(keras.layers.Input(shape=(3,))) root.attached_layer = DoNotTrace() saved_model_dir = self._save_model_dir() # With the default settings, the call function is traced. with self.assertRaisesRegex(ValueError, 'do not trace'): root.save(saved_model_dir, save_format='tf') # When saving the config only, the layer call function should not be not # traced. root.save(saved_model_dir, save_format='tf', save_traces=False) loaded = tf.saved_model.load(saved_model_dir) self.assertTrue(hasattr(loaded, 'attached_layer')) # This should raise an error when loaded without the custom object loaded = keras_load.load(saved_model_dir) with self.assertRaisesRegex(ValueError, 'Cannot call custom layer'): loaded.attached_layer(tf.constant([1.])) # Try loading with the custom objects with generic_utils.CustomObjectScope({'DoNotTrace': DoNotTrace}): loaded = keras_load.load(saved_model_dir) with self.assertRaisesRegex(ValueError, 'I said do not trace'): loaded.attached_layer(tf.constant([1.])) def test_load_non_keras_saved_model(self): model = testing_utils.get_small_functional_mlp(1, 4, input_dim=3) saved_model_dir = self._save_model_dir() tf.saved_model.save(model, saved_model_dir) with self.assertRaisesRegex(ValueError, 'Unable to create a Keras model'): keras_load.load(saved_model_dir) class TestLayerCallTracing(tf.test.TestCase, parameterized.TestCase): def test_functions_have_same_trace(self): class Layer(keras.engine.base_layer.Layer): def call(self, inputs): return inputs def call2(self, inputs): return inputs * 2 layer = Layer() call_collection = keras_save.LayerCallCollection(layer) fn = call_collection.add_function(layer.call, 'call', True) fn2 = call_collection.add_function(layer.call2, 'call2', True) with keras_save.tracing_scope(): fn(np.ones((2, 3))) fn(np.ones((4, 5))) self.assertLen( fn.wrapped_call._list_all_concrete_functions_for_serialization(), 2) self.assertLen( fn2.wrapped_call._list_all_concrete_functions_for_serialization(), 2) # Check that the shapes are correct self.assertEqual( {(2, 3), (4, 5)}, set(tuple(c.structured_input_signature[0][0].shape.as_list()) for c in fn2.wrapped_call._list_all_concrete_functions_for_serialization())) def test_training_arg_replacement(self): def assert_num_traces(layer_cls, training_keyword): layer = layer_cls() call_collection = keras_save.LayerCallCollection(layer) fn = call_collection.add_function(layer.call, 'call', True) with keras_save.tracing_scope(): fn(np.ones((2, 3)), training=True) self.assertLen( fn.wrapped_call._list_all_concrete_functions_for_serialization(), 2) with keras_save.tracing_scope(): fn(np.ones((2, 4)), training=False) self.assertLen( fn.wrapped_call._list_all_concrete_functions_for_serialization(), 4) if training_keyword: with keras_save.tracing_scope(): fn(np.ones((2, 5)), True) self.assertLen( fn.wrapped_call._list_all_concrete_functions_for_serialization(), 6) with keras_save.tracing_scope(): fn(np.ones((2, 6))) self.assertLen( fn.wrapped_call._list_all_concrete_functions_for_serialization(), 8) class LayerWithTrainingKeyword(keras.engine.base_layer.Layer): def call(self, inputs, training=False): return inputs * training assert_num_traces(LayerWithTrainingKeyword, training_keyword=True) class LayerWithKwargs(keras.engine.base_layer.Layer): def call(self, inputs, **kwargs): return inputs * kwargs['training'] assert_num_traces(LayerWithKwargs, training_keyword=False) class LayerWithChildLayer(keras.engine.base_layer.Layer): def __init__(self): self.child = LayerWithKwargs() super(LayerWithChildLayer, self).__init__() def call(self, inputs): return self.child(inputs) assert_num_traces(LayerWithChildLayer, training_keyword=False) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_maintains_losses(self): layer = LayerWithLoss() layer(np.ones((2, 3))) previous_losses = layer.losses[:] call_collection = keras_save.LayerCallCollection(layer) fn = call_collection.add_function(layer.call, 'call', True) fn(np.ones((2, 3))) self.assertAllEqual(previous_losses, layer.losses) @generic_utils.register_keras_serializable('Testing') class CustomMeanMetric(keras.metrics.Mean): def update_state(self, *args): # pylint: disable=useless-super-delegation # Sometimes built-in metrics return an op in update_state. Custom # metrics don't support returning ops, so wrap the update_state method # while returning nothing. super(CustomMeanMetric, self).update_state(*args) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class MetricTest(tf.test.TestCase, parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def generate_inputs(self, num_tensor_args, shape=(1, 5)): return [ np.random.uniform(0, 1, shape).astype('float32') for _ in range(num_tensor_args) ] def _test_metric_save_and_load(self, metric, save_dir, num_tensor_args, shape=(1, 5), test_sample_weight=True): with self.cached_session(): model = testing_utils.get_model_from_layers( [keras.layers.Layer()], input_shape=[3], model_type='functional') model.saved_metric = metric model.save(save_dir, save_format='tf') loaded_model = keras_load.load(save_dir) loaded = loaded_model.saved_metric self.evaluate([v.initializer for v in loaded.variables]) self.assertEqual(metric.name, loaded.name) self.assertEqual(metric.dtype, loaded.dtype) inputs = self.generate_inputs(num_tensor_args, shape) actual = self.evaluate(metric(*inputs)) self.assertAllClose(actual, loaded(*inputs)) self.assertAllClose(metric.variables, loaded.variables) # Test with separate calls to update state and result. inputs = self.generate_inputs(num_tensor_args, shape) self.evaluate(metric.update_state(*inputs)) self.evaluate(loaded.update_state(*inputs)) actual = self.evaluate(metric.result()) self.assertAllClose(actual, loaded.result()) if test_sample_weight: # Test with sample weights input. inputs = self.generate_inputs(num_tensor_args, shape) sample_weight = self.generate_inputs(1, [])[0] inputs.append(sample_weight) actual = self.evaluate(metric(*inputs)) self.assertAllClose(actual, loaded(*inputs)) return loaded @parameterized.named_parameters([ ('mean', keras.metrics.Mean, 1, (1, 5)), ('false_positives', keras.metrics.FalsePositives, 2, (1, 5)), ('precision_at_top_k', keras.metrics.Precision, 2, (2, 3, 4), { 'top_k': 2, 'class_id': 1 }), ('precision_at_recall', keras.metrics.PrecisionAtRecall, 2, (1, 5), { 'recall': .8 }), ('auc', keras.metrics.AUC, 2, (1, 5), { 'multi_label': True }), ('cosine_similarity', keras.metrics.CosineSimilarity, 2, (2, 3, 1)) ]) def test_metric(self, metric_cls, num_tensor_args, shape, init_kwargs=None): init_kwargs = init_kwargs or {} metric = metric_cls(**init_kwargs) metric(*self.generate_inputs(num_tensor_args, shape)) self.evaluate([v.initializer for v in metric.variables]) loaded = self._test_metric_save_and_load(metric, self._save_model_dir(), num_tensor_args, shape) self.assertEqual(type(loaded), type(metric)) @parameterized.named_parameters([ ('mean', keras.metrics.Mean, 1, False), ('auc', keras.metrics.AUC, 2, False), ('mean_tensor', keras.metrics.MeanTensor, 1, True)]) def test_custom_metric(self, base_cls, num_tensor_args, requires_build): class CustomMetric(base_cls): def update_state(self, *args): # pylint: disable=useless-super-delegation # Sometimes built-in metrics return an op in update_state. Custom # metrics don't support returning ops, so wrap the update_state method # while returning nothing. super(CustomMetric, self).update_state(*args) with self.cached_session(): metric = CustomMetric() save_dir = self._save_model_dir('first_save') if requires_build: metric(*self.generate_inputs(num_tensor_args)) # pylint: disable=not-callable self.evaluate([v.initializer for v in metric.variables]) with self.assertRaisesRegex(ValueError, 'Unable to restore custom object'): self._test_metric_save_and_load(metric, save_dir, num_tensor_args) with generic_utils.CustomObjectScope({'CustomMetric': CustomMetric}): loaded = self._test_metric_save_and_load( metric, save_dir, num_tensor_args, test_sample_weight=False) self._test_metric_save_and_load( loaded, self._save_model_dir('second_save'), num_tensor_args, test_sample_weight=False) def test_registered_custom_metric(self): with self.cached_session(): metric = CustomMeanMetric() save_dir = self._save_model_dir('first_save') self.evaluate([v.initializer for v in metric.variables]) loaded = self._test_metric_save_and_load( metric, save_dir, num_tensor_args=1, test_sample_weight=False) self._test_metric_save_and_load( loaded, self._save_model_dir('second_save'), num_tensor_args=1, test_sample_weight=False) def test_custom_metric_wrapped_call(self): class NegativeMean(keras.metrics.Mean): @tf.function( input_signature=[tf.TensorSpec(None, tf.float32)]) def update_state(self, value): super(NegativeMean, self).update_state(-value) metric = NegativeMean() self.evaluate([v.initializer for v in metric.variables]) with generic_utils.CustomObjectScope({'NegativeMean': NegativeMean}): self._test_metric_save_and_load( metric, self._save_model_dir(), 1, test_sample_weight=False) @keras_parameterized.run_with_all_model_types def test_custom_metric_model(self): # TODO(b/134519980): Issue with `model.fit` if the model call function uses # a `tf.function` in graph mode. if not tf.executing_eagerly(): return x = np.random.random((1, 3)) y = np.random.random((1, 4)) class CustomMetric(keras.metrics.MeanSquaredError): pass def zero_metric(y_true, y_pred): del y_true, y_pred return 0 model = testing_utils.get_small_mlp(1, 4, input_dim=3) model.compile(loss='mse', optimizer='SGD', metrics=[CustomMetric(), zero_metric]) model.fit(x, y) saved_model_dir = self._save_model_dir() model.save(saved_model_dir, save_format='tf') with self.assertRaisesRegex(ValueError, 'custom_objects'): keras_load.load(saved_model_dir) with generic_utils.CustomObjectScope( {'CustomMetric': CustomMetric, 'zero_metric': zero_metric}): loaded = keras_load.load(saved_model_dir) self.evaluate([v.initializer for v in loaded.variables]) loaded.fit(x, y) class TestUpdateMetadata(tf.test.TestCase): def testAddFullSaveSpec(self): save_spec = tf.TensorSpec([3, 5], dtype=tf.int32) node_metadata = json_utils.Encoder().encode({'save_spec': save_spec}) metadata = saved_metadata_pb2.SavedMetadata() metadata.nodes.add( version=versions_pb2.VersionDef( producer=1, min_consumer=1, bad_consumers=[]), identifier='_tf_keras_model', metadata=node_metadata) # pylint: disable=protected-access new_metadata = keras_load._update_to_current_version(metadata) node_metadata = json_utils.decode(new_metadata.nodes[0].metadata) expected_full_spec = ([tf.TensorSpec(shape=(3, 5), dtype=tf.int32)], {}) self.assertAllEqual(expected_full_spec, node_metadata.get('full_save_spec')) if __name__ == '__main__': tf.test.main()
50,333
36.395245
86
py
keras
keras-master/keras/saving/saved_model/load_context.py
# 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. # ============================================================================== """Context for storing options for loading a SavedModel.""" import contextlib import threading class LoadContext(threading.local): """A context for loading a model.""" def __init__(self): super(LoadContext, self).__init__() self._load_options = None def set_load_options(self, load_options): self._load_options = load_options def clear_load_options(self): self._load_options = None def load_options(self): return self._load_options _load_context = LoadContext() @contextlib.contextmanager def load_context(load_options): _load_context.set_load_options(load_options) try: yield finally: _load_context.clear_load_options() def get_load_options(): """Returns whether under a load context.""" return _load_context.load_options()
1,475
26.849057
80
py
keras
keras-master/keras/saving/saved_model/network_serialization.py
# 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. # ============================================================================== """Classes and functions implementing to Network SavedModel serialization.""" from keras.saving.saved_model import constants from keras.saving.saved_model import model_serialization # FunctionalModel serialization is pretty much the same as Model serialization. class NetworkSavedModelSaver(model_serialization.ModelSavedModelSaver): """Network serialization.""" @property def object_identifier(self): return constants.NETWORK_IDENTIFIER
1,141
39.785714
80
py
keras
keras-master/keras/saving/saved_model/create_test_saved_model.py
"""A binary that creates a serialized SavedModel from a keras model. This is used in tests to ensure that model serialization is deterministic across different processes. """ from absl import app from absl import flags from keras import regularizers from keras import testing_utils import tensorflow.compat.v2 as tf flags.DEFINE_string('output_path', '', 'The path to write the SavedModel at.') FLAGS = flags.FLAGS def main(_) -> None: with testing_utils.model_type_scope('functional'): model = testing_utils.get_small_mlp(1, 4, input_dim=3) model.layers[-1].activity_regularizer = regularizers.get('l2') model.activity_regularizer = regularizers.get('l2') model.compile( loss='mse', optimizer='rmsprop') def callable_loss(): return tf.reduce_sum(model.weights[0]) model.add_loss(callable_loss) print(f'_____Writing saved model to: {FLAGS.output_path}') model.save(FLAGS.output_path) if __name__ == '__main__': app.run(main)
993
25.864865
80
py
keras
keras-master/keras/datasets/cifar100.py
# 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. # ============================================================================== """CIFAR100 small images classification dataset.""" import os import numpy as np from keras import backend from keras.datasets.cifar import load_batch from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.cifar100.load_data') def load_data(label_mode='fine'): """Loads the CIFAR100 dataset. This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 100 fine-grained classes that are grouped into 20 coarse-grained classes. See more info at the [CIFAR homepage](https://www.cs.toronto.edu/~kriz/cifar.html). Args: label_mode: one of "fine", "coarse". If it is "fine" the category labels are the fine-grained labels, if it is "coarse" the output labels are the coarse-grained superclasses. Returns: Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train**: uint8 NumPy array of grayscale image data with shapes `(50000, 32, 32, 3)`, containing the training data. Pixel values range from 0 to 255. **y_train**: uint8 NumPy array of labels (integers in range 0-99) with shape `(50000, 1)` for the training data. **x_test**: uint8 NumPy array of grayscale image data with shapes (10000, 32, 32, 3), containing the test data. Pixel values range from 0 to 255. **y_test**: uint8 NumPy array of labels (integers in range 0-99) with shape `(10000, 1)` for the test data. Example: ```python (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data() assert x_train.shape == (50000, 32, 32, 3) assert x_test.shape == (10000, 32, 32, 3) assert y_train.shape == (50000, 1) assert y_test.shape == (10000, 1) ``` """ if label_mode not in ['fine', 'coarse']: raise ValueError('`label_mode` must be one of `"fine"`, `"coarse"`. ' f'Received: label_mode={label_mode}.') dirname = 'cifar-100-python' origin = 'https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz' path = get_file( dirname, origin=origin, untar=True, file_hash= '85cd44d02ba6437773c5bbd22e183051d648de2e7d6b014e1ef29b855ba677a7') fpath = os.path.join(path, 'train') x_train, y_train = load_batch(fpath, label_key=label_mode + '_labels') fpath = os.path.join(path, 'test') x_test, y_test = load_batch(fpath, label_key=label_mode + '_labels') y_train = np.reshape(y_train, (len(y_train), 1)) y_test = np.reshape(y_test, (len(y_test), 1)) if backend.image_data_format() == 'channels_last': x_train = x_train.transpose(0, 2, 3, 1) x_test = x_test.transpose(0, 2, 3, 1) return (x_train, y_train), (x_test, y_test)
3,387
34.663158
80
py
keras
keras-master/keras/datasets/imdb.py
# 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. # ============================================================================== """IMDB sentiment classification dataset.""" import json import numpy as np from keras.preprocessing.sequence import _remove_long_seq from keras.utils.data_utils import get_file from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.imdb.load_data') def load_data(path='imdb.npz', num_words=None, skip_top=0, maxlen=None, seed=113, start_char=1, oov_char=2, index_from=3, **kwargs): """Loads the [IMDB dataset](https://ai.stanford.edu/~amaas/data/sentiment/). This is a dataset of 25,000 movies reviews from IMDB, labeled by sentiment (positive/negative). Reviews have been preprocessed, and each review is encoded as a list of word indexes (integers). For convenience, words are indexed by overall frequency in the dataset, so that for instance the integer "3" encodes the 3rd most frequent word in the data. This allows for quick filtering operations such as: "only consider the top 10,000 most common words, but eliminate the top 20 most common words". As a convention, "0" does not stand for a specific word, but instead is used to encode any unknown word. Args: path: where to cache the data (relative to `~/.keras/dataset`). num_words: integer or None. Words are ranked by how often they occur (in the training set) and only the `num_words` most frequent words are kept. Any less frequent word will appear as `oov_char` value in the sequence data. If None, all words are kept. Defaults to None, so all words are kept. skip_top: skip the top N most frequently occurring words (which may not be informative). These words will appear as `oov_char` value in the dataset. Defaults to 0, so no words are skipped. maxlen: int or None. Maximum sequence length. Any longer sequence will be truncated. Defaults to None, which means no truncation. seed: int. Seed for reproducible data shuffling. start_char: int. The start of a sequence will be marked with this character. Defaults to 1 because 0 is usually the padding character. oov_char: int. The out-of-vocabulary character. Words that were cut out because of the `num_words` or `skip_top` limits will be replaced with this character. index_from: int. Index actual words with this index and higher. **kwargs: Used for backwards compatibility. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train, x_test**: lists of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is `num_words - 1`. If the `maxlen` argument was specified, the largest possible sequence length is `maxlen`. **y_train, y_test**: lists of integer labels (1 or 0). Raises: ValueError: in case `maxlen` is so low that no input sequence could be kept. Note that the 'out of vocabulary' character is only used for words that were present in the training set but are not included because they're not making the `num_words` cut here. Words that were not seen in the training set but are in the test set have simply been skipped. """ # Legacy support if 'nb_words' in kwargs: logging.warning('The `nb_words` argument in `load_data` ' 'has been renamed `num_words`.') num_words = kwargs.pop('nb_words') if kwargs: raise TypeError(f'Unrecognized keyword arguments: {str(kwargs)}.') origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'imdb.npz', file_hash= '69664113be75683a8fe16e3ed0ab59fda8886cb3cd7ada244f7d9544e4676b9f') with np.load(path, allow_pickle=True) as f: # pylint: disable=unexpected-keyword-arg x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test'] rng = np.random.RandomState(seed) indices = np.arange(len(x_train)) rng.shuffle(indices) x_train = x_train[indices] labels_train = labels_train[indices] indices = np.arange(len(x_test)) rng.shuffle(indices) x_test = x_test[indices] labels_test = labels_test[indices] if start_char is not None: x_train = [[start_char] + [w + index_from for w in x] for x in x_train] x_test = [[start_char] + [w + index_from for w in x] for x in x_test] elif index_from: x_train = [[w + index_from for w in x] for x in x_train] x_test = [[w + index_from for w in x] for x in x_test] if maxlen: x_train, labels_train = _remove_long_seq(maxlen, x_train, labels_train) x_test, labels_test = _remove_long_seq(maxlen, x_test, labels_test) if not x_train or not x_test: raise ValueError('After filtering for sequences shorter than maxlen=' f'{str(maxlen)}, no sequence was kept. Increase maxlen.') xs = x_train + x_test labels = np.concatenate([labels_train, labels_test]) if not num_words: num_words = max(max(x) for x in xs) # by convention, use 2 as OOV word # reserve 'index_from' (=3 by default) characters: # 0 (padding), 1 (start), 2 (OOV) if oov_char is not None: xs = [ [w if (skip_top <= w < num_words) else oov_char for w in x] for x in xs ] else: xs = [[w for w in x if skip_top <= w < num_words] for x in xs] idx = len(x_train) x_train, y_train = np.array(xs[:idx], dtype='object'), labels[:idx] x_test, y_test = np.array(xs[idx:], dtype='object'), labels[idx:] return (x_train, y_train), (x_test, y_test) @keras_export('keras.datasets.imdb.get_word_index') def get_word_index(path='imdb_word_index.json'): """Retrieves a dict mapping words to their index in the IMDB dataset. Args: path: where to cache the data (relative to `~/.keras/dataset`). Returns: The word index dictionary. Keys are word strings, values are their index. Example: ```python # Retrieve the training sequences. (x_train, _), _ = keras.datasets.imdb.load_data() # Retrieve the word index file mapping words to indices word_index = keras.datasets.imdb.get_word_index() # Reverse the word index to obtain a dict mapping indices to words inverted_word_index = dict((i, word) for (word, i) in word_index.items()) # Decode the first sequence in the dataset decoded_sequence = " ".join(inverted_word_index[i] for i in x_train[0]) ``` """ origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'imdb_word_index.json', file_hash='bfafd718b763782e994055a2d397834f') with open(path) as f: return json.load(f)
7,524
38.814815
87
py
keras
keras-master/keras/datasets/fashion_mnist.py
# Copyright 2017 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. # ============================================================================== """Fashion-MNIST dataset.""" import gzip import os import numpy as np from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.fashion_mnist.load_data') def load_data(): """Loads the Fashion-MNIST dataset. This is a dataset of 60,000 28x28 grayscale images of 10 fashion categories, along with a test set of 10,000 images. This dataset can be used as a drop-in replacement for MNIST. The classes are: | Label | Description | |:-----:|-------------| | 0 | T-shirt/top | | 1 | Trouser | | 2 | Pullover | | 3 | Dress | | 4 | Coat | | 5 | Sandal | | 6 | Shirt | | 7 | Sneaker | | 8 | Bag | | 9 | Ankle boot | Returns: Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train**: uint8 NumPy array of grayscale image data with shapes `(60000, 28, 28)`, containing the training data. **y_train**: uint8 NumPy array of labels (integers in range 0-9) with shape `(60000,)` for the training data. **x_test**: uint8 NumPy array of grayscale image data with shapes (10000, 28, 28), containing the test data. **y_test**: uint8 NumPy array of labels (integers in range 0-9) with shape `(10000,)` for the test data. Example: ```python (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() assert x_train.shape == (60000, 28, 28) assert x_test.shape == (10000, 28, 28) assert y_train.shape == (60000,) assert y_test.shape == (10000,) ``` License: The copyright for Fashion-MNIST is held by Zalando SE. Fashion-MNIST is licensed under the [MIT license]( https://github.com/zalandoresearch/fashion-mnist/blob/master/LICENSE). """ dirname = os.path.join('datasets', 'fashion-mnist') base = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' files = [ 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz' ] paths = [] for fname in files: paths.append(get_file(fname, origin=base + fname, cache_subdir=dirname)) with gzip.open(paths[0], 'rb') as lbpath: y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8) with gzip.open(paths[1], 'rb') as imgpath: x_train = np.frombuffer( imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28) with gzip.open(paths[2], 'rb') as lbpath: y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8) with gzip.open(paths[3], 'rb') as imgpath: x_test = np.frombuffer( imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28) return (x_train, y_train), (x_test, y_test)
3,444
31.5
80
py
keras
keras-master/keras/datasets/cifar10.py
# 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. # ============================================================================== """CIFAR10 small images classification dataset.""" import os import numpy as np from keras import backend from keras.datasets.cifar import load_batch from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.cifar10.load_data') def load_data(): """Loads the CIFAR10 dataset. This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 10 categories. See more info at the [CIFAR homepage](https://www.cs.toronto.edu/~kriz/cifar.html). The classes are: | Label | Description | |:-----:|-------------| | 0 | airplane | | 1 | automobile | | 2 | bird | | 3 | cat | | 4 | deer | | 5 | dog | | 6 | frog | | 7 | horse | | 8 | ship | | 9 | truck | Returns: Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train**: uint8 NumPy array of grayscale image data with shapes `(50000, 32, 32, 3)`, containing the training data. Pixel values range from 0 to 255. **y_train**: uint8 NumPy array of labels (integers in range 0-9) with shape `(50000, 1)` for the training data. **x_test**: uint8 NumPy array of grayscale image data with shapes (10000, 32, 32, 3), containing the test data. Pixel values range from 0 to 255. **y_test**: uint8 NumPy array of labels (integers in range 0-9) with shape `(10000, 1)` for the test data. Example: ```python (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() assert x_train.shape == (50000, 32, 32, 3) assert x_test.shape == (10000, 32, 32, 3) assert y_train.shape == (50000, 1) assert y_test.shape == (10000, 1) ``` """ dirname = 'cifar-10-batches-py' origin = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' path = get_file( dirname, origin=origin, untar=True, file_hash= '6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce') num_train_samples = 50000 x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8') y_train = np.empty((num_train_samples,), dtype='uint8') for i in range(1, 6): fpath = os.path.join(path, 'data_batch_' + str(i)) (x_train[(i - 1) * 10000:i * 10000, :, :, :], y_train[(i - 1) * 10000:i * 10000]) = load_batch(fpath) fpath = os.path.join(path, 'test_batch') x_test, y_test = load_batch(fpath) y_train = np.reshape(y_train, (len(y_train), 1)) y_test = np.reshape(y_test, (len(y_test), 1)) if backend.image_data_format() == 'channels_last': x_train = x_train.transpose(0, 2, 3, 1) x_test = x_test.transpose(0, 2, 3, 1) x_test = x_test.astype(x_train.dtype) y_test = y_test.astype(y_train.dtype) return (x_train, y_train), (x_test, y_test)
3,548
31.263636
80
py
keras
keras-master/keras/datasets/__init__.py
"""Small NumPy datasets for debugging/testing."""
50
24.5
49
py
keras
keras-master/keras/datasets/reuters.py
# 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. # ============================================================================== """Reuters topic classification dataset.""" import json import numpy as np from keras.preprocessing.sequence import _remove_long_seq from keras.utils.data_utils import get_file from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.reuters.load_data') def load_data(path='reuters.npz', num_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2, index_from=3, **kwargs): """Loads the Reuters newswire classification dataset. This is a dataset of 11,228 newswires from Reuters, labeled over 46 topics. This was originally generated by parsing and preprocessing the classic Reuters-21578 dataset, but the preprocessing code is no longer packaged with Keras. See this [github discussion](https://github.com/keras-team/keras/issues/12072) for more info. Each newswire is encoded as a list of word indexes (integers). For convenience, words are indexed by overall frequency in the dataset, so that for instance the integer "3" encodes the 3rd most frequent word in the data. This allows for quick filtering operations such as: "only consider the top 10,000 most common words, but eliminate the top 20 most common words". As a convention, "0" does not stand for a specific word, but instead is used to encode any unknown word. Args: path: where to cache the data (relative to `~/.keras/dataset`). num_words: integer or None. Words are ranked by how often they occur (in the training set) and only the `num_words` most frequent words are kept. Any less frequent word will appear as `oov_char` value in the sequence data. If None, all words are kept. Defaults to None, so all words are kept. skip_top: skip the top N most frequently occurring words (which may not be informative). These words will appear as `oov_char` value in the dataset. Defaults to 0, so no words are skipped. maxlen: int or None. Maximum sequence length. Any longer sequence will be truncated. Defaults to None, which means no truncation. test_split: Float between 0 and 1. Fraction of the dataset to be used as test data. Defaults to 0.2, meaning 20% of the dataset is used as test data. seed: int. Seed for reproducible data shuffling. start_char: int. The start of a sequence will be marked with this character. Defaults to 1 because 0 is usually the padding character. oov_char: int. The out-of-vocabulary character. Words that were cut out because of the `num_words` or `skip_top` limits will be replaced with this character. index_from: int. Index actual words with this index and higher. **kwargs: Used for backwards compatibility. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train, x_test**: lists of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is `num_words - 1`. If the `maxlen` argument was specified, the largest possible sequence length is `maxlen`. **y_train, y_test**: lists of integer labels (1 or 0). Note: The 'out of vocabulary' character is only used for words that were present in the training set but are not included because they're not making the `num_words` cut here. Words that were not seen in the training set but are in the test set have simply been skipped. """ # Legacy support if 'nb_words' in kwargs: logging.warning('The `nb_words` argument in `load_data` ' 'has been renamed `num_words`.') num_words = kwargs.pop('nb_words') if kwargs: raise TypeError(f'Unrecognized keyword arguments: {str(kwargs)}') origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'reuters.npz', file_hash= 'd6586e694ee56d7a4e65172e12b3e987c03096cb01eab99753921ef915959916') with np.load(path, allow_pickle=True) as f: # pylint: disable=unexpected-keyword-arg xs, labels = f['x'], f['y'] rng = np.random.RandomState(seed) indices = np.arange(len(xs)) rng.shuffle(indices) xs = xs[indices] labels = labels[indices] if start_char is not None: xs = [[start_char] + [w + index_from for w in x] for x in xs] elif index_from: xs = [[w + index_from for w in x] for x in xs] if maxlen: xs, labels = _remove_long_seq(maxlen, xs, labels) if not num_words: num_words = max(max(x) for x in xs) # by convention, use 2 as OOV word # reserve 'index_from' (=3 by default) characters: # 0 (padding), 1 (start), 2 (OOV) if oov_char is not None: xs = [[w if skip_top <= w < num_words else oov_char for w in x] for x in xs] else: xs = [[w for w in x if skip_top <= w < num_words] for x in xs] idx = int(len(xs) * (1 - test_split)) x_train, y_train = np.array(xs[:idx], dtype='object'), np.array(labels[:idx]) x_test, y_test = np.array(xs[idx:], dtype='object'), np.array(labels[idx:]) return (x_train, y_train), (x_test, y_test) @keras_export('keras.datasets.reuters.get_word_index') def get_word_index(path='reuters_word_index.json'): """Retrieves a dict mapping words to their index in the Reuters dataset. Args: path: where to cache the data (relative to `~/.keras/dataset`). Returns: The word index dictionary. Keys are word strings, values are their index. """ origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'reuters_word_index.json', file_hash='4d44cc38712099c9e383dc6e5f11a921') with open(path) as f: return json.load(f)
6,605
38.795181
87
py
keras
keras-master/keras/datasets/cifar.py
# 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
1,341
30.209302
80
py
keras
keras-master/keras/datasets/boston_housing.py
# 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. # ============================================================================== """Boston housing price regression dataset.""" import numpy as np from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.boston_housing.load_data') def load_data(path='boston_housing.npz', test_split=0.2, seed=113): """Loads the Boston Housing dataset. This is a dataset taken from the StatLib library which is maintained at Carnegie Mellon University. Samples contain 13 attributes of houses at different locations around the Boston suburbs in the late 1970s. Targets are the median values of the houses at a location (in k$). The attributes themselves are defined in the [StatLib website](http://lib.stat.cmu.edu/datasets/boston). Args: path: path where to cache the dataset locally (relative to `~/.keras/datasets`). test_split: fraction of the data to reserve as test set. seed: Random seed for shuffling the data before computing the test split. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train, x_test**: numpy arrays with shape `(num_samples, 13)` containing either the training samples (for x_train), or test samples (for y_train). **y_train, y_test**: numpy arrays of shape `(num_samples,)` containing the target scalars. The targets are float scalars typically between 10 and 50 that represent the home prices in k$. """ assert 0 <= test_split < 1 origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'boston_housing.npz', file_hash= 'f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5') with np.load(path, allow_pickle=True) as f: # pylint: disable=unexpected-keyword-arg x = f['x'] y = f['y'] rng = np.random.RandomState(seed) indices = np.arange(len(x)) rng.shuffle(indices) x = x[indices] y = y[indices] x_train = np.array(x[:int(len(x) * (1 - test_split))]) y_train = np.array(y[:int(len(x) * (1 - test_split))]) x_test = np.array(x[int(len(x) * (1 - test_split)):]) y_test = np.array(y[int(len(x) * (1 - test_split)):]) return (x_train, y_train), (x_test, y_test)
2,913
36.844156
87
py
keras
keras-master/keras/datasets/mnist.py
# 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. # ============================================================================== """MNIST handwritten digits dataset.""" import numpy as np from keras.utils.data_utils import get_file from tensorflow.python.util.tf_export import keras_export @keras_export('keras.datasets.mnist.load_data') def load_data(path='mnist.npz'): """Loads the MNIST dataset. This is a dataset of 60,000 28x28 grayscale images of the 10 digits, along with a test set of 10,000 images. More info can be found at the [MNIST homepage](http://yann.lecun.com/exdb/mnist/). Args: path: path where to cache the dataset locally (relative to `~/.keras/datasets`). Returns: Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`. **x_train**: uint8 NumPy array of grayscale image data with shapes `(60000, 28, 28)`, containing the training data. Pixel values range from 0 to 255. **y_train**: uint8 NumPy array of digit labels (integers in range 0-9) with shape `(60000,)` for the training data. **x_test**: uint8 NumPy array of grayscale image data with shapes (10000, 28, 28), containing the test data. Pixel values range from 0 to 255. **y_test**: uint8 NumPy array of digit labels (integers in range 0-9) with shape `(10000,)` for the test data. Example: ```python (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() assert x_train.shape == (60000, 28, 28) assert x_test.shape == (10000, 28, 28) assert y_train.shape == (60000,) assert y_test.shape == (10000,) ``` License: Yann LeCun and Corinna Cortes hold the copyright of MNIST dataset, which is a derivative work from original NIST datasets. MNIST dataset is made available under the terms of the [Creative Commons Attribution-Share Alike 3.0 license.]( https://creativecommons.org/licenses/by-sa/3.0/) """ origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/' path = get_file( path, origin=origin_folder + 'mnist.npz', file_hash= '731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1') with np.load(path, allow_pickle=True) as f: # pylint: disable=unexpected-keyword-arg x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test'] return (x_train, y_train), (x_test, y_test)
2,958
35.530864
87
py
keras
keras-master/keras/tests/model_architectures.py
# 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 saving/loading function for keras Model.""" import collections import keras # Declaring namedtuple() ModelFn = collections.namedtuple('ModelFn', ['model', 'input_shape', 'target_shape']) def basic_sequential(): """Basic sequential model.""" model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def basic_sequential_deferred(): """Sequential model with deferred input shape.""" model = keras.Sequential([ keras.layers.Dense(3, activation='relu'), keras.layers.Dense(2, activation='softmax'), ]) return ModelFn(model, (None, 3), (None, 2)) def stacked_rnn(): """Stacked RNN model.""" inputs = keras.Input((None, 3)) layer = keras.layers.RNN([keras.layers.LSTMCell(2) for _ in range(3)]) x = layer(inputs) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def lstm(): """LSTM model.""" inputs = keras.Input((None, 3)) x = keras.layers.LSTM(4, return_sequences=True)(inputs) x = keras.layers.LSTM(3, return_sequences=True)(x) x = keras.layers.LSTM(2, return_sequences=False)(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2)) def multi_input_multi_output(): """Multi-input Multi-output model.""" body_input = keras.Input(shape=(None,), name='body') tags_input = keras.Input(shape=(2,), name='tags') x = keras.layers.Embedding(10, 4)(body_input) body_features = keras.layers.LSTM(5)(x) x = keras.layers.concatenate([body_features, tags_input]) pred_1 = keras.layers.Dense(2, activation='sigmoid', name='priority')(x) pred_2 = keras.layers.Dense(3, activation='softmax', name='department')(x) model = keras.Model( inputs=[body_input, tags_input], outputs=[pred_1, pred_2]) return ModelFn(model, [(None, 1), (None, 2)], [(None, 2), (None, 3)]) def nested_sequential_in_functional(): """A sequential model nested in a functional model.""" inner_model = keras.Sequential([ keras.layers.Dense(3, activation='relu', input_shape=(3,)), keras.layers.Dense(2, activation='relu'), ]) inputs = keras.Input(shape=(3,)) x = inner_model(inputs) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def seq_to_seq(): """Sequence to sequence model.""" num_encoder_tokens = 3 num_decoder_tokens = 3 latent_dim = 2 encoder_inputs = keras.Input(shape=(None, num_encoder_tokens)) encoder = keras.layers.LSTM(latent_dim, return_state=True) _, state_h, state_c = encoder(encoder_inputs) encoder_states = [state_h, state_c] decoder_inputs = keras.Input(shape=(None, num_decoder_tokens)) decoder_lstm = keras.layers.LSTM( latent_dim, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm( decoder_inputs, initial_state=encoder_states) decoder_dense = keras.layers.Dense(num_decoder_tokens, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) model = keras.Model([encoder_inputs, decoder_inputs], decoder_outputs) return ModelFn( model, [(None, 2, num_encoder_tokens), (None, 2, num_decoder_tokens)], (None, 2, num_decoder_tokens)) def shared_layer_functional(): """Shared layer in a functional model.""" main_input = keras.Input(shape=(10,), dtype='int32', name='main_input') x = keras.layers.Embedding( output_dim=5, input_dim=4, input_length=10)(main_input) lstm_out = keras.layers.LSTM(3)(x) auxiliary_output = keras.layers.Dense( 1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = keras.Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input]) x = keras.layers.Dense(2, activation='relu')(x) main_output = keras.layers.Dense( 1, activation='sigmoid', name='main_output')(x) model = keras.Model( inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) return ModelFn(model, [(None, 10), (None, 5)], [(None, 1), (None, 1)]) def shared_sequential(): """Shared sequential model in a functional model.""" inner_model = keras.Sequential([ keras.layers.Conv2D(2, 3, activation='relu'), keras.layers.Conv2D(2, 3, activation='relu'), ]) inputs_1 = keras.Input((5, 5, 3)) inputs_2 = keras.Input((5, 5, 3)) x1 = inner_model(inputs_1) x2 = inner_model(inputs_2) x = keras.layers.concatenate([x1, x2]) outputs = keras.layers.GlobalAveragePooling2D()(x) model = keras.Model([inputs_1, inputs_2], outputs) return ModelFn(model, [(None, 5, 5, 3), (None, 5, 5, 3)], (None, 4)) class MySubclassModel(keras.Model): """A subclass model.""" def __init__(self, input_dim=3): super(MySubclassModel, self).__init__(name='my_subclass_model') self._config = {'input_dim': input_dim} self.dense1 = keras.layers.Dense(8, activation='relu') self.dense2 = keras.layers.Dense(2, activation='softmax') self.bn = keras.layers.BatchNormalization() self.dp = keras.layers.Dropout(0.5) def call(self, inputs, **kwargs): x = self.dense1(inputs) x = self.dp(x) x = self.bn(x) return self.dense2(x) def get_config(self): return self._config @classmethod def from_config(cls, config): return cls(**config) def nested_subclassed_model(): """A subclass model nested in another subclass model.""" class NestedSubclassModel(keras.Model): """A nested subclass model.""" def __init__(self): super(NestedSubclassModel, self).__init__() self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.bn = keras.layers.BatchNormalization() self.inner_subclass_model = MySubclassModel() def call(self, inputs): x = self.dense1(inputs) x = self.bn(x) x = self.inner_subclass_model(x) return self.dense2(x) return ModelFn(NestedSubclassModel(), (None, 3), (None, 2)) def nested_subclassed_in_functional_model(): """A subclass model nested in a functional model.""" inner_subclass_model = MySubclassModel() inputs = keras.Input(shape=(3,)) x = inner_subclass_model(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2, activation='softmax')(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 3), (None, 2)) def nested_functional_in_subclassed_model(): """A functional model nested in a subclass model.""" def get_functional_model(): inputs = keras.Input(shape=(4,)) x = keras.layers.Dense(4, activation='relu')(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) return keras.Model(inputs, outputs) class NestedFunctionalInSubclassModel(keras.Model): """A functional nested in subclass model.""" def __init__(self): super(NestedFunctionalInSubclassModel, self).__init__( name='nested_functional_in_subclassed_model') self.dense1 = keras.layers.Dense(4, activation='relu') self.dense2 = keras.layers.Dense(2, activation='relu') self.inner_functional_model = get_functional_model() def call(self, inputs): x = self.dense1(inputs) x = self.inner_functional_model(x) return self.dense2(x) return ModelFn(NestedFunctionalInSubclassModel(), (None, 3), (None, 2)) def shared_layer_subclassed_model(): """Shared layer in a subclass model.""" class SharedLayerSubclassModel(keras.Model): """A subclass model with shared layers.""" def __init__(self): super(SharedLayerSubclassModel, self).__init__( name='shared_layer_subclass_model') self.dense = keras.layers.Dense(3, activation='relu') self.dp = keras.layers.Dropout(0.5) self.bn = keras.layers.BatchNormalization() def call(self, inputs): x = self.dense(inputs) x = self.dp(x) x = self.bn(x) return self.dense(x) return ModelFn(SharedLayerSubclassModel(), (None, 3), (None, 3)) def functional_with_keyword_args(): """A functional model with keyword args.""" inputs = keras.Input(shape=(3,)) x = keras.layers.Dense(4)(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs, name='m', trainable=False) return ModelFn(model, (None, 3), (None, 2)) ALL_MODELS = [ ('basic_sequential', basic_sequential), ('basic_sequential_deferred', basic_sequential_deferred), ('stacked_rnn', stacked_rnn), ('lstm', lstm), ('multi_input_multi_output', multi_input_multi_output), ('nested_sequential_in_functional', nested_sequential_in_functional), ('seq_to_seq', seq_to_seq), ('shared_layer_functional', shared_layer_functional), ('shared_sequential', shared_sequential), ('nested_subclassed_model', nested_subclassed_model), ('nested_subclassed_in_functional_model', nested_subclassed_in_functional_model), ('nested_functional_in_subclassed_model', nested_functional_in_subclassed_model), ('shared_layer_subclassed_model', shared_layer_subclassed_model), ('functional_with_keyword_args', functional_with_keyword_args) ] def get_models(exclude_models=None): """Get all models excluding the specified ones.""" models = [model for model in ALL_MODELS if model[0] not in exclude_models] return models
10,285
33.986395
80
py
keras
keras-master/keras/tests/model_subclassing_compiled_test.py
# 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 compiled Model subclassing.""" import tensorflow.compat.v2 as tf import os import numpy as np import keras from keras import keras_parameterized from keras import testing_utils from keras.tests import model_subclassing_test_util as model_util try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None @keras_parameterized.run_all_keras_modes class ModelSubclassCompiledTest(keras_parameterized.TestCase): def test_single_io_workflow_with_np_arrays(self): num_classes = 2 num_samples = 100 input_dim = 50 model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc', keras.metrics.CategoricalAccuracy()], run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim)) y = np.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, batch_size=32, verbose=0) _ = model.evaluate(x, y, verbose=0) def test_multi_io_workflow_with_np_arrays(self): num_classes = (2, 3) num_samples = 1000 input_dim = 50 model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_dp=True, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0) _ = model.evaluate([x1, x2], [y1, y2], verbose=0) def test_single_io_workflow_with_datasets(self): num_classes = 2 num_samples = 10 input_dim = 50 with self.cached_session(): model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim), dtype=np.float32) y = np.zeros((num_samples, num_classes), dtype=np.float32) dataset = tf.data.Dataset.from_tensor_slices((x, y)) dataset = dataset.repeat(100) dataset = dataset.batch(10) model.fit(dataset, epochs=2, steps_per_epoch=10, verbose=0) _ = model.evaluate(dataset, steps=10, verbose=0) def test_attributes(self): # layers, weights, trainable_weights, non_trainable_weights, inputs, outputs num_classes = (2, 3) num_samples = 100 input_dim = 50 model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) self.assertEqual(model.name, 'test_model') self.assertEqual(model.built, False) self.assertEqual(len(model.weights), 0) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch([x1, x2], [y1, y2]) self.assertEqual(model.built, True) self.assertEqual(len(model.layers), 4) self.assertEqual(len(model.weights), 10) self.assertEqual(len(model.trainable_weights), 8) self.assertEqual(len(model.non_trainable_weights), 2) def test_updates(self): # test that updates get run during training num_samples = 100 input_dim = 50 class BNNet(keras.Model): def __init__(self): super(BNNet, self).__init__() self.bn = keras.layers.BatchNormalization(beta_initializer='ones', gamma_initializer='ones') def call(self, inputs): return self.bn(inputs) x = np.ones((num_samples, input_dim)) y = np.ones((num_samples, input_dim)) model = BNNet() model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) y_ref = model.predict(x) model.train_on_batch(x, y) y_new = model.predict(x) self.assertGreater(np.sum(np.abs(y_ref - y_new)), 0.1) def test_training_and_inference_behavior(self): # test that dropout is applied in training and not inference num_samples = 100 input_dim = 50 class DPNet(keras.Model): def __init__(self): super(DPNet, self).__init__() self.dp = keras.layers.Dropout(0.5) self.dense = keras.layers.Dense(1, use_bias=False, kernel_initializer='ones') def call(self, inputs): x = self.dp(inputs) return self.dense(x) model = DPNet() x = np.ones((num_samples, input_dim)) y = model.predict(x) self.assertEqual(np.sum(y), np.sum(x)) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) loss = model.train_on_batch(x, y) self.assertGreater(loss, 0.1) def test_training_methods(self): # test fit, train_on_batch # on different input types: list, dict num_classes = (2, 3) num_samples = 100 input_dim = 50 x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0) model.fit({'input_1': x1, 'input_2': x2}, {'output_1': y1, 'output_2': y2}, epochs=2, batch_size=32) model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0, validation_data=([x1, x2], [y1, y2])) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch([x1, x2], [y1, y2]) model.train_on_batch({'input_1': x1, 'input_2': x2}, {'output_1': y1, 'output_2': y2}) def test_inference_methods(self): # test predict, evaluate, test_on_batch, predict_on_batch # on different input types: list, dict num_classes = (2, 3) num_samples = 100 input_dim = 50 x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.evaluate([x1, x2], [y1, y2]) model.test_on_batch([x1, x2], [y1, y2]) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.predict([x1, x2]) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.predict_on_batch([x1, x2]) def test_saving(self): num_classes = (2, 3) num_samples = 100 input_dim = 50 x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0) y_ref_1, y_ref_2 = model.predict([x1, x2]) tf_format_name = os.path.join(self.get_temp_dir(), 'ckpt') model.save_weights(tf_format_name) if h5py is not None: hdf5_format_name = os.path.join(self.get_temp_dir(), 'weights.h5') model.save_weights(hdf5_format_name) model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_bn=True) if h5py is not None: with self.assertRaises(ValueError): model.load_weights(hdf5_format_name) model.load_weights(tf_format_name) y1, y2 = model.predict([x1, x2]) self.assertAllClose(y_ref_1, y1, atol=1e-5) self.assertAllClose(y_ref_2, y2, atol=1e-5) if h5py is not None: model.load_weights(hdf5_format_name) y1, y2 = model.predict([x1, x2]) self.assertAllClose(y_ref_1, y1, atol=1e-5) self.assertAllClose(y_ref_2, y2, atol=1e-5) def test_subclass_nested_in_subclass(self): num_classes = 2 num_samples = 100 input_dim = 50 model = model_util.NestedTestModel1(num_classes=num_classes) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim)) y = np.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, batch_size=32, verbose=0) _ = model.evaluate(x, y, verbose=0) self.assertEqual(len(model.weights), 8 + len(model.test_net.weights)) self.assertEqual(len(model.non_trainable_weights), 2 + len(model.test_net.non_trainable_weights)) self.assertEqual(len(model.trainable_weights), 6 + len(model.test_net.trainable_weights)) def test_graph_nested_in_subclass(self): num_classes = 2 num_samples = 100 input_dim = 50 model = model_util.NestedTestModel2(num_classes=num_classes) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim)) y = np.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, batch_size=32, verbose=0) _ = model.evaluate(x, y, verbose=0) self.assertEqual(len(model.weights), 8 + len(model.test_net.weights)) self.assertEqual(len(model.non_trainable_weights), 2 + len(model.test_net.non_trainable_weights)) self.assertEqual(len(model.trainable_weights), 6 + len(model.test_net.trainable_weights)) def test_subclass_nested_in_graph(self): num_classes = 2 num_samples = 100 input_dim = 50 model = model_util.get_nested_model_3( input_dim=input_dim, num_classes=num_classes) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim)) y = np.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, batch_size=32, verbose=0) _ = model.evaluate(x, y, verbose=0) self.assertEqual(len(model.weights), 16) self.assertEqual(len(model.non_trainable_weights), 4) self.assertEqual(len(model.trainable_weights), 12) def test_subclass_nested_in_sequential(self): num_classes = 2 num_samples = 100 input_dim = 50 class Inner(keras.Model): def __init__(self): super(Inner, self).__init__() self.dense1 = keras.layers.Dense(32, activation='relu') self.dense2 = keras.layers.Dense(num_classes, activation='relu') self.bn = keras.layers.BatchNormalization() def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) return self.bn(x) model = keras.Sequential([Inner()]) model.compile( loss='mse', optimizer='rmsprop', metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) x = np.ones((num_samples, input_dim)) y = np.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, batch_size=32, verbose=0) _ = model.evaluate(x, y, verbose=0) self.assertEqual(len(model.weights), 8) self.assertEqual(len(model.non_trainable_weights), 2) self.assertEqual(len(model.trainable_weights), 6) def test_support_for_manual_training_arg(self): # In most cases, the `training` argument is left unspecified, in which # case it defaults to value corresponding to the Model method being used # (fit -> True, predict -> False, etc). # If the user writes their model `call` method to take # an explicit `training` argument, we must check that the correct value # is being passed to the model for each method call. class DPNet(keras.Model): def __init__(self): super(DPNet, self).__init__() self.dp = keras.layers.Dropout(0.5) self.dense = keras.layers.Dense(1, use_bias=False, kernel_initializer='ones') def call(self, inputs, training=False): x = self.dp(inputs, training=training) return self.dense(x) model = DPNet() x = np.ones((10, 10)) y = model.predict(x) self.assertEqual(np.sum(y), np.sum(x)) model.compile( loss='mse', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) loss = model.train_on_batch(x, y) self.assertGreater(loss, 0.1) if __name__ == '__main__': tf.test.main()
14,222
31.398633
80
py
keras
keras-master/keras/tests/add_loss_correctness_test.py
# 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 tensorflow.compat.v2 as tf import numpy as np from keras import Input from keras import keras_parameterized from keras import layers from keras import losses from keras import Model from keras import optimizer_v2 from keras import Sequential from keras import testing_utils 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_v2.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(keras_parameterized.TestCase): def setUp(self): super(TestAddLossCorrectness, self).setUp() self.x = np.array([[0.], [1.], [2.]], dtype='float32') self.y = np.array([[0.5], [2.], [3.5]], dtype='float32') self.w = np.array([[1.25], [0.5], [1.25]], dtype='float32') @keras_parameterized.run_all_keras_modes def test_loss_on_model_fit(self): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = testing_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_v2.gradient_descent.SGD(0.05), run_eagerly=testing_utils.should_run_eagerly()) history = model.fit([self.x, self.y], batch_size=3, epochs=5) self.assertAllClose(history.history['loss'], [2., 1.8, 1.6, 1.4, 1.2], 1e-3) @keras_parameterized.run_with_all_model_types(exclude_models=['sequential']) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_loss_callable_on_model_fit(self): model = testing_utils.get_model_from_layers([testing_utils.Bias()], input_shape=(1,)) def callable_loss(): return tf.reduce_sum(model.weights) model.add_loss(callable_loss) model.compile( optimizer_v2.gradient_descent.SGD(0.1), run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(self.x, batch_size=3, epochs=5) self.assertAllClose(history.history['loss'], [0., -.1, -.2, -.3, -.4], 1e-3) @keras_parameterized.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 = testing_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., 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., 1.8, 1.6, 1.4, 1.2], 1e-3) @keras_parameterized.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 = testing_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.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.05, -0.1, -0.15, -0.2], 1e-3) @keras_parameterized.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 = testing_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_v2.gradient_descent.SGD(0.025), run_eagerly=testing_utils.should_run_eagerly()) history = model.fit([self.x, self.y, self.w], batch_size=3, epochs=5) self.assertAllClose(history.history['loss'], [4., 3.6, 3.2, 2.8, 2.4], 1e-3) @keras_parameterized.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 = testing_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., 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., 1.8, 1.6, 1.4, 1.2], 1e-3) @keras_parameterized.run_all_keras_modes def test_loss_with_sample_weight_in_model_call(self): class MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.bias = testing_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_v2.gradient_descent.SGD(0.05), run_eagerly=testing_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., 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) @keras_parameterized.run_all_keras_modes def test_loss_with_sample_weight_in_layer_call(self): class MyLayer(layers.Layer): def __init__(self): super(MyLayer, self).__init__() self.bias = testing_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_v2.gradient_descent.SGD(0.05), run_eagerly=testing_utils.should_run_eagerly()) history = model.fit([self.x, self.y, self.w], batch_size=3, epochs=5) self.assertAllClose(history.history['loss'], [2., 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) @keras_parameterized.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.assertEqual(len(model.losses), 1) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3))) self.assertEqual(loss, 2 * 3) @keras_parameterized.run_all_keras_modes @keras_parameterized.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 = testing_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=testing_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']) @keras_parameterized.run_all_keras_modes @keras_parameterized.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 = testing_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=testing_utils.should_run_eagerly()) loss = model.test_on_batch(x) self.assertAlmostEqual(0.01, loss, places=4) @keras_parameterized.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=testing_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) @keras_parameterized.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), inputs=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]) @keras_parameterized.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), inputs=inputs) return inputs * 2 class LayerWithNestedLayerWithLoss(layers.Layer): def __init__(self): super(LayerWithNestedLayerWithLoss, self).__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.assertEqual(len(m2.losses), 2) self.assertAllClose(m2.losses, [6, 12]) @keras_parameterized.run_all_keras_modes def test_clear_losses(self): class LayerWithSharedNestedLossLayer(layers.Layer): def __init__(self): super(LayerWithSharedNestedLossLayer, self).__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.assertEqual(len(l.get_losses_for(x1)), 2) self.assertEqual(len(l.get_losses_for(None)), 1) x2 = tf.ones((1, 1)) _ = l(x2) if not tf.executing_eagerly(): self.assertEqual(len(l.get_losses_for(x1)), 2) self.assertEqual(len(l.get_losses_for(x2)), 2) self.assertEqual(len(l.get_losses_for(None)), 1) outputs = l(inputs) model = Model(inputs, outputs) if not tf.executing_eagerly(): self.assertEqual(len(model.losses), 7) self.assertEqual(len(l.get_losses_for(x1)), 2) self.assertEqual(len(l.get_losses_for(x2)), 2) self.assertEqual(len(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.assertEqual(len(model.losses), 3) else: self.assertEqual(len(model.losses), 11) self.assertEqual(len(model.get_losses_for(x3)), 2) self.assertEqual(len(model.get_losses_for(x4)), 2) self.assertEqual(len(model.get_losses_for(None)), 1) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_invalid_constant_input(self): inputs = Input(shape=(1,)) outputs = testing_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.) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_invalid_variable_input(self): inputs = Input(shape=(1,)) outputs = testing_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]) @keras_parameterized.run_all_keras_modes def test_add_entropy_loss_on_functional_model(self): inputs = Input(shape=(1,)) targets = Input(shape=(1,)) outputs = testing_utils.Bias()(inputs) model = Model([inputs, targets], outputs) model.add_loss(losses.binary_crossentropy(targets, outputs)) model.compile('sgd', run_eagerly=testing_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()
15,860
33.782895
80
py
keras
keras-master/keras/tests/convert_to_constants_test.py
# 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 convert_to_constants.py.""" import tensorflow.compat.v2 as tf import os import numpy as np import keras from tensorflow.python.framework import convert_to_constants from keras import testing_utils from tensorflow.python.saved_model.load import load from tensorflow.python.saved_model.save import save class VariablesToConstantsTest(tf.test.TestCase): def _freezeModel(self, model): """Freezes the model. Args: model: Function. Returns: root: AutoTrackable object with original ConcreteFunction. output_func: frozen ConcreteFunction. """ root = tf.Module() root.f = model input_func = root.f.get_concrete_function() output_func = convert_to_constants.convert_variables_to_constants_v2( input_func, lower_control_flow=False) return root, output_func def _hasStatefulPartitionedCallOp(self, graph_def): """Determines if a StatefulPartitionedCall op exists in the graph.""" for node in graph_def.node: if node.op == "StatefulPartitionedCall": return True return False def _getNumVariables(self, graph_def): """Returns the number of ReadVariableOp in the graph.""" return sum(node.op == "ReadVariableOp" for node in graph_def.node) def _testConvertedFunction(self, obj, func, converted_concrete_func, input_data): # Ensure the converted graph has no variables and no function calls. constant_graph_def = converted_concrete_func.graph.as_graph_def() self.assertEqual(0, self._getNumVariables(constant_graph_def)) self.assertFalse(self._hasStatefulPartitionedCallOp(constant_graph_def)) # Check that the converted ConcreteFunction produces the same result as the # original Function. expected_value = tf.nest.flatten(func(**input_data)) actual_value = tf.nest.flatten(converted_concrete_func(**input_data)) for expected, actual in zip(expected_value, actual_value): np.testing.assert_almost_equal(expected.numpy(), actual.numpy()) # Ensure the shape is retained. for tensor in converted_concrete_func.inputs: actual_shape = input_data[tensor.name.split(":")[0]].shape self.assertEqual(tensor.shape, actual_shape) # Save the converted ConcreteFunction as a signature. save_dir = os.path.join(self.get_temp_dir(), "frozen_saved_model") root = tf.Module() root.f = converted_concrete_func save(root, save_dir, {"mykey": converted_concrete_func}) # Load it back and make sure it works. loaded_obj = load(save_dir) actual_value = tf.nest.flatten(loaded_obj.signatures["mykey"](**input_data)) for expected, actual in zip(expected_value, actual_value): np.testing.assert_almost_equal(expected.numpy(), actual.numpy()) @testing_utils.run_v2_only def testKerasModel(self): """Test a basic Keras model with Variables.""" input_data = {"x": tf.constant(1., shape=[1, 1])} # Create a simple Keras model. x = [-1, 0, 1, 2, 3, 4] y = [-3, -1, 1, 3, 5, 7] model = keras.models.Sequential( [keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer="sgd", loss="mean_squared_error") model.fit(x, y, epochs=1) @tf.function(input_signature=[ tf.TensorSpec(shape=[1, 1], dtype=tf.float32) ]) def to_save(x): return model(x) root, output_func = self._freezeModel(to_save) self._testConvertedFunction(root, root.f, output_func, input_data) @testing_utils.run_v2_only def testKerasLSTM(self): """Test a Keras LSTM containing dynamic_rnn ops.""" input_data = { "x": tf.constant( np.array( np.random.random_sample((10, 10, 10)), dtype=np.float32)) } model = keras.models.Sequential( [keras.layers.LSTM(units=10, input_shape=(10, 10))]) @tf.function(input_signature=[ tf.TensorSpec(shape=[10, 10, 10], dtype=tf.float32) ]) def to_save(x): return model(x) root, output_func = self._freezeModel(to_save) self._testConvertedFunction(root, root.f, output_func, input_data) @testing_utils.run_v2_only def testEmbeddings(self): """Test model with embeddings.""" input_data = { "x": tf.constant( np.array(np.random.random_sample((20)), dtype=np.int32)) } class EmbeddingModel(keras.Model): def __init__(self): super(EmbeddingModel, self).__init__() self.shared_weights = self.add_weight( "weights", shape=(2000, 300), dtype=tf.float32, initializer=tf.compat.v1.random_normal_initializer( mean=0.0, stddev=300**(-0.5))) @tf.function(input_signature=[ tf.TensorSpec(shape=(20), dtype=tf.int32) ]) def func(self, x): return tf.gather(self.shared_weights, x) model = EmbeddingModel() root, output_func = self._freezeModel(model.func) self._testConvertedFunction(root, root.f, output_func, input_data) if __name__ == "__main__": tf.test.main()
5,774
32.77193
80
py
keras
keras-master/keras/tests/saver_test.py
# 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 tensorflow.python.training.saver.py.""" import tensorflow.compat.v2 as tf import functools import os from keras.engine import training from keras.layers import core from tensorflow.python.training.tracking import util as trackable_utils class NonLayerTrackable(tf.Module): def __init__(self): super(NonLayerTrackable, self).__init__() self.a_variable = trackable_utils.add_variable( self, name="a_variable", shape=[]) class MyModel(training.Model): """A concrete Model for testing.""" def __init__(self): super(MyModel, self).__init__() self._named_dense = core.Dense(1, use_bias=True) self._second = core.Dense(1, use_bias=False) # We can still track Trackables which aren't Layers. self._non_layer = NonLayerTrackable() def call(self, values): ret = self._second(self._named_dense(values)) return ret class TrackableCompatibilityTests(tf.test.TestCase): def _initialized_model(self): input_value = tf.constant([[3.]]) model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) optimizer_step = tf.compat.v1.train.get_or_create_global_step() root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=optimizer_step) train_op = optimizer.minimize( functools.partial(model, input_value), global_step=optimizer_step) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) # A regular variable, a slot variable, and a non-slot Optimizer variable # with known values to check when loading. self.evaluate(model._named_dense.bias.assign([1.])) self.evaluate(optimizer.get_slot( var=model._named_dense.bias, name="m").assign([2.])) beta1_power, _ = optimizer._get_beta_accumulators() self.evaluate(beta1_power.assign(3.)) return root_trackable def _set_sentinels(self, root_trackable): self.evaluate(root_trackable.model._named_dense.bias.assign([101.])) self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, name="m") .assign([102.])) beta1_power, _ = root_trackable.optimizer._get_beta_accumulators() self.evaluate(beta1_power.assign(103.)) def _check_sentinels(self, root_trackable): self.assertAllEqual( [1.], self.evaluate(root_trackable.model._named_dense.bias)) self.assertAllEqual([2.], self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, name="m"))) beta1_power, _ = root_trackable.optimizer._get_beta_accumulators() self.assertAllEqual(3., self.evaluate(beta1_power)) def testLoadFromObjectBasedGraph(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") save_graph = tf.Graph() with save_graph.as_default(), self.session(graph=save_graph) as sess: root = self._initialized_model() object_saver = tf.train.Checkpoint(root=root) save_path = object_saver.save(file_prefix=checkpoint_prefix) # An incompatible object-based checkpoint to check error messages var = tf.Variable(1., name="a") self.evaluate(var.initializer) second_saver = tf.train.Checkpoint(v=var) second_path = second_saver.save(file_prefix=os.path.join( checkpoint_directory, "second")) restore_graph = tf.Graph() with restore_graph.as_default(), self.session( graph=restore_graph) as sess: root = self._initialized_model() self._set_sentinels(root) saver = tf.compat.v1.train.Saver() saver.restore(sess=sess, save_path=save_path) self._check_sentinels(root) before_second_restore_ops = restore_graph.get_operations() # Test that multiple restores do not pollute the graph saver.restore(sess=sess, save_path=save_path) self.assertEqual(before_second_restore_ops, restore_graph.get_operations()) with self.assertRaisesRegex(tf.errors.NotFoundError, "Could not find some variables"): saver.restore(sess=sess, save_path=second_path) def testLoadFromObjectBasedEager(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") save_graph = tf.Graph() with save_graph.as_default(), self.session(graph=save_graph): root = self._initialized_model() object_saver = tf.train.Checkpoint(root=root) save_path = object_saver.save(file_prefix=checkpoint_prefix) with tf.__internal__.eager_context.eager_mode(): root = self._initialized_model() self._set_sentinels(root) saver = tf.compat.v1.train.Saver( root.model.variables + root.optimizer.variables()) saver.restore(sess=None, save_path=save_path) self._check_sentinels(root) if __name__ == "__main__": tf.test.main()
5,665
37.808219
79
py
keras
keras-master/keras/tests/get_config_test.py
# 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 `get_config` backwards compatibility.""" import tensorflow.compat.v2 as tf from keras import keras_parameterized from keras.engine import sequential from keras.engine import training from keras.tests import get_config_samples @keras_parameterized.run_all_keras_modes class TestGetConfigBackwardsCompatible(keras_parameterized.TestCase): def test_functional_dnn(self): model = training.Model.from_config(get_config_samples.FUNCTIONAL_DNN) self.assertLen(model.layers, 3) def test_functional_cnn(self): model = training.Model.from_config(get_config_samples.FUNCTIONAL_CNN) self.assertLen(model.layers, 4) def test_functional_lstm(self): model = training.Model.from_config(get_config_samples.FUNCTIONAL_LSTM) self.assertLen(model.layers, 3) def test_sequential_dnn(self): model = sequential.Sequential.from_config(get_config_samples.SEQUENTIAL_DNN) self.assertLen(model.layers, 2) def test_sequential_cnn(self): model = sequential.Sequential.from_config(get_config_samples.SEQUENTIAL_CNN) self.assertLen(model.layers, 3) def test_sequential_lstm(self): model = sequential.Sequential.from_config( get_config_samples.SEQUENTIAL_LSTM) self.assertLen(model.layers, 2) if __name__ == '__main__': tf.test.main()
1,985
34.464286
80
py
keras
keras-master/keras/tests/serialization_util_test.py
# 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 serialization functions.""" import tensorflow.compat.v2 as tf import json from keras import combinations from keras import keras_parameterized from keras.engine import input_layer from keras.engine import sequential from keras.engine import training from keras.layers import core from keras.saving.saved_model import json_utils @combinations.generate(combinations.combine(mode=["graph", "eager"])) class SerializationTests(keras_parameterized.TestCase): def test_serialize_dense(self): dense = core.Dense(3) dense(tf.constant([[4.]])) round_trip = json.loads(json.dumps( dense, default=json_utils.get_json_type)) self.assertEqual(3, round_trip["config"]["units"]) def test_serialize_sequential(self): model = sequential.Sequential() model.add(core.Dense(4)) model.add(core.Dense(5)) model(tf.constant([[1.]])) sequential_round_trip = json.loads( json.dumps(model, default=json_utils.get_json_type)) self.assertEqual( # Note that `config['layers'][0]` will be an InputLayer in V2 # (but not in V1) 5, sequential_round_trip["config"]["layers"][-1]["config"]["units"]) def test_serialize_model(self): x = input_layer.Input(shape=[3]) y = core.Dense(10)(x) model = training.Model(x, y) model(tf.constant([[1., 1., 1.]])) model_round_trip = json.loads( json.dumps(model, default=json_utils.get_json_type)) self.assertEqual( 10, model_round_trip["config"]["layers"][1]["config"]["units"]) if __name__ == "__main__": tf.test.main()
2,263
34.936508
80
py
keras
keras-master/keras/tests/model_architectures_test.py
# 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. # ============================================================================== # pylint: disable=protected-access """Tests for saving/loading function for keras Model.""" import tensorflow.compat.v2 as tf import os import shutil from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import optimizer_v1 from keras import testing_utils from keras.tests import model_architectures @keras_parameterized.run_with_all_saved_model_formats class TestModelArchitectures(keras_parameterized.TestCase): def _save_model_dir(self, dirname='saved_model'): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) return os.path.join(temp_dir, dirname) def get_test_data(self, input_shape, target_shape): """Generate test dataset for testing.""" if isinstance(input_shape, list): x = [ np.random.random((2,) + input_shape[i][1:]) for i in range(len(input_shape)) ] else: x = np.random.random((2,) + input_shape[1:]) if isinstance(target_shape, list): y = [ np.random.random((2,) + target_shape[i][1:]) for i in range(len(target_shape)) ] else: y = np.random.random((2,) + target_shape[1:]) return x, y def get_custom_objects(self): """Define custom_objects.""" class CustomOpt(optimizer_v1.SGD): pass def custom_loss(y_true, y_pred): return keras.losses.mse(y_true, y_pred) return {'CustomOpt': CustomOpt, 'custom_loss': custom_loss} @parameterized.named_parameters(*model_architectures.ALL_MODELS) def test_basic_saving_and_loading(self, model_fn): save_format = testing_utils.get_save_format() custom_objects = self.get_custom_objects() if 'subclassed_in_functional' in model_fn.__name__: subclass_custom_objects = { 'MySubclassModel': model_architectures.MySubclassModel, } custom_objects.update(subclass_custom_objects) elif ('subclassed' in model_fn.__name__ and save_format == 'h5'): self.skipTest('Saving the model to HDF5 format requires the model to be ' 'a Functional model or a Sequential model.') saved_model_dir = self._save_model_dir() model_data = model_fn() model = model_data.model x_test, y_test = self.get_test_data( model_data.input_shape, model_data.target_shape) model.compile('rmsprop', 'mse') model.train_on_batch(x_test, y_test) # Save model. out1 = model.predict(x_test) keras.models.save_model(model, saved_model_dir, save_format=save_format) # Load model. loaded_model = keras.models.load_model( saved_model_dir, custom_objects=custom_objects) out2 = loaded_model.predict(x_test) self.assertAllClose(out1, out2, atol=1e-05) if __name__ == '__main__': tf.test.main()
3,535
31.440367
80
py
keras
keras-master/keras/tests/get_config_samples.py
# 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. # ============================================================================== # pylint: disable=protected-access """Sample `get_config` results for testing backwards compatibility.""" # inputs = tf.keras.Input(10) # x = tf.keras.layers.Dense(10, activation='relu')(inputs) # outputs = tf.keras.layers.Dense(1)(x) # model = tf.keras.Model(inputs, outputs) FUNCTIONAL_DNN = { 'input_layers': [['input_1', 0, 0]], 'layers': [{ 'class_name': 'InputLayer', 'config': { 'batch_input_shape': (None, 10), 'dtype': 'float32', 'name': 'input_1', 'ragged': False, 'sparse': False }, 'inbound_nodes': [], 'name': 'input_1' }, { 'class_name': 'Dense', 'config': { 'activation': 'relu', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense', 'trainable': True, 'units': 10, 'use_bias': True }, 'inbound_nodes': [[['input_1', 0, 0, {}]]], 'name': 'dense' }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_1', 'trainable': True, 'units': 1, 'use_bias': True }, 'inbound_nodes': [[['dense', 0, 0, {}]]], 'name': 'dense_1' }], 'name': 'model', 'output_layers': [['dense_1', 0, 0]] } # inputs = tf.keras.Input((256, 256, 3)) # x = tf.keras.layers.Conv2D(filters=3, kernel_size=(3, 3))(inputs) # x = tf.keras.layers.Flatten()(x) # outputs = tf.keras.layers.Dense(1)(x) # model = tf.keras.Model(inputs, outputs) FUNCTIONAL_CNN = { 'input_layers': [['input_2', 0, 0]], 'layers': [{ 'class_name': 'InputLayer', 'config': { 'batch_input_shape': (None, 256, 256, 3), 'dtype': 'float32', 'name': 'input_2', 'ragged': False, 'sparse': False }, 'inbound_nodes': [], 'name': 'input_2' }, { 'class_name': 'Conv2D', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'data_format': 'channels_last', 'dilation_rate': (1, 1), 'dtype': 'float32', 'filters': 3, 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'kernel_size': (3, 3), 'name': 'conv2d', 'padding': 'valid', 'strides': (1, 1), 'trainable': True, 'use_bias': True }, 'inbound_nodes': [[['input_2', 0, 0, {}]]], 'name': 'conv2d' }, { 'class_name': 'Flatten', 'config': { 'data_format': 'channels_last', 'dtype': 'float32', 'name': 'flatten', 'trainable': True }, 'inbound_nodes': [[['conv2d', 0, 0, {}]]], 'name': 'flatten' }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_2', 'trainable': True, 'units': 1, 'use_bias': True }, 'inbound_nodes': [[['flatten', 0, 0, {}]]], 'name': 'dense_2' }], 'name': 'model_1', 'output_layers': [['dense_2', 0, 0]] } # inputs = tf.keras.Input((10, 3)) # x = tf.keras.layers.LSTM(10)(inputs) # outputs = tf.keras.layers.Dense(1)(x) # model = tf.keras.Model(inputs, outputs) FUNCTIONAL_LSTM = { 'input_layers': [['input_5', 0, 0]], 'layers': [{ 'class_name': 'InputLayer', 'config': { 'batch_input_shape': (None, 10, 3), 'dtype': 'float32', 'name': 'input_5', 'ragged': False, 'sparse': False }, 'inbound_nodes': [], 'name': 'input_5' }, { 'class_name': 'LSTM', 'config': { 'activation': 'tanh', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dropout': 0.0, 'dtype': 'float32', 'go_backwards': False, 'implementation': 2, 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'lstm_2', 'recurrent_activation': 'sigmoid', 'recurrent_constraint': None, 'recurrent_dropout': 0.0, 'recurrent_initializer': { 'class_name': 'Orthogonal', 'config': { 'gain': 1.0, 'seed': None } }, 'recurrent_regularizer': None, 'return_sequences': False, 'return_state': False, 'stateful': False, 'time_major': False, 'trainable': True, 'unit_forget_bias': True, 'units': 10, 'unroll': False, 'use_bias': True }, 'inbound_nodes': [[['input_5', 0, 0, {}]]], 'name': 'lstm_2' }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_4', 'trainable': True, 'units': 1, 'use_bias': True }, 'inbound_nodes': [[['lstm_2', 0, 0, {}]]], 'name': 'dense_4' }], 'name': 'model_3', 'output_layers': [['dense_4', 0, 0]] } # model = tf.keras.Sequential() # model.add(tf.keras.layers.Dense(10)) # model.add(tf.keras.layers.Dense(1)) SEQUENTIAL_DNN = { 'layers': [{ 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_2', 'trainable': True, 'units': 10, 'use_bias': True } }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_3', 'trainable': True, 'units': 1, 'use_bias': True } }], 'name': 'sequential_1' } # model = tf.keras.Sequential() # model.add(tf.keras.layers.Conv2D(32, (3, 3))) # model.add(tf.keras.layers.Flatten()) # model.add(tf.keras.layers.Dense(1)) SEQUENTIAL_CNN = { 'layers': [{ 'class_name': 'Conv2D', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'data_format': 'channels_last', 'dilation_rate': (1, 1), 'dtype': 'float32', 'filters': 32, 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'kernel_size': (3, 3), 'name': 'conv2d_1', 'padding': 'valid', 'strides': (1, 1), 'trainable': True, 'use_bias': True } }, { 'class_name': 'Flatten', 'config': { 'data_format': 'channels_last', 'dtype': 'float32', 'name': 'flatten_1', 'trainable': True } }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_6', 'trainable': True, 'units': 1, 'use_bias': True } }], 'name': 'sequential_4' } # model = tf.keras.Sequential() # model.add(tf.keras.layers.LSTM(10)) # model.add(tf.keras.layers.Dense(1)) SEQUENTIAL_LSTM = { 'layers': [{ 'class_name': 'LSTM', 'config': { 'activation': 'tanh', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dropout': 0.0, 'dtype': 'float32', 'go_backwards': False, 'implementation': 2, 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'lstm', 'recurrent_activation': 'sigmoid', 'recurrent_constraint': None, 'recurrent_dropout': 0.0, 'recurrent_initializer': { 'class_name': 'Orthogonal', 'config': { 'gain': 1.0, 'seed': None } }, 'recurrent_regularizer': None, 'return_sequences': False, 'return_state': False, 'stateful': False, 'time_major': False, 'trainable': True, 'unit_forget_bias': True, 'units': 10, 'unroll': False, 'use_bias': True } }, { 'class_name': 'Dense', 'config': { 'activation': 'linear', 'activity_regularizer': None, 'bias_constraint': None, 'bias_initializer': { 'class_name': 'Zeros', 'config': {} }, 'bias_regularizer': None, 'dtype': 'float32', 'kernel_constraint': None, 'kernel_initializer': { 'class_name': 'GlorotUniform', 'config': { 'seed': None } }, 'kernel_regularizer': None, 'name': 'dense_4', 'trainable': True, 'units': 1, 'use_bias': True } }], 'name': 'sequential_2' }
14,844
29.357873
80
py
keras
keras-master/keras/tests/model_subclassing_test_util.py
# 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 models for use in Model subclassing tests.""" import keras from keras import testing_utils # pylint: disable=missing-docstring,not-callable class SimpleConvTestModel(keras.Model): def __init__(self, num_classes=10): super(SimpleConvTestModel, self).__init__(name='test_model') self.num_classes = num_classes self.conv1 = keras.layers.Conv2D(32, (3, 3), activation='relu') self.flatten = keras.layers.Flatten() self.dense1 = keras.layers.Dense(num_classes, activation='softmax') def call(self, x): x = self.conv1(x) x = self.flatten(x) return self.dense1(x) def get_multi_io_subclass_model(use_bn=False, use_dp=False, num_classes=(2, 3)): """Creates MultiIOModel for the tests of subclass model.""" shared_layer = keras.layers.Dense(32, activation='relu') branch_a = [shared_layer] if use_dp: branch_a.append(keras.layers.Dropout(0.5)) branch_a.append(keras.layers.Dense(num_classes[0], activation='softmax')) branch_b = [shared_layer] if use_bn: branch_b.append(keras.layers.BatchNormalization()) branch_b.append(keras.layers.Dense(num_classes[1], activation='softmax')) model = ( testing_utils._MultiIOSubclassModel( # pylint: disable=protected-access branch_a, branch_b, name='test_model')) return model class NestedTestModel1(keras.Model): """A model subclass nested inside a model subclass. """ def __init__(self, num_classes=2): super(NestedTestModel1, self).__init__(name='nested_model_1') self.num_classes = num_classes self.dense1 = keras.layers.Dense(32, activation='relu') self.dense2 = keras.layers.Dense(num_classes, activation='relu') self.bn = keras.layers.BatchNormalization() self.test_net = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=4, use_bn=True, use_dp=True) def call(self, inputs): x = self.dense1(inputs) x = self.bn(x) x = self.test_net(x) return self.dense2(x) class NestedTestModel2(keras.Model): """A model subclass with a functional-API graph network inside. """ def __init__(self, num_classes=2): super(NestedTestModel2, self).__init__(name='nested_model_2') self.num_classes = num_classes self.dense1 = keras.layers.Dense(32, activation='relu') self.dense2 = keras.layers.Dense(num_classes, activation='relu') self.bn = self.bn = keras.layers.BatchNormalization() self.test_net = self.get_functional_graph_model(32, 4) @staticmethod def get_functional_graph_model(input_dim, num_classes): # A simple functional-API model (a.k.a. graph network) inputs = keras.Input(shape=(input_dim,)) x = keras.layers.Dense(32, activation='relu')(inputs) x = keras.layers.BatchNormalization()(x) outputs = keras.layers.Dense(num_classes)(x) return keras.Model(inputs, outputs) def call(self, inputs): x = self.dense1(inputs) x = self.bn(x) x = self.test_net(x) return self.dense2(x) def get_nested_model_3(input_dim, num_classes): # A functional-API model with a subclassed model inside. # NOTE: this requires the inner subclass to implement `compute_output_shape`. inputs = keras.Input(shape=(input_dim,)) x = keras.layers.Dense(32, activation='relu')(inputs) x = keras.layers.BatchNormalization()(x) class Inner(keras.Model): def __init__(self): super(Inner, self).__init__() self.dense1 = keras.layers.Dense(32, activation='relu') self.dense2 = keras.layers.Dense(5, activation='relu') self.bn = keras.layers.BatchNormalization() def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) return self.bn(x) test_model = Inner() x = test_model(x) outputs = keras.layers.Dense(num_classes)(x) return keras.Model(inputs, outputs, name='nested_model_3') class CustomCallModel(keras.Model): def __init__(self): super(CustomCallModel, self).__init__() self.dense1 = keras.layers.Dense(1, activation='relu') self.dense2 = keras.layers.Dense(1, activation='softmax') def call(self, first, second, fiddle_with_output='no', training=True): combined = self.dense1(first) + self.dense2(second) if fiddle_with_output == 'yes': return 10. * combined else: return combined class TrainingNoDefaultModel(keras.Model): def __init__(self): super(TrainingNoDefaultModel, self).__init__() self.dense1 = keras.layers.Dense(1) def call(self, x, training): return self.dense1(x) class TrainingMaskingModel(keras.Model): def __init__(self): super(TrainingMaskingModel, self).__init__() self.dense1 = keras.layers.Dense(1) def call(self, x, training=False, mask=None): return self.dense1(x)
5,398
31.721212
80
py
keras
keras-master/keras/tests/tracking_util_test.py
# Copyright 2017 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 functools import tensorflow.compat.v2 as tf import os import weakref from tensorflow.python.eager import context from tensorflow.python.framework import test_util from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.engine import input_layer from keras.engine import sequential from keras.engine import training from keras.layers import core from keras.optimizer_v2 import adam from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training.tracking import util as trackable_utils # pylint: disable=not-callable class MyModel(training.Model): """A concrete Model for testing.""" def __init__(self): super(MyModel, self).__init__() self._named_dense = core.Dense(1, use_bias=True) self._second = core.Dense(1, use_bias=False) # We can still track Trackables which aren't Layers. self._non_layer = NonLayerTrackable() def call(self, values): ret = self._second(self._named_dense(values)) return ret class NonLayerTrackable(tf.Module): def __init__(self): super(NonLayerTrackable, self).__init__() self.a_variable = trackable_utils.add_variable( self, name="a_variable", shape=[]) class InterfaceTests(tf.test.TestCase): def testLayerDeduplication(self): model = training.Model() layer_one = core.Dense(1) layer_two = core.Dense(1) model.other_path = [layer_one, layer_two] model.l2 = layer_two model.l1 = layer_one self.assertEqual([layer_one, layer_two], model.layers) def testSaveWithOnlyKerasSession(self): with tf.Graph().as_default(), self.cached_session(): inp = input_layer.Input([1]) dense = core.Dense(1)(inp) model = training.Model(inp, dense) model.compile(optimizer="sgd", loss="mse") model.fit([1.], [2.]) checkpoint = tf.train.Checkpoint(model=model) checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt")) class CheckpointingTests(keras_parameterized.TestCase): @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True) def testNamingWithOptimizer(self): input_value = tf.constant([[3.]]) model = MyModel() # A nuisance Model using the same optimizer. Its slot variables should not # go in the checkpoint, since it is never depended on. other_model = MyModel() optimizer = adam.Adam(0.001) step = tf.compat.v1.train.get_or_create_global_step() root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model, step=step) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) train_op = tf.group( optimizer.apply_gradients(zip(gradients, variables)), step.assign_add(1)) with tf.GradientTape() as tape: loss = other_model(input_value) variables = other_model.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) named_variables, serialized_graph, _ = tf.__internal__.tracking.ObjectGraphView( root_trackable).serialize_object_graph() expected_slot_keys = ( "model/_second/kernel/.OPTIMIZER_SLOT/optimizer/m", "model/_second/kernel/.OPTIMIZER_SLOT/optimizer/v", "model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/m", "model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/v", "model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/m", "model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/v", ) expected_checkpoint_names = ( # Created in the root node, so no prefix. "step", "model/_second/kernel", "model/_named_dense/kernel", "model/_named_dense/bias", # non-Layer dependency of the model "model/_non_layer/a_variable", "optimizer/learning_rate", "optimizer/beta_1", "optimizer/beta_2", "optimizer/iter", "optimizer/decay", ) + expected_slot_keys suffix = "/.ATTRIBUTES/VARIABLE_VALUE" expected_checkpoint_names = [ name + suffix for name in expected_checkpoint_names] named_variables = {v.name: v for v in named_variables} self.assertEqual(len(expected_checkpoint_names), len(named_variables.keys())) # Check that we've mapped to the right variable objects (not exhaustive) self.assertEqual( "global_step", named_variables["step" + suffix].full_name) self.assertEqual( "my_model/dense_1/kernel", named_variables["model/_second/kernel" + suffix].full_name) self.assertEqual( "my_model/dense/kernel", named_variables["model/_named_dense/kernel" + suffix].full_name) self.assertEqual("Adam/beta_1", named_variables["optimizer/beta_1" + suffix].full_name) self.assertEqual("Adam/beta_2", named_variables["optimizer/beta_2" + suffix].full_name) # Spot check the generated protocol buffers. self.assertEqual("optimizer", serialized_graph.nodes[0].children[1].local_name) optimizer_node = serialized_graph.nodes[ serialized_graph.nodes[0].children[1].node_id] children = [node.local_name for node in optimizer_node.children] self.assertEqual( # hyper variable dependencies len(["beta_1", "beta_2", "iter", "decay", "learning_rate"]), len(children)) serialized_slot_keys = [] for slot in optimizer_node.slot_variables: for attribute in ( serialized_graph.nodes[slot.slot_variable_node_id].attributes): serialized_slot_keys.append(attribute.checkpoint_key) self.assertEqual( len([key + suffix for key in expected_slot_keys]), len(serialized_slot_keys)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testSaveRestore(self): with self.test_session(): model = MyModel() optimizer = adam.Adam(0.001) root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model) input_value = tf.constant([[3.]]) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) train_op = optimizer.apply_gradients(zip(gradients, variables)) self.assertFalse(root_trackable.save_counter.trainable) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(tf.compat.v1.assign(model._named_dense.variables[1], [42.])) m_bias_slot = optimizer.get_slot(model._named_dense.variables[1], "m") self.evaluate(tf.compat.v1.assign(m_bias_slot, [1.5])) save_path = root_trackable.save(file_prefix=prefix) self.evaluate(tf.compat.v1.assign(model._named_dense.variables[1], [43.])) self.evaluate(tf.compat.v1.assign(root_trackable.save_counter, 3)) optimizer_variables = self.evaluate( sorted(optimizer.variables(), key=lambda v: v.name)) self.evaluate(tf.compat.v1.assign(m_bias_slot, [-2.])) # Immediate restoration status = root_trackable.restore(save_path=save_path).assert_consumed() status.run_restore_ops() self.assertAllEqual([42.], self.evaluate(model._named_dense.variables[1])) self.assertAllEqual(1, self.evaluate(root_trackable.save_counter)) self.assertAllEqual([1.5], self.evaluate(m_bias_slot)) if not tf.executing_eagerly(): return # Restore-on-create is only supported when executing eagerly on_create_model = MyModel() on_create_optimizer = adam.Adam(0.001) on_create_root = tf.train.Checkpoint( optimizer=on_create_optimizer, model=on_create_model) # Deferred restoration status = on_create_root.restore(save_path=save_path) status.assert_nontrivial_match() status.assert_existing_objects_matched() with self.assertRaises(AssertionError): status.assert_consumed() on_create_model(tf.constant([[3.]])) # create variables self.assertAllEqual(1, self.evaluate(on_create_root.save_counter)) self.assertAllEqual([42.], self.evaluate( on_create_model._named_dense.variables[1])) on_create_m_bias_slot = on_create_optimizer.get_slot( on_create_model._named_dense.variables[1], "m") status.assert_existing_objects_matched() if not tf.executing_eagerly(): with self.assertRaises(AssertionError): status.assert_consumed() # Optimizer slot variables are created when the original variable is # restored. self.assertAllEqual([1.5], self.evaluate(on_create_m_bias_slot)) dummy_var = tf.Variable([1.]) on_create_optimizer.minimize(loss=dummy_var.read_value, var_list=[dummy_var]) status.assert_existing_objects_matched() status.assert_consumed() self.assertAllEqual( optimizer_variables, # Creation order is different, so .variables() needs to be re-sorted. self.evaluate(sorted(optimizer.variables(), key=lambda v: v.name))) # TODO(allenl): Debug garbage created by this test in python3. def testDeferredRestorationUsageEager(self): """An idiomatic eager execution example.""" num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): model = MyModel() optimizer = adam.Adam(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model) root.restore(tf.train.latest_checkpoint( checkpoint_directory)) for _ in range(num_training_steps): # TODO(allenl): Use a Dataset and serialize/checkpoint it. input_value = tf.constant([[3.]]) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, root.optimizer.iterations.numpy()) def testUsageGraph(self): """Expected usage when graph building.""" with context.graph_mode(): num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): with tf.Graph().as_default(): model = MyModel() optimizer = adam.Adam(0.001) root = tf.compat.v1.train.Checkpoint( optimizer=optimizer, model=model) input_value = tf.constant([[3.]]) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) train_op = optimizer.apply_gradients(zip(gradients, variables)) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) with self.session(graph=tf.compat.v1.get_default_graph()) as session: status = root.restore(save_path=checkpoint_path) status.initialize_or_restore(session=session) if checkpoint_path is None: self.assertEqual(0, training_continuation) with self.assertRaises(AssertionError): status.assert_consumed() with self.assertRaises(AssertionError): status.assert_existing_objects_matched() else: status.assert_consumed() status.assert_existing_objects_matched() for _ in range(num_training_steps): session.run(train_op) root.save(file_prefix=checkpoint_prefix, session=session) self.assertEqual((training_continuation + 1) * num_training_steps, session.run(root.optimizer.iterations)) self.assertEqual(training_continuation + 1, session.run(root.save_counter)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testAgnosticUsage(self): """Graph/eager agnostic usage.""" # Does create garbage when executing eagerly due to ops.Graph() creation. with self.test_session(): num_training_steps = 10 checkpoint_directory = self.get_temp_dir() optimizer = adam.Adam(0.001) def _train_fn(model, input_value): with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) return optimizer.apply_gradients(zip(gradients, variables)) for training_continuation in range(3): with testing_utils.device(should_use_gpu=True): model = MyModel() root = tf.train.Checkpoint( optimizer=optimizer, model=model) manager = tf.train.CheckpointManager( root, checkpoint_directory, max_to_keep=1) status = root.restore(save_path=manager.latest_checkpoint) input_value = tf.constant([[3.]]) train_fn = functools.partial(_train_fn, model, input_value) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) status.initialize_or_restore() for _ in range(num_training_steps): train_fn() manager.save() self.assertEqual((training_continuation + 1) * num_training_steps, self.evaluate(root.optimizer.iterations)) self.assertEqual(training_continuation + 1, self.evaluate(root.save_counter)) @combinations.generate(combinations.combine(mode=["eager"])) def testPartialRestoreWarningObject(self): optimizer = adam.Adam(0.0) original_root = tf.train.Checkpoint(v1=tf.Variable(2.), v2=tf.Variable(3.), optimizer=optimizer) # Create a slot variable to save optimizer.minimize(original_root.v1.read_value, [original_root.v1]) prefix = os.path.join(self.get_temp_dir(), "ckpt") save_path = original_root.save(prefix) partial_root = tf.train.Checkpoint(v1=tf.Variable(0.)) weak_partial_root = weakref.ref(partial_root) weak_v1 = weakref.ref(partial_root.v1) partial_root.restore(save_path) self.assertEqual(2., partial_root.v1.numpy()) with tf.compat.v1.test.mock.patch.object(logging, "warning") as mock_log: del partial_root self.assertIsNone(weak_partial_root()) self.assertIsNone(weak_v1()) messages = str(mock_log.call_args_list) self.assertIn("(root).v2'", messages) self.assertIn("(root).optimizer's state 'm' for (root).v1", messages) self.assertNotIn("(root).v1'", messages) self.assertIn("expect_partial()", messages) # pylint: disable=cell-var-from-loop @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testWithDefun(self): with self.test_session(): num_training_steps = 2 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): with testing_utils.device(should_use_gpu=True): model = MyModel() # Don't actually train so we can test variable values optimizer = adam.Adam(0.) root = tf.train.Checkpoint( optimizer=optimizer, model=model) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) status = root.restore(save_path=checkpoint_path) def train_fn(): @tf.function def _call_model(x): return model(x) with tf.GradientTape() as tape: loss = _call_model(tf.constant([[3.]])) gradients = tape.gradient(loss, model.variables) return optimizer.apply_gradients(zip(gradients, model.variables)) if not tf.executing_eagerly(): train_fn = functools.partial( self.evaluate, train_fn()) status.initialize_or_restore() for _ in range(num_training_steps): train_fn() if training_continuation > 0: status.assert_consumed() self.assertAllClose([[42.]], self.evaluate(model.variables[0])) else: self.evaluate(model.variables[0].assign([[42.]])) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, self.evaluate(optimizer.iterations)) self.assertEqual(training_continuation + 1, self.evaluate(root.save_counter)) # pylint: enable=cell-var-from-loop @combinations.generate(combinations.combine(mode=["eager"])) def testAnonymousVarsInInit(self): class Model(training.Model): def __init__(self): super(Model, self).__init__() self.w = tf.Variable(0.0) self.b = tf.Variable(0.0) self.vars = [self.w, self.b] def call(self, x): return x * self.w + self.b model = Model() optimizer = adam.Adam(learning_rate=0.05) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") checkpoint = tf.train.Checkpoint( model=model, optimizer=optimizer) for _ in range(2): checkpoint.save(checkpoint_prefix) with tf.GradientTape() as tape: loss = (tf.constant(1.) - model(tf.constant(1.))) ** 2 grad = tape.gradient(loss, model.vars) optimizer.apply_gradients( [(g, v) for g, v in zip(grad, model.vars)]) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testDeferredSlotRestoration(self): with self.test_session(): checkpoint_directory = self.get_temp_dir() root = tf.train.Checkpoint() root.var = trackable_utils.add_variable( root, name="var", initializer=0.) optimizer = adam.Adam(0.1) variables = [root.var] gradients = [1.] train_op = optimizer.apply_gradients(zip(gradients, variables)) # Note that `optimizer` has not been added as a dependency of # `root`. Create a one-off grouping so that slot variables for `root.var` # get initialized too. self.evaluate(trackable_utils.gather_initializers( tf.train.Checkpoint(root=root, optimizer=optimizer))) self.evaluate(train_op) self.evaluate(tf.compat.v1.assign(root.var, 12.)) no_slots_path = root.save(os.path.join(checkpoint_directory, "no_slots")) root.optimizer = optimizer self.evaluate(tf.compat.v1.assign(root.var, 13.)) self.evaluate(tf.compat.v1.assign( optimizer.get_slot(slot_name="m", var=root.var), 14.)) slots_path = root.save(os.path.join(checkpoint_directory, "with_slots")) new_root = tf.train.Checkpoint() # Load the slot-containing checkpoint (deferred), then immediately # overwrite the non-slot variable (also deferred). slot_status = new_root.restore(slots_path) no_slot_status = new_root.restore(no_slots_path) with self.assertRaises(AssertionError): no_slot_status.assert_consumed() new_root.var = trackable_utils.add_variable( new_root, name="var", shape=[]) no_slot_status.assert_consumed() no_slot_status.run_restore_ops() self.assertEqual(12., self.evaluate(new_root.var)) new_root.optimizer = adam.Adam(0.1) slot_status.assert_existing_objects_matched() if not tf.executing_eagerly(): with self.assertRaisesRegex(AssertionError, "Unresolved object"): slot_status.assert_consumed() self.assertEqual(12., self.evaluate(new_root.var)) if tf.executing_eagerly(): # Slot variables are only created with restoring initializers when # executing eagerly. self.assertEqual(14., self.evaluate( new_root.optimizer.get_slot(slot_name="m", var=new_root.var))) else: # Slot variables are not created eagerly when graph building. with self.assertRaises(KeyError): new_root.optimizer.get_slot(slot_name="m", var=new_root.var) variables = [new_root.var] gradients = [1.] train_op = new_root.optimizer.apply_gradients(zip(gradients, variables)) # The slot variable now exists; restore() didn't create it, but we should # now have a restore op for it. slot_status.run_restore_ops() if not tf.executing_eagerly(): # The train op hasn't run when graph building, so the slot variable has # its restored value. It has run in eager, so the value will # be different. self.assertEqual(14., self.evaluate( new_root.optimizer.get_slot(slot_name="m", var=new_root.var))) self.evaluate(train_op) slot_status.assert_consumed() def testManySavesGraph(self): """Saves after the first should not modify the graph.""" with context.graph_mode(): graph = tf.Graph() with graph.as_default(), self.session(graph): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") obj = tf.train.Checkpoint() obj.var = tf.Variable(0., name="v") obj.opt = adam.Adam(0.1) variables = [obj.var] gradients = [1.] obj.opt.apply_gradients(zip(gradients, variables)) self.evaluate(trackable_utils.gather_initializers(obj)) obj.save(checkpoint_prefix) graph.finalize() obj.save(checkpoint_prefix) def testManyRestoresGraph(self): """Restores after the first should not modify the graph.""" with context.graph_mode(): graph = tf.Graph() with graph.as_default(), self.session(graph): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") obj = tf.train.Checkpoint() obj.var = tf.Variable(0., name="v") obj.opt = adam.Adam(0.1) variables = [obj.var] gradients = [1.] obj.opt.apply_gradients(zip(gradients, variables)) self.evaluate(trackable_utils.gather_initializers(obj)) save_path = obj.save(checkpoint_prefix) obj.restore(save_path) graph.finalize() obj.restore(save_path) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def test_sequential(self): with self.test_session(): model = sequential.Sequential() checkpoint = tf.train.Checkpoint(model=model) model.add(core.Dense(4)) second_dense = core.Dense(5) model.add(second_dense) model(tf.constant([[1.]])) checkpoint.restore(None).initialize_or_restore() self.evaluate(second_dense.bias.assign( tf.constant([1., 2., 3., 4., 5.]))) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") save_path = checkpoint.save(checkpoint_prefix) self.evaluate(second_dense.bias.assign( tf.constant([5., 6., 7., 8., 9.]))) checkpoint.restore(save_path).assert_consumed().run_restore_ops() self.assertAllEqual([1., 2., 3., 4., 5.], self.evaluate(second_dense.bias)) deferred_sequential = sequential.Sequential() deferred_sequential_checkpoint = tf.train.Checkpoint( model=deferred_sequential) status = deferred_sequential_checkpoint.restore(save_path) deferred_sequential.add(core.Dense(4)) deferred_second_dense = core.Dense(5) deferred_sequential.add(deferred_second_dense) deferred_sequential(tf.constant([[1.]])) status.run_restore_ops() self.assertAllEqual([1., 2., 3., 4., 5.], self.evaluate(deferred_second_dense.bias)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def test_initialize_if_not_restoring(self): with self.test_session(): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") optimizer_only_prefix = os.path.join(checkpoint_directory, "opt") with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = adam.Adam(0.001) root = tf.train.Checkpoint( model=model) # Do not save the optimizer with the checkpoint. optimizer_checkpoint = tf.train.Checkpoint( optimizer=optimizer) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) status = root.restore(save_path=checkpoint_path) input_value = tf.constant([[3.]]) def train_fn(): with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) return optimizer.apply_gradients(zip(gradients, variables)) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) status.initialize_or_restore() # TODO(tanzheny): Add hyper variables to .variables(), and set them with # set_weights etc. variables_not_in_the_variables_property = [ obj for obj in optimizer._hyper.values() if isinstance(obj, tf.Variable)] self.evaluate([v.initializer for v in optimizer.variables() + variables_not_in_the_variables_property]) train_fn() model_save_path = root.save(file_prefix=checkpoint_prefix) self.evaluate(optimizer.beta_1.assign(42.)) optimizer_save_path = optimizer_checkpoint.save(optimizer_only_prefix) del train_fn # Restore into a graph with the optimizer with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = adam.Adam(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model) status = root.restore(save_path=model_save_path) input_value = tf.constant([[3.]]) def train_fn1(): with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) return optimizer.apply_gradients(zip(gradients, variables)) if not tf.executing_eagerly(): train_fn1 = functools.partial(self.evaluate, train_fn1()) status.initialize_or_restore() train_fn1() with self.assertRaises(AssertionError): status.assert_existing_objects_matched() with self.assertRaises(AssertionError): status.assert_consumed() del train_fn1 # Make sure initialization doesn't clobber later restores with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = adam.Adam(0.001, beta_1=1.0) root = tf.train.Checkpoint( optimizer=optimizer, model=model) opt_root = tf.train.Checkpoint( optimizer=optimizer) status = root.restore(save_path=model_save_path) init_only_optimizer_status = opt_root.restore(save_path=None) optimizer_status = opt_root.restore(save_path=optimizer_save_path) input_value = tf.constant([[3.]]) def train_fn2(): with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) return optimizer.apply_gradients(zip(gradients, variables)) if not tf.executing_eagerly(): train_fn2 = functools.partial(self.evaluate, train_fn2()) optimizer_status.run_restore_ops() status.initialize_or_restore() init_only_optimizer_status.initialize_or_restore() train_fn2() self.assertEqual(42., self.evaluate(optimizer.beta_1)) class _ManualScope(tf.Module): def __call__(self): with tf.compat.v1.variable_scope("ManualScope") as vs: self.variable_scope = vs with trackable_utils.capture_dependencies(template=self): return self._build() def _build(self): return tf.compat.v1.get_variable(name="in_manual_scope", shape=[]) @combinations.generate(combinations.combine(mode=["graph", "eager"])) class TemplateTests(keras_parameterized.TestCase): def test_trackable_save_restore(self): with self.test_session(): def _templated(): v = tf.compat.v1.get_variable( "v", shape=[1], initializer=tf.compat.v1.zeros_initializer(), use_resource=True) v2 = tf.compat.v1.get_variable( "v2", shape=[1], initializer=tf.compat.v1.zeros_initializer(), use_resource=True) manual = _ManualScope() return v, v + 1., v2, manual, manual() save_template = tf.compat.v1.make_template("s1", _templated) v1_save, _, v2_save, manual_scope, manual_scope_v = save_template() self.assertEqual( set([id(v1_save), id(v2_save), id(manual_scope), id(manual_scope_v), id(save_template)]), set(map(id, trackable_utils.list_objects(save_template)))) manual_dep, = manual_scope._checkpoint_dependencies self.assertEqual("in_manual_scope", manual_dep.name) self.assertIs(manual_scope_v, manual_dep.ref) optimizer = adam.Adam(0.0) save_root = tf.train.Checkpoint( my_template=save_template, optimizer=optimizer) optimizer.minimize(v1_save.read_value, var_list=[v1_save]) self.evaluate([v.initializer for v in save_template.variables]) optimizer_variables = optimizer.variables() + list( optimizer._hyper.values()) self.evaluate([v.initializer for v in optimizer_variables]) self.evaluate(v1_save.assign([12.])) self.evaluate(v2_save.assign([14.])) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") save_path = save_root.save(checkpoint_prefix) load_template = tf.compat.v1.make_template("s2", _templated) load_optimizer = adam.Adam(0.0) load_root = tf.train.Checkpoint( my_template=load_template, optimizer=load_optimizer) status = load_root.restore(save_path) var, var_plus_one, var2, _, _ = load_template() load_optimizer.minimize(var.read_value, var_list=[var]) self.assertLen(load_template._checkpoint_dependencies, 3) self.assertEqual("v", load_template._checkpoint_dependencies[0].name) self.assertEqual("v2", load_template._checkpoint_dependencies[1].name) self.assertEqual("ManualScope", load_template._checkpoint_dependencies[2].name) status.assert_consumed().run_restore_ops() self.assertAllEqual([12.], self.evaluate(var)) self.assertAllEqual([13.], self.evaluate(var_plus_one)) self.assertAllEqual([14.], self.evaluate(var2)) class CheckpointCompatibilityTests(keras_parameterized.TestCase): def _initialized_model(self): input_value = tf.constant([[3.]]) model = MyModel() optimizer = adam.Adam(0.001) root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) train_op = optimizer.apply_gradients(zip(gradients, variables)) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) # A regular variable, a slot variable, and a non-slot Optimizer variable # with known values to check when loading. self.evaluate(model._named_dense.bias.assign([1.])) self.evaluate(optimizer.get_slot( var=model._named_dense.bias, slot_name="m").assign([2.])) self.evaluate(optimizer.beta_1.assign(3.)) return root_trackable def _set_sentinels(self, root_trackable): self.evaluate(root_trackable.model._named_dense.bias.assign([101.])) self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, slot_name="m") .assign([102.])) self.evaluate(root_trackable.optimizer.beta_1.assign(103.)) def _check_sentinels(self, root_trackable): self.assertAllEqual( [1.], self.evaluate(root_trackable.model._named_dense.bias)) self.assertAllEqual([2.], self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, slot_name="m"))) self.assertAllEqual(3., self.evaluate(root_trackable.optimizer.beta_1)) def _write_name_based_checkpoint(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph) as session: root = self._initialized_model() name_saver = tf.compat.v1.train.Saver() return name_saver.save( sess=session, save_path=checkpoint_prefix, global_step=root.optimizer.iterations) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testLoadFromNameBasedSaver(self): """Save a name-based checkpoint, load it using the object-based API.""" with testing_utils.device(should_use_gpu=True): with self.test_session(): save_path = self._write_name_based_checkpoint() root = self._initialized_model() self._set_sentinels(root) with self.assertRaises(AssertionError): self._check_sentinels(root) object_saver = tf.__internal__.tracking.TrackableSaver( tf.__internal__.tracking.ObjectGraphView(root)) self._set_sentinels(root) status = object_saver.restore(save_path) if tf.executing_eagerly(): self._check_sentinels(root) if tf.executing_eagerly(): status.assert_consumed() status.assert_existing_objects_matched() status.assert_nontrivial_match() else: # When graph building, we haven't read any keys, so we don't know # whether the restore will be complete. with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_consumed() with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_existing_objects_matched() with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_nontrivial_match() status.run_restore_ops() self._check_sentinels(root) self._set_sentinels(root) status = object_saver.restore(save_path) status.initialize_or_restore() status.assert_nontrivial_match() self._check_sentinels(root) # Check that there is no error when keys are missing from the name-based # checkpoint. root.not_in_name_checkpoint = tf.Variable([1.]) status = object_saver.restore(save_path) with self.assertRaises(AssertionError): status.assert_existing_objects_matched() def testSaveGraphLoadEager(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph): root = self._initialized_model() save_path = root.save(file_prefix=checkpoint_prefix) with tf.__internal__.eager_context.eager_mode(): root = self._initialized_model() self._set_sentinels(root) root.restore(save_path).assert_consumed() self._check_sentinels(root) def testSaveEagerLoadGraph(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with tf.__internal__.eager_context.eager_mode(): root = self._initialized_model() save_path = root.save(file_prefix=checkpoint_prefix) with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph): root = self._initialized_model() self._set_sentinels(root) root.restore(save_path).assert_consumed().run_restore_ops() self._check_sentinels(root) def testIgnoreSaveCounter(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with self.cached_session() as session: # Create and save a model using Saver() before using a Checkpoint. This # generates a snapshot without the Checkpoint's `save_counter`. model = sequential.Sequential() model.add(core.Flatten(input_shape=(1,))) model.add(core.Dense(1)) name_saver = tf.compat.v1.train.Saver(model.trainable_variables) save_path = name_saver.save( sess=session, save_path=checkpoint_prefix, global_step=1) # Checkpoint.restore must successfully load that checkpoint. ckpt = tf.train.Checkpoint(model=model) status = ckpt.restore(save_path) status.assert_existing_objects_matched() # It should, however, refuse to load a checkpoint where an unrelated # `save_counter` variable is missing. model.layers[1].var = tf.Variable(0., name="save_counter") status = ckpt.restore(save_path) with self.assertRaises(AssertionError): status.assert_existing_objects_matched() if __name__ == "__main__": tf.compat.v1.enable_eager_execution() tf.test.main()
38,981
42.458194
84
py
keras
keras-master/keras/tests/integration_test.py
# 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. # ============================================================================== """Integration tests for Keras.""" import tensorflow.compat.v2 as tf import os import random import numpy as np import keras from keras import keras_parameterized from keras import testing_utils from keras.layers.legacy_rnn import rnn_cell_impl as rnn_cell from keras.legacy_tf_layers import base as base_layer from keras.utils import np_utils class KerasIntegrationTest(keras_parameterized.TestCase): def _save_and_reload_model(self, model): self.temp_dir = self.get_temp_dir() fpath = os.path.join(self.temp_dir, 'test_model_%s' % (random.randint(0, 1e7),)) if tf.executing_eagerly(): save_format = 'tf' else: if (not isinstance(model, keras.Sequential) and not model._is_graph_network): return model # Not supported save_format = 'h5' model.save(fpath, save_format=save_format) model = keras.models.load_model(fpath) return model @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes class VectorClassificationIntegrationTest(keras_parameterized.TestCase): def test_vector_classification(self): np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train) model = testing_utils.get_model_from_layers( [keras.layers.Dense(16, activation='relu'), keras.layers.Dropout(0.1), keras.layers.Dense(y_train.shape[-1], activation='softmax')], input_shape=x_train.shape[1:]) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(x_train, y_train, epochs=10, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) def test_vector_classification_shared_model(self): # Test that Sequential models that feature internal updates # and internal losses can be shared. np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train) base_model = testing_utils.get_model_from_layers( [keras.layers.Dense(16, activation='relu', kernel_regularizer=keras.regularizers.l2(1e-5), bias_regularizer=keras.regularizers.l2(1e-5)), keras.layers.BatchNormalization()], input_shape=x_train.shape[1:]) x = keras.layers.Input(x_train.shape[1:]) y = base_model(x) y = keras.layers.Dense(y_train.shape[-1], activation='softmax')(y) model = keras.models.Model(x, y) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) self.assertLen(model.losses, 2) if not tf.executing_eagerly(): self.assertLen(model.get_updates_for(x), 2) history = model.fit(x_train, y_train, epochs=10, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) @keras_parameterized.run_all_keras_modes class SequentialIntegrationTest(KerasIntegrationTest): def test_sequential_save_and_pop(self): # Test the following sequence of actions: # - construct a Sequential model and train it # - save it # - load it # - pop its last layer and add a new layer instead # - continue training np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train) model = keras.Sequential([ keras.layers.Dense(16, activation='relu'), keras.layers.Dropout(0.1), keras.layers.Dense(y_train.shape[-1], activation='softmax') ]) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) model.fit(x_train, y_train, epochs=1, batch_size=10, validation_data=(x_train, y_train), verbose=2) model = self._save_and_reload_model(model) model.pop() model.add(keras.layers.Dense(y_train.shape[-1], activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(x_train, y_train, epochs=10, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) model = self._save_and_reload_model(model) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) # See b/122473407 @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class TimeseriesClassificationIntegrationTest(keras_parameterized.TestCase): @keras_parameterized.run_with_all_model_types def test_timeseries_classification(self): np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(4, 10), num_classes=2) y_train = np_utils.to_categorical(y_train) layers = [ keras.layers.LSTM(5, return_sequences=True), keras.layers.GRU(y_train.shape[-1], activation='softmax') ] model = testing_utils.get_model_from_layers( layers, input_shape=x_train.shape[1:]) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(x_train, y_train, epochs=15, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) def test_timeseries_classification_sequential_tf_rnn(self): np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(4, 10), num_classes=2) y_train = np_utils.to_categorical(y_train) with base_layer.keras_style_scope(): model = keras.models.Sequential() model.add(keras.layers.RNN(rnn_cell.LSTMCell(5), return_sequences=True, input_shape=x_train.shape[1:])) model.add(keras.layers.RNN(rnn_cell.GRUCell(y_train.shape[-1], activation='softmax', dtype=tf.float32))) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(x_train, y_train, epochs=15, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) @keras_parameterized.run_with_all_model_types @keras_parameterized.run_all_keras_modes class ImageClassificationIntegrationTest(keras_parameterized.TestCase): def test_image_classification(self): np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(10, 10, 3), num_classes=2) y_train = np_utils.to_categorical(y_train) layers = [ keras.layers.Conv2D(4, 3, padding='same', activation='relu'), keras.layers.Conv2D(8, 3, padding='same'), keras.layers.BatchNormalization(), keras.layers.Conv2D(8, 3, padding='same'), keras.layers.Flatten(), keras.layers.Dense(y_train.shape[-1], activation='softmax') ] model = testing_utils.get_model_from_layers( layers, input_shape=x_train.shape[1:]) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['acc'], run_eagerly=testing_utils.should_run_eagerly()) history = model.fit(x_train, y_train, epochs=10, batch_size=10, validation_data=(x_train, y_train), verbose=2) self.assertGreater(history.history['val_acc'][-1], 0.7) _, val_acc = model.evaluate(x_train, y_train) self.assertAlmostEqual(history.history['val_acc'][-1], val_acc) predictions = model.predict(x_train) self.assertEqual(predictions.shape, (x_train.shape[0], 2)) @keras_parameterized.run_all_keras_modes class ActivationV2IntegrationTest(keras_parameterized.TestCase): """Tests activation function V2 in model exporting and loading. This test is to verify in TF 2.x, when 'tf.nn.softmax' is used as an activation function, its model exporting and loading work as expected. Check b/123041942 for details. """ def test_serialization_v2_model(self): np.random.seed(1337) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=100, test_samples=0, input_shape=(10,), num_classes=2) y_train = np_utils.to_categorical(y_train) model = keras.Sequential([ keras.layers.Flatten(input_shape=x_train.shape[1:]), keras.layers.Dense(10, activation=tf.nn.relu), # To mimic 'tf.nn.softmax' used in TF 2.x. keras.layers.Dense(y_train.shape[-1], activation=tf.math.softmax), ]) # Check if 'softmax' is in model.get_config(). last_layer_activation = model.get_layer(index=2).get_config()['activation'] self.assertEqual(last_layer_activation, 'softmax') model.compile( loss='categorical_crossentropy', optimizer=keras.optimizer_v2.adam.Adam(0.005), metrics=['accuracy'], run_eagerly=testing_utils.should_run_eagerly()) model.fit(x_train, y_train, epochs=2, batch_size=10, validation_data=(x_train, y_train), verbose=2) output_path = os.path.join(self.get_temp_dir(), 'tf_keras_saved_model') model.save(output_path, save_format='tf') loaded_model = keras.models.load_model(output_path) self.assertEqual(model.summary(), loaded_model.summary()) if __name__ == '__main__': tf.test.main()
12,541
37.950311
80
py
keras
keras-master/keras/tests/tracking_util_with_v1_optimizers_test.py
# Copyright 2017 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 object-based saving which use tf.train.* optimizers.""" import tensorflow.compat.v2 as tf import functools import os from tensorflow.python.eager import context from tensorflow.python.framework import test_util from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.engine import training from keras.layers import core from tensorflow.python.training.tracking import util as trackable_utils class NonLayerTrackable(tf.Module): def __init__(self): super(NonLayerTrackable, self).__init__() self.a_variable = trackable_utils.add_variable( self, name="a_variable", shape=[]) # pylint: disable=not-callable class MyModel(training.Model): """A concrete Model for testing.""" def __init__(self): super(MyModel, self).__init__() self._named_dense = core.Dense(1, use_bias=True) self._second = core.Dense(1, use_bias=False) # We can still track Trackables which aren't Layers. self._non_layer = NonLayerTrackable() def call(self, values): ret = self._second(self._named_dense(values)) return ret class CheckpointingTests(keras_parameterized.TestCase): @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True) def testNamingWithOptimizer(self): input_value = tf.constant([[3.]]) model = MyModel() # A nuisance Model using the same optimizer. Its slot variables should not # go in the checkpoint, since it is never depended on. other_model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) optimizer_step = tf.compat.v1.train.get_or_create_global_step() root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=optimizer_step) if tf.executing_eagerly(): optimizer.minimize( lambda: model(input_value), global_step=optimizer_step) optimizer.minimize( lambda: other_model(input_value), global_step=optimizer_step) else: train_op = optimizer.minimize( model(input_value), global_step=optimizer_step) optimizer.minimize( other_model(input_value), global_step=optimizer_step) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) named_variables, serialized_graph, _ = tf.__internal__.tracking.ObjectGraphView( root_trackable).serialize_object_graph() expected_checkpoint_names = ( # Created in the root node, so no prefix. "optimizer_step", "model/_second/kernel", "model/_named_dense/kernel", "model/_named_dense/bias", # non-Layer dependency of the model "model/_non_layer/a_variable", # The optimizer creates two non-slot variables "optimizer/beta1_power", "optimizer/beta2_power", # Slot variables "model/_second/kernel/.OPTIMIZER_SLOT/optimizer/m", "model/_second/kernel/.OPTIMIZER_SLOT/optimizer/v", "model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/m", "model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/v", "model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/m", "model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/v", ) suffix = "/.ATTRIBUTES/VARIABLE_VALUE" expected_checkpoint_names = [ name + suffix for name in expected_checkpoint_names] named_variables = {v.name: v for v in named_variables} self.assertEqual(len(expected_checkpoint_names), len(named_variables.keys())) # Check that we've mapped to the right variable objects (not exhaustive) self.assertEqual( "global_step", named_variables["optimizer_step" + suffix].full_name) self.assertEqual( "my_model/dense_1/kernel", named_variables["model/_second/kernel" + suffix].full_name) self.assertEqual( "my_model/dense/kernel", named_variables["model/_named_dense/kernel" + suffix].full_name) self.assertEqual( "beta1_power", named_variables["optimizer/beta1_power" + suffix].full_name) self.assertEqual( "beta2_power", named_variables["optimizer/beta2_power" + suffix].full_name) # Spot check the generated protocol buffers. self.assertEqual("optimizer", serialized_graph.nodes[0].children[1].local_name) optimizer_node = serialized_graph.nodes[serialized_graph.nodes[0].children[ 1].node_id] self.assertEqual("beta1_power", optimizer_node.children[0].local_name) self.assertEqual("beta1_power", serialized_graph.nodes[optimizer_node.children[0].node_id] .attributes[0].full_name) self.assertEqual( "my_model/dense/kernel", serialized_graph.nodes[optimizer_node.slot_variables[0] .original_variable_node_id] .attributes[0].full_name) # We strip off the :0 suffix, as variable.name-based saving does. self.assertEqual( "my_model/dense/kernel/Adam", serialized_graph.nodes[optimizer_node.slot_variables[0] .slot_variable_node_id] .attributes[0].full_name) self.assertEqual( "my_model/dense/kernel/Adam:0", optimizer.get_slot( var=model._named_dense.kernel, name="m").name) self.assertEqual( "model/_named_dense/kernel" + suffix, serialized_graph.nodes[ optimizer_node.slot_variables[0] .original_variable_node_id].attributes[0].checkpoint_key) self.assertEqual("m", optimizer_node.slot_variables[0].slot_name) self.assertEqual( "model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/m" + suffix, serialized_graph.nodes[ optimizer_node.slot_variables[0] .slot_variable_node_id].attributes[0].checkpoint_key) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testSaveRestore(self): with self.test_session(): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model) input_value = tf.constant([[3.]]) if tf.executing_eagerly(): optimizer.minimize( lambda: model(input_value)) else: train_op = optimizer.minimize(model(input_value)) # TODO(allenl): Make initialization more pleasant when graph building. root_trackable.save_counter # pylint: disable=pointless-statement self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) prefix = os.path.join(self.get_temp_dir(), "ckpt") self.evaluate(tf.compat.v1.assign(model._named_dense.variables[1], [42.])) m_bias_slot = optimizer.get_slot(model._named_dense.variables[1], "m") self.evaluate(tf.compat.v1.assign(m_bias_slot, [1.5])) save_path = root_trackable.save(file_prefix=prefix) self.evaluate(tf.compat.v1.assign(model._named_dense.variables[1], [43.])) self.evaluate(tf.compat.v1.assign(root_trackable.save_counter, 3)) optimizer_variables = self.evaluate(optimizer.variables()) self.evaluate(tf.compat.v1.assign(m_bias_slot, [-2.])) # Immediate restoration status = root_trackable.restore(save_path=save_path).assert_consumed() status.run_restore_ops() self.assertAllEqual([42.], self.evaluate(model._named_dense.variables[1])) self.assertAllEqual(1, self.evaluate(root_trackable.save_counter)) self.assertAllEqual([1.5], self.evaluate(m_bias_slot)) if not tf.executing_eagerly(): return # Restore-on-create is only supported when executing eagerly on_create_model = MyModel() on_create_optimizer = tf.compat.v1.train.AdamOptimizer( 0.001, # Preserve beta1_power and beta2_power when applying gradients # so we can test that they've been restored correctly. beta1=1.0, beta2=1.0) on_create_root = tf.train.Checkpoint( optimizer=on_create_optimizer, model=on_create_model) # Deferred restoration status = on_create_root.restore(save_path=save_path) status.assert_nontrivial_match() status.assert_existing_objects_matched() with self.assertRaises(AssertionError): status.assert_consumed() on_create_model(tf.constant([[3.]])) # create variables self.assertAllEqual(1, self.evaluate(on_create_root.save_counter)) self.assertAllEqual([42.], self.evaluate( on_create_model._named_dense.variables[1])) on_create_m_bias_slot = on_create_optimizer.get_slot( on_create_model._named_dense.variables[1], "m") status.assert_existing_objects_matched() with self.assertRaises(AssertionError): status.assert_consumed() # Optimizer slot variables are created when the original variable is # restored. self.assertAllEqual([1.5], self.evaluate(on_create_m_bias_slot)) self.assertAllEqual(optimizer_variables[2:], self.evaluate(on_create_optimizer.variables())) dummy_var = tf.Variable([1.]) on_create_optimizer.minimize(loss=dummy_var.read_value) status.assert_existing_objects_matched() status.assert_consumed() beta1_power, beta2_power = on_create_optimizer._get_beta_accumulators() self.assertAllEqual(optimizer_variables[0], self.evaluate(beta1_power)) self.assertAllEqual(optimizer_variables[1], self.evaluate(beta2_power)) # TODO(allenl): Debug garbage created by this test in python3. def testDeferredRestorationUsageEager(self): """An idiomatic eager execution example.""" num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=tf.compat.v1.train.get_or_create_global_step()) root.restore(tf.train.latest_checkpoint( checkpoint_directory)) for _ in range(num_training_steps): # TODO(allenl): Use a Dataset and serialize/checkpoint it. input_value = tf.constant([[3.]]) optimizer.minimize( lambda: model(input_value), # pylint: disable=cell-var-from-loop global_step=root.optimizer_step) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, root.optimizer_step.numpy()) def testEagerDistributionStrategy(self): num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") def _train_fn(optimizer, model, root): input_value = tf.constant([[3.]]) optimizer.minimize( functools.partial(model, input_value), global_step=root.optimizer_step) strategy = tf.distribute.MirroredStrategy() with strategy.scope(): for training_continuation in range(3): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=tf.compat.v1.train.get_or_create_global_step()) root.restore( tf.train.latest_checkpoint(checkpoint_directory)) for _ in range(num_training_steps): strategy.extended.call_for_each_replica( functools.partial(_train_fn, optimizer, model, root)) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, root.optimizer_step.numpy()) def testGraphDistributionStrategy(self): self.skipTest("b/121381184") num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") def _train_fn(optimizer, model, root): input_value = tf.constant([[3.]]) return optimizer.minimize( functools.partial(model, input_value), global_step=root.optimizer_step) for training_continuation in range(3): with tf.Graph().as_default(): strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=tf.compat.v1.train.get_or_create_global_step()) status = root.restore(tf.train.latest_checkpoint( checkpoint_directory)) train_op = strategy.extended.call_for_each_replica( functools.partial(_train_fn, optimizer, model, root)) with self.session() as session: if training_continuation > 0: status.assert_consumed() status.initialize_or_restore() for _ in range(num_training_steps): session.run(train_op) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, root.optimizer_step.numpy()) def testUsageGraph(self): """Expected usage when graph building.""" with context.graph_mode(): num_training_steps = 10 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): with tf.Graph().as_default(): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.compat.v1.train.Checkpoint( optimizer=optimizer, model=model, global_step=tf.compat.v1.train.get_or_create_global_step()) input_value = tf.constant([[3.]]) train_op = optimizer.minimize( model(input_value), global_step=root.global_step) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) with self.session(graph=tf.compat.v1.get_default_graph()) as session: status = root.restore(save_path=checkpoint_path) status.initialize_or_restore(session=session) if checkpoint_path is None: self.assertEqual(0, training_continuation) with self.assertRaises(AssertionError): status.assert_consumed() with self.assertRaises(AssertionError): status.assert_existing_objects_matched() else: status.assert_consumed() status.assert_existing_objects_matched() for _ in range(num_training_steps): session.run(train_op) root.save(file_prefix=checkpoint_prefix, session=session) self.assertEqual((training_continuation + 1) * num_training_steps, session.run(root.global_step)) self.assertEqual(training_continuation + 1, session.run(root.save_counter)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testAgnosticUsage(self): """Graph/eager agnostic usage.""" # Does create garbage when executing eagerly due to ops.Graph() creation. with self.test_session(): num_training_steps = 10 checkpoint_directory = self.get_temp_dir() for training_continuation in range(3): with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model, global_step=tf.compat.v1.train.get_or_create_global_step()) manager = tf.train.CheckpointManager( root, checkpoint_directory, max_to_keep=1) status = root.restore(save_path=manager.latest_checkpoint) input_value = tf.constant([[3.]]) train_fn = functools.partial( optimizer.minimize, functools.partial(model, input_value), global_step=root.global_step) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) status.initialize_or_restore() for _ in range(num_training_steps): train_fn() manager.save() self.assertEqual((training_continuation + 1) * num_training_steps, self.evaluate(root.global_step)) self.assertEqual(training_continuation + 1, self.evaluate(root.save_counter)) # pylint: disable=cell-var-from-loop @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testWithDefun(self): with self.test_session(): num_training_steps = 2 checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") for training_continuation in range(3): with testing_utils.device(should_use_gpu=True): model = MyModel() # Don't actually train so we can test variable values optimizer = tf.compat.v1.train.AdamOptimizer(0.) root = tf.train.Checkpoint( optimizer=optimizer, model=model, global_step=tf.compat.v1.train.get_or_create_global_step()) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) status = root.restore(save_path=checkpoint_path) def train_fn(): @tf.function def _call_model(x): return model(x) with tf.GradientTape() as tape: loss = _call_model(tf.constant([[3.]])) gradients = tape.gradient(loss, model.variables) return optimizer.apply_gradients(zip(gradients, model.variables), global_step=root.global_step) if not tf.executing_eagerly(): train_fn = functools.partial( self.evaluate, train_fn()) status.initialize_or_restore() for _ in range(num_training_steps): train_fn() if training_continuation > 0: status.assert_consumed() self.assertAllClose([[42.]], self.evaluate(model.variables[0])) else: self.evaluate(model.variables[0].assign([[42.]])) root.save(file_prefix=checkpoint_prefix) self.assertEqual((training_continuation + 1) * num_training_steps, self.evaluate(root.global_step)) self.assertEqual(training_continuation + 1, self.evaluate(root.save_counter)) # pylint: enable=cell-var-from-loop @combinations.generate(combinations.combine(mode=["eager"])) def testAnonymousVarsInInit(self): class Model(training.Model): def __init__(self): super(Model, self).__init__() self.w = tf.Variable(0.0) self.b = tf.Variable(0.0) self.vars = [self.w, self.b] def call(self, x): return x * self.w + self.b model = Model() optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.05) checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") checkpoint = tf.train.Checkpoint( model=model, optimizer=optimizer) for _ in range(2): checkpoint.save(checkpoint_prefix) with tf.GradientTape() as tape: loss = (tf.constant(1.) - model(tf.constant(1.))) ** 2 grad = tape.gradient(loss, model.vars) optimizer.apply_gradients( [(g, v) for g, v in zip(grad, model.vars)]) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def test_initialize_if_not_restoring(self): with self.test_session(): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") optimizer_only_prefix = os.path.join(checkpoint_directory, "opt") with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( model=model, # Do not save the optimizer with the checkpoint. global_step=tf.compat.v1.train.get_or_create_global_step()) optimizer_checkpoint = tf.train.Checkpoint( optimizer=optimizer) checkpoint_path = tf.train.latest_checkpoint( checkpoint_directory) status = root.restore(save_path=checkpoint_path) input_value = tf.constant([[3.]]) train_fn = functools.partial( optimizer.minimize, functools.partial(model, input_value), global_step=root.global_step) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) status.initialize_or_restore() self.evaluate([v.initializer for v in optimizer.variables()]) train_fn() model_save_path = root.save(file_prefix=checkpoint_prefix) self.evaluate(optimizer.variables()[0].assign(42.)) optimizer_save_path = optimizer_checkpoint.save(optimizer_only_prefix) # Restore into a graph with the optimizer with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model, global_step=tf.compat.v1.train.get_or_create_global_step()) status = root.restore(save_path=model_save_path) input_value = tf.constant([[3.]]) train_fn = functools.partial( optimizer.minimize, functools.partial(model, input_value), global_step=root.global_step) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) status.initialize_or_restore() train_fn() with self.assertRaises(AssertionError): status.assert_existing_objects_matched() with self.assertRaises(AssertionError): status.assert_consumed() # Make sure initialization doesn't clobber later restores with testing_utils.device(should_use_gpu=True): model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001, beta1=1.0) root = tf.train.Checkpoint( optimizer=optimizer, model=model, global_step=tf.compat.v1.train.get_or_create_global_step()) opt_root = tf.train.Checkpoint( optimizer=optimizer) status = root.restore(save_path=model_save_path) init_only_optimizer_status = opt_root.restore(save_path=None) optimizer_status = opt_root.restore(save_path=optimizer_save_path) input_value = tf.constant([[3.]]) train_fn = functools.partial( optimizer.minimize, functools.partial(model, input_value), global_step=root.global_step) if not tf.executing_eagerly(): train_fn = functools.partial(self.evaluate, train_fn()) optimizer_status.run_restore_ops() status.initialize_or_restore() init_only_optimizer_status.initialize_or_restore() train_fn() self.assertEqual(42., self.evaluate(optimizer.variables()[0])) class CheckpointCompatibilityTests(keras_parameterized.TestCase): def _initialized_model(self): input_value = tf.constant([[3.]]) model = MyModel() optimizer = tf.compat.v1.train.AdamOptimizer(0.001) optimizer_step = tf.compat.v1.train.get_or_create_global_step() root_trackable = tf.train.Checkpoint( optimizer=optimizer, model=model, optimizer_step=optimizer_step) train_op = optimizer.minimize( functools.partial(model, input_value), global_step=optimizer_step) self.evaluate(trackable_utils.gather_initializers( root_trackable)) self.evaluate(train_op) # A regular variable, a slot variable, and a non-slot Optimizer variable # with known values to check when loading. self.evaluate(model._named_dense.bias.assign([1.])) self.evaluate(optimizer.get_slot( var=model._named_dense.bias, name="m").assign([2.])) beta1_power, _ = optimizer._get_beta_accumulators() self.evaluate(beta1_power.assign(3.)) return root_trackable def _set_sentinels(self, root_trackable): self.evaluate(root_trackable.model._named_dense.bias.assign([101.])) self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, name="m") .assign([102.])) beta1_power, _ = root_trackable.optimizer._get_beta_accumulators() self.evaluate(beta1_power.assign(103.)) def _check_sentinels(self, root_trackable): self.assertAllEqual( [1.], self.evaluate(root_trackable.model._named_dense.bias)) self.assertAllEqual([2.], self.evaluate( root_trackable.optimizer.get_slot( var=root_trackable.model._named_dense.bias, name="m"))) beta1_power, _ = root_trackable.optimizer._get_beta_accumulators() self.assertAllEqual(3., self.evaluate(beta1_power)) def _write_name_based_checkpoint(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph) as session: root = self._initialized_model() name_saver = tf.compat.v1.train.Saver() return name_saver.save( sess=session, save_path=checkpoint_prefix, global_step=root.optimizer_step) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testLoadFromNameBasedSaver(self): """Save a name-based checkpoint, load it using the object-based API.""" with testing_utils.device(should_use_gpu=True): with self.test_session(): save_path = self._write_name_based_checkpoint() root = self._initialized_model() self._set_sentinels(root) with self.assertRaises(AssertionError): self._check_sentinels(root) object_saver = tf.__internal__.tracking.TrackableSaver( tf.__internal__.tracking.ObjectGraphView(root)) self._set_sentinels(root) status = object_saver.restore(save_path) if tf.executing_eagerly(): self._check_sentinels(root) if tf.executing_eagerly(): status.assert_consumed() status.assert_existing_objects_matched() status.assert_nontrivial_match() else: # When graph building, we haven't read any keys, so we don't know # whether the restore will be complete. with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_consumed() with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_existing_objects_matched() with self.assertRaisesRegex(AssertionError, "not restored"): status.assert_nontrivial_match() status.run_restore_ops() self._check_sentinels(root) self._set_sentinels(root) status = object_saver.restore(save_path) status.initialize_or_restore() self._check_sentinels(root) # Check that there is no error when keys are missing from the name-based # checkpoint. root.not_in_name_checkpoint = tf.Variable([1.]) status = object_saver.restore(save_path) with self.assertRaises(AssertionError): status.assert_existing_objects_matched() def testSaveGraphLoadEager(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph): root = self._initialized_model() save_path = root.save(file_prefix=checkpoint_prefix) with tf.__internal__.eager_context.eager_mode(): root = self._initialized_model() self._set_sentinels(root) root.restore(save_path).assert_consumed() self._check_sentinels(root) def testSaveEagerLoadGraph(self): checkpoint_directory = self.get_temp_dir() checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") with tf.__internal__.eager_context.eager_mode(): root = self._initialized_model() save_path = root.save(file_prefix=checkpoint_prefix) with context.graph_mode(): save_graph = tf.Graph() with save_graph.as_default(), self.session( graph=save_graph): root = self._initialized_model() self._set_sentinels(root) root.restore(save_path).assert_consumed().run_restore_ops() self._check_sentinels(root) if __name__ == "__main__": tf.compat.v1.enable_eager_execution() tf.test.main()
30,012
42.878655
84
py
keras
keras-master/keras/tests/custom_training_loop_test.py
# 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 custom training loops.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import testing_utils class LayerWithLosses(keras.layers.Layer): def build(self, input_shape): self.v = self.add_weight( name='hey', shape=(), initializer='ones', regularizer=keras.regularizers.l1(100)) def call(self, inputs): self.add_loss(tf.reduce_sum(inputs)) return self.v * inputs class LayerWithMetrics(keras.layers.Layer): def build(self, input_shape): self.mean = keras.metrics.Mean(name='mean_object') def call(self, inputs): self.add_metric( tf.reduce_mean(inputs), name='mean_tensor', aggregation='mean') self.add_metric(self.mean(inputs)) return inputs class LayerWithTrainingArg(keras.layers.Layer): def call(self, inputs, training=None): self.training = training if training: return inputs else: return 0. * inputs def add_loss_step(defun): optimizer = keras.optimizer_v2.adam.Adam() model = testing_utils.get_model_from_layers([LayerWithLosses()], input_shape=(10,)) def train_step(x): with tf.GradientTape() as tape: model(x) assert len(model.losses) == 2 loss = tf.reduce_sum(model.losses) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) return loss if defun: train_step = tf.function(train_step) x = tf.ones((10, 10)) return train_step(x) def batch_norm_step(defun): optimizer = keras.optimizer_v2.adadelta.Adadelta() model = testing_utils.get_model_from_layers([ keras.layers.BatchNormalization(momentum=0.9), keras.layers.Dense(1, kernel_initializer='zeros', activation='softmax') ], input_shape=(10,)) def train_step(x, y): with tf.GradientTape() as tape: y_pred = model(x, training=True) loss = keras.losses.binary_crossentropy(y, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) return loss, model(x, training=False) if defun: train_step = tf.function(train_step) x, y = tf.ones((10, 10)), tf.ones((10, 1)) return train_step(x, y) def add_metric_step(defun): optimizer = keras.optimizer_v2.rmsprop.RMSprop() model = testing_utils.get_model_from_layers([ LayerWithMetrics(), keras.layers.Dense(1, kernel_initializer='zeros', activation='softmax') ], input_shape=(10,)) def train_step(x, y): with tf.GradientTape() as tape: y_pred_1 = model(x) y_pred_2 = model(2 * x) y_pred = y_pred_1 + y_pred_2 loss = keras.losses.mean_squared_error(y, y_pred) gradients = tape.gradient(loss, model.trainable_weights) optimizer.apply_gradients(zip(gradients, model.trainable_weights)) assert len(model.metrics) == 2 return [m.result() for m in model.metrics] if defun: train_step = tf.function(train_step) x, y = tf.ones((10, 10)), tf.zeros((10, 1)) metrics = train_step(x, y) assert np.allclose(metrics[0], 1.5) assert np.allclose(metrics[1], 1.5) return metrics @keras_parameterized.run_with_all_model_types class CustomTrainingLoopTest(keras_parameterized.TestCase): @parameterized.named_parameters(('add_loss_step', add_loss_step), ('add_metric_step', add_metric_step), ('batch_norm_step', batch_norm_step)) def test_eager_and_tf_function(self, train_step): eager_result = train_step(defun=False) fn_result = train_step(defun=True) self.assertAllClose(eager_result, fn_result) @parameterized.named_parameters(('eager', False), ('defun', True)) def test_training_arg_propagation(self, defun): model = testing_utils.get_model_from_layers([LayerWithTrainingArg()], input_shape=(1,)) def train_step(x): return model(x), model(x, training=False), model(x, training=True) if defun: train_step = tf.function(train_step) x = tf.ones((1, 1)) results = train_step(x) self.assertAllClose(results[0], tf.zeros((1, 1))) self.assertAllClose(results[1], tf.zeros((1, 1))) self.assertAllClose(results[2], tf.ones((1, 1))) @parameterized.named_parameters(('eager', False), ('defun', True)) def test_learning_phase_propagation(self, defun): class MyModel(keras.layers.Layer): def __init__(self): super(MyModel, self).__init__() self.layer = LayerWithTrainingArg() def call(self, inputs): return self.layer(inputs) model = MyModel() def train_step(x): no_learning_phase_out = model(x) self.assertFalse(model.layer.training) with keras.backend.learning_phase_scope(0): inf_learning_phase_out = model(x) self.assertEqual(model.layer.training, 0) with keras.backend.learning_phase_scope(1): train_learning_phase_out = model(x) self.assertEqual(model.layer.training, 1) return [ no_learning_phase_out, inf_learning_phase_out, train_learning_phase_out ] if defun: train_step = tf.function(train_step) x = tf.ones((1, 1)) results = train_step(x) self.assertAllClose(results[0], tf.zeros((1, 1))) self.assertAllClose(results[1], tf.zeros((1, 1))) self.assertAllClose(results[2], tf.ones((1, 1))) @parameterized.named_parameters(('eager', False), ('defun', True)) def test_training_arg_priorities(self, defun): class MyModel(keras.layers.Layer): def __init__(self): super(MyModel, self).__init__() self.layer = LayerWithTrainingArg() def call(self, inputs, training=False): return self.layer(inputs) model = MyModel() def train_step(x): explicit_out = model(x, training=True) default_out = model(x) with keras.backend.learning_phase_scope(1): parent_out = model(x, training=False) lr_out = model(x) return [explicit_out, default_out, parent_out, lr_out] if defun: train_step = tf.function(train_step) x = tf.ones((1, 1)) results = train_step(x) self.assertAllClose(results[0], tf.ones((1, 1))) self.assertAllClose(results[1], tf.zeros((1, 1))) self.assertAllClose(results[2], tf.zeros((1, 1))) self.assertAllClose(results[3], tf.ones((1, 1))) if __name__ == '__main__': tf.compat.v1.enable_eager_execution() tf.test.main()
7,407
30.12605
80
py
keras
keras-master/keras/tests/model_subclassing_test.py
# 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 Model subclassing.""" import tensorflow.compat.v2 as tf import copy import os from absl.testing import parameterized import numpy as np import keras from tensorflow.python.framework import test_util from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.tests import model_subclassing_test_util as model_util from tensorflow.python.training.tracking import data_structures try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None @keras_parameterized.run_all_keras_modes class ModelSubclassingTest(keras_parameterized.TestCase): def test_custom_build(self): class DummyModel(keras.Model): def __init__(self): super(DummyModel, self).__init__() self.dense1 = keras.layers.Dense(32, activation='relu') self.uses_custom_build = False def call(self, inputs): return self.dense1(inputs) def build(self, input_shape): self.uses_custom_build = True test_model = DummyModel() dummy_data = tf.ones((32, 50)) test_model(dummy_data) self.assertTrue(test_model.uses_custom_build, 'Model should use user ' 'defined build when called.') def test_attribute_conflict_error(self): class ModelWithProperty(keras.Model): @property def read_only(self): return 1. m = ModelWithProperty() with self.assertRaisesRegex(AttributeError, 'read_only'): m.read_only = 2. def test_custom_build_with_fit(self): class DummyModel(keras.Model): def __init__(self): super(DummyModel, self).__init__() self.layer1 = keras.layers.Dense(10, activation='relu') def build(self, input_shape): self.layer2 = keras.layers.Dense(1, activation='relu') def call(self, inputs): return self.layer2(self.layer1(inputs)) model = DummyModel() model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) model.fit(np.ones((10, 10)), np.ones((10, 1)), batch_size=2, epochs=2) self.assertLen(model.layers, 2) self.assertLen(model.trainable_variables, 4) def test_dataset_dict_with_fit(self): class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = keras.layers.Dense(1) self.dense2 = keras.layers.Dense(1) self.add = keras.layers.Add() def call(self, x): return self.add([self.dense1(x['a']), self.dense2(x['b'])]) model = MyModel() model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) data = tf.data.Dataset.from_tensor_slices(({ 'a': np.ones((32, 10)), 'b': np.ones((32, 20)) }, np.ones((32, 1)))).batch(2) model.fit(data, epochs=2) def test_invalid_input_shape_build(self): num_classes = 2 input_dim = 50 model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) with self.assertRaisesRegex(ValueError, 'input shape is not one of the valid types'): model.build(input_shape=tf.compat.v1.Dimension(input_dim)) def test_embed_dtype_with_subclass_build(self): class Embedding(keras.layers.Layer): """An Embedding layer.""" def __init__(self, vocab_size, embedding_dim, **kwargs): super(Embedding, self).__init__(**kwargs) self.vocab_size = vocab_size self.embedding_dim = embedding_dim def build(self, _): self.embedding = self.add_variable( 'embedding_kernel', shape=[self.vocab_size, self.embedding_dim], dtype=np.float32, initializer=tf.compat.v1.random_uniform_initializer(-0.1, 0.1), trainable=True) def call(self, x): return tf.compat.v1.nn.embedding_lookup(self.embedding, x) class EmbedModel(keras.Model): def __init__(self, vocab_size, embed_size): super(EmbedModel, self).__init__() self.embed1 = Embedding(vocab_size, embed_size) def call(self, inputs): return self.embed1(inputs) model = EmbedModel(100, 20) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) with self.assertRaisesRegex( ValueError, 'if your layers do not support float type inputs'): model.build(input_shape=(35, 20)) def test_single_time_step_rnn_build(self): dim = 4 timesteps = 1 batch_input_shape = (None, timesteps, dim) units = 3 class SimpleRNNModel(keras.Model): def __init__(self): super(SimpleRNNModel, self).__init__() self.lstm = keras.layers.LSTM(units) def call(self, inputs): return self.lstm(inputs) model = SimpleRNNModel() self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build(batch_input_shape) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') model(tf.ones((32, timesteps, dim))) def test_single_io_subclass_build(self): num_classes = 2 input_dim = 50 batch_size = None model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build(input_shape=(batch_size, input_dim)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') model(tf.ones((32, input_dim))) def test_single_io_dimension_subclass_build(self): num_classes = 2 input_dim = tf.compat.v1.Dimension(50) batch_size = tf.compat.v1.Dimension(None) model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build(input_shape=(batch_size, input_dim)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') model(tf.ones((32, input_dim))) def test_multidim_io_subclass_build(self): num_classes = 10 # Input size, e.g. image batch_size = 32 input_shape = (32, 32, 3) model = model_util.SimpleConvTestModel(num_classes) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) batch_input_shape = (batch_size,) + input_shape model.build(input_shape=batch_input_shape) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') model(tf.ones(batch_input_shape)) def test_tensorshape_io_subclass_build(self): num_classes = 10 # Input size, e.g. image batch_size = None input_shape = (32, 32, 3) model = model_util.SimpleConvTestModel(num_classes) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build( input_shape=tf.TensorShape((batch_size,) + input_shape)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') model(tf.ones((32,) + input_shape)) def test_subclass_save_model(self): num_classes = 10 # Input size, e.g. image batch_size = None input_shape = (32, 32, 3) model = model_util.SimpleConvTestModel(num_classes) self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build( input_shape=tf.TensorShape((batch_size,) + input_shape)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') weights = model.get_weights() tf_format_name = os.path.join(self.get_temp_dir(), 'ckpt') model.save_weights(tf_format_name) if h5py is not None: hdf5_format_name = os.path.join(self.get_temp_dir(), 'weights.h5') model.save_weights(hdf5_format_name) model = model_util.SimpleConvTestModel(num_classes) model.build( input_shape=tf.TensorShape((batch_size,) + input_shape)) if h5py is not None: model.load_weights(hdf5_format_name) self.assertAllClose(weights, model.get_weights()) model.load_weights(tf_format_name) self.assertAllClose(weights, model.get_weights()) def test_multi_io_subclass_build(self): batch_size = None num_samples = 1000 input_dim = 50 model = model_util.get_multi_io_subclass_model() self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) batch_input_shape = tf.TensorShape((batch_size, input_dim)) model.build( input_shape=[batch_input_shape, batch_input_shape]) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') x1 = tf.ones((num_samples, input_dim)) x2 = tf.ones((num_samples, input_dim)) model([x1, x2]) def test_summary(self): class ToString: def __init__(self): self.contents = '' def __call__(self, msg): self.contents += msg + '\n' # Single-io model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=4, use_bn=True, use_dp=True) model(np.ones((3, 4))) # need to build model first print_fn = ToString() model.summary(print_fn=print_fn) self.assertIn('Trainable params: 356', print_fn.contents) # Multi-io model = model_util.get_multi_io_subclass_model( num_classes=(5, 6), use_bn=True, use_dp=True) model([np.ones((3, 4)), np.ones((3, 4))]) # need to build model first print_fn = ToString() model.summary(print_fn=print_fn) self.assertIn('Trainable params: 587', print_fn.contents) # Single-io with unused layer model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=4, use_bn=True, use_dp=True) model.unused_layer = keras.layers.Dense(10) model(np.ones((3, 4))) # need to build model first print_fn = ToString() model.summary(print_fn=print_fn) self.assertIn('Trainable params: 356', print_fn.contents) self.assertIn('0 (unused)', print_fn.contents) def test_no_dependency(self): class Foo(keras.Model): def __init__(self): super(Foo, self).__init__() self.isdep = keras.layers.Dense(1) self.notdep = data_structures.NoDependency(keras.layers.Dense(2)) self.notdep_var = data_structures.NoDependency( tf.Variable(1., name='notdep_var')) m = Foo() self.assertEqual([m.isdep, m.notdep], m.layers) self.assertEqual(1, len(m._checkpoint_dependencies)) self.assertIs(m.isdep, m._checkpoint_dependencies[0].ref) self.assertEqual('notdep_var:0', m.notdep_var.name) def test_extra_variable(self): class ExtraVar(keras.Model): def __init__(self): super(ExtraVar, self).__init__() self.dense = keras.layers.Dense(1) self.var = tf.Variable(1.) self.not_trainable_var = tf.Variable(2., trainable=False) def call(self, inputs): return self.dense(inputs + self.var) m = ExtraVar() self.assertTrue(m.trainable) self.assertEqual([m.dense], m.layers) self.assertEqual([m.var, m.not_trainable_var], m.variables) self.assertEqual([m.var], m.trainable_variables) self.assertEqual([m.not_trainable_var], m.non_trainable_variables) self.assertLen(m.get_weights(), 2) m.trainable = False self.assertEqual([m.var, m.not_trainable_var], m.variables) self.assertEqual([], m.trainable_variables) self.assertEqual([m.var, m.not_trainable_var], m.non_trainable_variables) self.assertLen(m.get_weights(), 2) m.trainable = True m(tf.ones([1, 1])) self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.variables) self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.weights) self.assertLen(m.get_weights(), 4) self.assertEqual([m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var], m.variables) self.assertEqual([m.dense.kernel, m.dense.bias, m.var], m.trainable_variables) self.assertEqual([m.not_trainable_var], m.non_trainable_variables) m.dense.trainable = False self.assertEqual( [m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var], m.variables) self.assertEqual([m.var], m.trainable_variables) self.assertEqual([m.dense.kernel, m.dense.bias, m.not_trainable_var], m.non_trainable_variables) self.assertLen(m.get_weights(), 4) def test_add_weight_in_model(self): class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.b = self.add_weight('bias', (10,)) self.c = self.add_weight('bias2', (10,), trainable=False) def call(self, inputs): return inputs + self.b + self.c x = tf.convert_to_tensor(np.ones((10, 10), 'float32')) model = MyModel() model(x) self.assertEqual(1, len(model.trainable_weights)) self.assertEqual(1, len(model.non_trainable_weights)) self.assertEqual(2, len(model.weights)) class MyModelCustomBuild(keras.Model): def build(self, input_shape): self.b = self.add_weight('bias', (10,)) self.c = self.add_weight('bias2', (10,), trainable=False) def call(self, inputs): return inputs + self.b + self.c x = tf.convert_to_tensor(np.ones((10, 10), 'float32')) model = MyModelCustomBuild() model(x) self.assertEqual(1, len(model.trainable_weights)) self.assertEqual(1, len(model.non_trainable_weights)) self.assertEqual(2, len(model.weights)) def test_add_update_in_model(self): class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.b = self.add_weight('bias', (10,)) self.c = self.add_weight('bias2', (10,)) def call(self, inputs): # Unconditional self.add_update(self.b.assign(self.b * 2)) # Conditional self.add_update(self.c.assign(inputs[1, :])) return inputs + self.b + self.c x = tf.convert_to_tensor(np.ones((10, 10), 'float32')) model = MyModel() model(x) if tf.executing_eagerly(): self.assertEqual(0, len(model.updates)) else: self.assertEqual(2, len(model.updates)) class GraphSpecificModelSubclassingTests(tf.test.TestCase): def test_single_io_workflow_with_tensors(self): num_classes = 2 num_samples = 10 input_dim = 50 with tf.Graph().as_default(), self.cached_session(): model = testing_utils.SmallSubclassMLP( num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True) model.compile(loss='mse', optimizer='rmsprop') x = tf.ones((num_samples, input_dim)) y = tf.zeros((num_samples, num_classes)) model.fit(x, y, epochs=2, steps_per_epoch=10, verbose=0) _ = model.evaluate(steps=10, verbose=0) def test_multi_io_workflow_with_tensors(self): num_classes = (2, 3) num_samples = 10 input_dim = 50 with tf.Graph().as_default(), self.cached_session(): model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_dp=True, use_bn=True) model.compile(loss='mse', optimizer='rmsprop') x1 = tf.ones((num_samples, input_dim)) x2 = tf.ones((num_samples, input_dim)) y1 = tf.zeros((num_samples, num_classes[0])) y2 = tf.zeros((num_samples, num_classes[1])) model.fit([x1, x2], [y1, y2], epochs=2, steps_per_epoch=10, verbose=0) _ = model.evaluate(steps=10, verbose=0) def test_updates_and_losses_for_nested_models_in_subclassed_model(self): # Case 1: deferred-build sequential nested in subclass. class TestModel1(keras.Model): def __init__(self): super(TestModel1, self).__init__() self.fc = keras.layers.Dense(10, input_shape=(784,), activity_regularizer='l1') self.bn = keras.Sequential([keras.layers.BatchNormalization(axis=1)]) def call(self, x): return self.bn(self.fc(x)) with tf.compat.v1.get_default_graph().as_default(), self.cached_session(): model = TestModel1() x = tf.ones(shape=[100, 784], dtype='float32') model(x) self.assertLen(model.updates, 2) self.assertLen(model.losses, 1) # Case 2: placeholder-sequential nested in subclass. class TestModel2(keras.Model): def __init__(self): super(TestModel2, self).__init__() self.fc = keras.layers.Dense(10, input_shape=(784,), activity_regularizer='l1') self.bn = keras.Sequential( [keras.layers.BatchNormalization(axis=1, input_shape=(10,))]) def call(self, x): return self.bn(self.fc(x)) with tf.compat.v1.get_default_graph().as_default(), self.cached_session(): model = TestModel2() x = tf.ones(shape=[100, 784], dtype='float32') model(x) self.assertEqual(len(model.get_updates_for(x)), 2) self.assertEqual(len(model.get_losses_for(x)), 1) # Case 3: functional-API model nested in subclass. with tf.compat.v1.get_default_graph().as_default(): inputs = keras.Input((10,)) outputs = keras.layers.BatchNormalization(axis=1)(inputs) bn = keras.Model(inputs, outputs) class TestModel3(keras.Model): def __init__(self): super(TestModel3, self).__init__() self.fc = keras.layers.Dense(10, input_shape=(784,), activity_regularizer='l1') self.bn = bn def call(self, x): return self.bn(self.fc(x)) with self.cached_session(): model = TestModel3() x = tf.ones(shape=[100, 784], dtype='float32') model(x) self.assertEqual(len(model.get_updates_for(x)), 2) self.assertEqual(len(model.get_losses_for(x)), 1) def test_multi_io_workflow_with_numpy_arrays_and_custom_placeholders(self): num_classes = (2, 3) num_samples = 1000 input_dim = 50 with tf.Graph().as_default(), self.cached_session(): model = model_util.get_multi_io_subclass_model( num_classes=num_classes, use_dp=True, use_bn=True) model.compile(loss='mse', optimizer='rmsprop') x1 = np.ones((num_samples, input_dim)) x2 = np.ones((num_samples, input_dim)) y1 = np.zeros((num_samples, num_classes[0])) y2 = np.zeros((num_samples, num_classes[1])) x2_placeholder = tf.compat.v1.placeholder( dtype='float32', shape=(None, input_dim)) model._set_inputs([x1, x2_placeholder]) model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0) _ = model.evaluate([x1, x2], [y1, y2], verbose=0) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class CustomCallSignatureTests(tf.test.TestCase, parameterized.TestCase): def test_no_inputs_in_signature(self): model = model_util.CustomCallModel() first = tf.ones([2, 3]) second = tf.ones([2, 5]) output = model(first, second) self.evaluate([v.initializer for v in model.variables]) expected_output = self.evaluate(model.dense1(first) + model.dense2(second)) self.assertAllClose(expected_output, self.evaluate(output)) output = model(first, second, fiddle_with_output='yes') self.assertAllClose(10. * expected_output, self.evaluate(output)) output = model(first, second=second, training=False) self.assertAllClose(expected_output, self.evaluate(output)) def test_training_args_call_build(self): input_dim = 2 model = model_util.TrainingNoDefaultModel() self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build((None, input_dim)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') def test_training_and_mask_args_call_build(self): input_dim = 2 model = model_util.TrainingMaskingModel() self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) model.build((None, input_dim)) self.assertTrue(model.weights, ('Model should have weights now that it ' 'has been properly built.')) self.assertTrue(model.built, 'Model should be built after calling `build`.') def test_custom_call_kwargs_and_build(self): first_input_shape = (2, 3) second_input_shape = (2, 5) model = model_util.CustomCallModel() self.assertFalse(model.built, 'Model should not have been built') self.assertFalse(model.weights, ('Model should have no weights since it ' 'has not been built.')) with self.assertRaisesRegex(ValueError, 'cannot build your model if it has positional'): model.build(input_shape=[first_input_shape, second_input_shape]) def test_kwargs_in_signature(self): class HasKwargs(keras.Model): def call(self, x, y=3, **kwargs): return x model = HasKwargs() arg = tf.ones([1]) model(arg, a=3) if not tf.executing_eagerly(): self.assertLen(model.inputs, 1) @test_util.assert_no_new_tensors @test_util.assert_no_garbage_created def test_training_no_default(self): if not tf.executing_eagerly(): return model = model_util.TrainingNoDefaultModel() arg = tf.ones([1, 1]) model(arg, True) def test_positional_arg_in_call(self): class ModelWithPositionalArgs(keras.Model): def call(self, x, x2, x3=None): return x + x2 x = np.ones((10, 1)) y = np.ones((10, 1)) m = ModelWithPositionalArgs() m.compile('sgd', 'mse') with self.assertRaisesRegex(ValueError, r'Models passed to `fit`'): m.fit(x, y, batch_size=2) with self.assertRaisesRegex(ValueError, r'Models passed to `evaluate`'): m.evaluate(x, y, batch_size=2) with self.assertRaisesRegex(ValueError, r'Models passed to `predict`'): m.predict(x, batch_size=2) with self.assertRaisesRegex(ValueError, r'Models passed to `train_on_batch`'): m.train_on_batch(x, y) with self.assertRaisesRegex(ValueError, r'Models passed to `test_on_batch`'): m.test_on_batch(x, y) with self.assertRaisesRegex(ValueError, r'Models passed to `predict_on_batch`'): m.predict_on_batch(x) def test_deepcopy(self): if not tf.executing_eagerly(): self.skipTest('Run in eager mode only.') class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.my_variable = tf.Variable(0.0, trainable=False) self.layer = keras.layers.Dense(4) def call(self, obs): return self.layer(obs) model = MyModel() model.my_variable.assign_add(1.0) new_model = copy.deepcopy(model) self.assertEqual(model.my_variable.numpy(), 1.0) self.assertEqual(new_model.my_variable.numpy(), 1.0) model.my_variable.assign_add(1.0) self.assertEqual(model.my_variable.numpy(), 2.0) self.assertEqual(new_model.my_variable.numpy(), 1.0) # Check that Trackable logic still works. self.assertLen(new_model.variables, 1) self.assertLen(new_model.layers, 1) def test_batch_counters_not_in_variables(self): class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.layer = keras.layers.Dense(4) def call(self, obs): return self.layer(obs) model = MyModel() model(np.ones((10, 10))) self.assertLen(model.variables, 2) if __name__ == '__main__': tf.test.main()
26,833
34.588859
80
py
keras
keras-master/keras/tests/memory_checker_test.py
# 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 keras import tensorflow.compat.v2 as tf from tensorflow.python.framework.memory_checker import MemoryChecker class MemoryCheckerTest(tf.test.TestCase): def testKerasBasic(self): # TODO(kkb): Fix the slowness on Forge. self.skipTest('This test is too slow on Forge so disabled for now.') x = tf.zeros([1, 1]) y = tf.constant([[3]]) model = keras.models.Sequential() model.add(keras.layers.Dense(1, input_dim=1)) model.compile(loss='mean_squared_error') with MemoryChecker() as memory_checker: for _ in range(10): model.fit(x, y) model.evaluate(x, y) memory_checker.record_snapshot() memory_checker.report() memory_checker.assert_no_leak_if_all_possibly_except_one() def testKerasAdvanced(self): # TODO(kkb): Fix the slowness on Forge. self.skipTest('This test is too slow on Forge so disabled for now.') # A real world example taken from the following. # https://github.com/tensorflow/tensorflow/issues/32500 # b/142150794 with MemoryChecker() as memory_checker: rows = 6 columns = 7 model = keras.Sequential([ keras.layers.Flatten(input_shape=[rows * columns, 3]), keras.layers.Dense(7, input_shape=[rows * columns * 3]), ]) model.compile( optimizer=keras.optimizer_v2.gradient_descent.SGD(lr=0.01), loss='mean_squared_error', metrics=['accuracy']) states = [[1] * rows * columns for _ in range(20)] f = tf.one_hot(states, dtype='float32', depth=3) for _ in range(20): model.predict(f, steps=10) memory_checker.record_snapshot() memory_checker.report() memory_checker.assert_no_leak_if_all_possibly_except_one() if __name__ == '__main__': tf.compat.v1.enable_eager_execution() tf.test.main()
2,527
31.831169
79
py
keras
keras-master/keras/tests/temporal_sample_weights_correctness_test.py
# 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 temporal sample weights correctness using Keras model.""" import tensorflow.compat.v2 as tf import numpy as np from keras import keras_parameterized from keras import layers from keras import metrics from keras import optimizer_v2 from keras import testing_utils class Bias(layers.Layer): """Layer that add a bias to its inputs.""" def build(self, input_shape): self.bias = self.add_variable('bias', (1,), initializer='zeros') def call(self, inputs): return inputs + self.bias def compute_output_shape(self, input_shape): return input_shape def get_multi_io_temporal_model(): timesteps = 2 inp_1 = layers.Input(shape=(1,), name='input_1') inp_2 = layers.Input(shape=(1,), name='input_2') x = layers.RepeatVector(timesteps) out_1 = layers.TimeDistributed(Bias(), name='output_1') out_2 = layers.TimeDistributed(Bias(), name='output_2') branch_a = [inp_1, x, out_1] branch_b = [inp_2, x, out_2] return testing_utils.get_multi_io_model(branch_a, branch_b) def get_compiled_multi_io_model_temporal(sample_weight_mode): model = get_multi_io_temporal_model() model.compile( optimizer=optimizer_v2.gradient_descent.SGD(0.1), loss='mae', metrics=[metrics.MeanAbsoluteError(name='mae')], weighted_metrics=[metrics.MeanAbsoluteError(name='mae_2')], sample_weight_mode=sample_weight_mode, run_eagerly=testing_utils.should_run_eagerly()) return model def run_with_different_sample_weight_mode_inputs(fn, partial_sw=True): """Executes the given function with different sample weight mode inputs. Args: fn: Training or eval function to execute. partial_sw: Boolean flag to indicate whether temporal sample weight mode should be set partially just for one output. """ model = get_compiled_multi_io_model_temporal(sample_weight_mode='temporal') fn(model) model = get_compiled_multi_io_model_temporal( sample_weight_mode=['temporal', 'temporal']) fn(model) model = get_compiled_multi_io_model_temporal(sample_weight_mode={ 'output_1': 'temporal', 'output_2': 'temporal' }) fn(model) if partial_sw: model = get_compiled_multi_io_model_temporal( sample_weight_mode=[None, 'temporal']) fn(model) # TODO(b/129700800): Enable after bug is fixed. # model = get_compiled_multi_io_model_temporal(sample_weight_mode={ # 'output_2': 'temporal' # }) # fn(model) @keras_parameterized.run_with_all_model_types(exclude_models=['sequential']) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class TestMetricsCorrectnessMultiIOTemporal(keras_parameterized.TestCase): def custom_generator_multi_io_temporal(self, sample_weights=None): """Generator for getting data for temporal multi io model. Args: sample_weights: List of sample_weights. Yields: Tuple of inputs, label, sample weights data. """ batch_size = 3 num_samples = 3 iteration = 0 while True: batch_index = iteration * batch_size % num_samples iteration += 1 start = batch_index end = start + batch_size x = [self.x[start:end], self.x[start:end]] y = [self.y1[start:end], self.y2[start:end]] if sample_weights: sw = tf.nest.map_structure(lambda w: w[start:end], sample_weights) else: sw = None yield x, y, sw def setUp(self): super(TestMetricsCorrectnessMultiIOTemporal, self).setUp() self.x = np.asarray([[0.], [1.], [2.]]) self.y1 = np.asarray([[[.5], [1.]], [[2.], [2.5]], [[3.5], [2.5]]]) self.y2 = np.asarray([[[.5], [1.5]], [[2.], [1.5]], [[3.5], [3.]]]) # Without weights: # Epoch 1 - bias = 0 # y_pred_1 = [[[0.], [0.]], [[1.], [1.]], [[2.], [2.]]] # y_pred_2 = [[[0.], [0.]], [[1.], [1.]], [[2.], [2.]]] # mae (y1 - y_pred_1) = [[[.5], [1.]], [[1.], [1.5]], [[1.5], [.5]]] # mae = [[3/3, 3/3]] = [[1, 1]] = 2/2 = 1 # mae_2 (y2 - y_pred_2) = [[[.5], [1.5]], [[1.], [.5]], [[1.5], [1.]]] # mae_2 = [[3/3, 3/3]] = [[1, 1]] = 2/2 = 1 # Epoch 2 - bias = 0.1 (2/2 * 0.1) # y_pred_1 = [[[.1], [.1]], [[1.1], [1.1]], [[2.1], [2.1]]] # y_pred_2 = [[[.1], [.1]], [[1.1], [1.1]], [[2.1], [2.1]]] # mae (y1 - y_pred_1) = [[[.4], [.9]], [[.9], [1.4]], [[1.4], [.4]]] # mae = [[2.7/3, 2.7/3]] = [[0.9, 0.9]] = 1.8/2 = 0.9 # mae_2 (y2 - y_pred_2) = [[[.4], [1.4]], [[.9], [.4]], [[1.4], [.9]]] # mae_2 = [[2.7/3, 2.7/3]] = [[0.9, 0.9]] = 1.8/2 = 0.9 self.expected_fit_result = { 'output_1_mae': [1, 0.9], 'output_2_mae': [1, 0.9], 'output_1_mae_2': [1, 0.9], 'output_2_mae_2': [1, 0.9], 'loss': [2., 1.8], 'output_1_loss': [1, 0.9], 'output_2_loss': [1, 0.9], } self.sample_weight_1 = np.asarray([[.5, 2.], [.5, 2.], [.5, 2.]]) self.sample_weight_2 = np.asarray([[2., .5], [2., .5], [2., .5]]) # With weights: # Epoch 1 # y_pred_1 = [[[0.], [0.]], [[1.], [1.]], [[2.], [2.]]] # y_pred_2 = [[[0.], [0.]], [[1.], [1.]], [[2.], [2.]]] # mae (y1 - y_pred_1) = [[[.5], [1.]], [[1.], [1.5]], [[1.5], [.5]]] # with weights = [[[.5 * .5], [1 * 2]], # [[1 * .5], [1.5 * 2]], # [[1.5 * .5], [.5 * 2]]] # mae (w/o weights) = [[3/3, 3/3]] = [[1, 1]] = 2/2 = 1 # mae (weighted mean) = [[1.5/1.5, 6/6]] = [[1, 1]] = 2/2 = 1 # mae (sum over bs) = [[1.5/3, 6/3]] = [[.5, 2]] = 2.5/2 = 1.25 # mae_2 (y2 - y_pred_2) = [[[.5], [1.5]], [[1.], [.5]], [[1.5], [1.]]] # with weights = [[[.5 * 2], [1.5 * .5]], # [[1. * 2], [.5 * .5]], # [[1.5 * 2], [1. * .5]]] # mae_2 (w/o weights) = [[3/3, 3/3]] = [[1, 1]] = 2/2 = 1 # mae_2 (weighted mean) = [[6/6, 1.5/1.5]] = [[1, 1]] = 2/2 = 1 # mae_2 (sum over bs) = [[6/3, 1.5/3]] = [[2, .5]] = 2.5/2 = 1.25 # Epoch 2 - bias = 0.125 (2.5/2 * 0.1) # y_pred_1 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], [2.125]]] # y_pred_2 = [[[0.125], [0.125]], [[1.125], [1.125]], [[2.125], [2.125]]] # mae (y1 - y_pred_1) = [[[.375], [.875]], # [[.875], [1.375]], # [[1.375], [.375]]] # with weights = [[[.375 * .5], [.875 * 2.]], # [[.875 * .5], [1.375 * 2.]], # [[1.375 * .5], [.375 * 2.]]] # mae (w/o weights) = [[2.625/3, 2.625/3]] = (.875+.875)/2 = .875 # mae (weighted mean) = [[1.3125/1.5, 5.25/6]] = (.875+.875)/2 = .875 # mae (sum over bs) = [[1.3125/3, 5.25/3]] = (0.4375+1.75)/2 = 1.09375 # mae_2 (y2 - y_pred_2) = [[[.375], [1.375]], # [[.875], [.375]], # [[1.375], [.875]]] # with weights = [[[.375 * 2.], [1.375 * .5]], # [[.875 * 2.], [.375 * .5]], # [[1.375 * 2.], [.875 * .5]]] # mae_2 (w/o weights) = [[2.625/3, 2.625/3]] = (.875+.875)/2 = .875 # mae_2 (weighted mean) = [[5.25/6, 1.3125/1.5]] = (.875+.875)/2 = .875 # mae_2 (sum over bs) = [[5.25/3, 1.3125/3]] = (1.75+0.4375)/2 = 1.09375 self.expected_fit_result_with_weights = { 'output_1_mae': [1, 0.875], 'output_2_mae': [1, 0.875], 'output_1_mae_2': [1, 0.875], 'output_2_mae_2': [1, 0.875], 'loss': [2.5, 2.1875], 'output_1_loss': [1.25, 1.09375], 'output_2_loss': [1.25, 1.09375], } self.expected_fit_result_with_weights_output_2 = { 'output_1_mae': [1., 0.9], 'output_2_mae': [1, 0.875], 'output_1_mae_2': [1., 0.9], 'output_2_mae_2': [1., 0.875], 'loss': [2.25, 1.99375], 'output_1_loss': [1., 0.9], 'output_2_loss': [1.25, 1.09375], } # In the order: 'loss', 'output_1_loss', 'output_2_loss', # 'output_1_mae', 'output_1_mae_2', # 'output_2_mae', 'output_2_mae_2' self.expected_batch_result_with_weights = [ 2.1875, 1.09375, 1.09375, 0.875, 0.875, 0.875, 0.875 ] self.expected_batch_result_with_weights_output_2 = [ 1.99375, 0.9, 1.09375, 0.9, 0.9, 0.875, 0.875 ] self.expected_batch_result = [1.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9] def test_fit(self): def _train_and_assert(model): history = model.fit([self.x, self.x], [self.y1, self.y2], batch_size=3, epochs=2, shuffle=False) for key, value in self.expected_fit_result.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_fit_with_sample_weight(self): def _train_and_assert(model): history = model.fit([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }, batch_size=3, epochs=2, shuffle=False) for key, value in self.expected_fit_result_with_weights.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs( _train_and_assert, partial_sw=False) def test_fit_with_partial_sample_weight(self): def _train_and_assert(model): history = model.fit([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }, batch_size=3, epochs=2, shuffle=False) for key, value in self.expected_fit_result_with_weights_output_2.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_eval(self): def _eval_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2]) eval_result = model.evaluate([self.x, self.x], [self.y1, self.y2], batch_size=3) self.assertAllClose(eval_result, self.expected_batch_result, 1e-3) run_with_different_sample_weight_mode_inputs(_eval_and_assert) def test_eval_with_sample_weight(self): def _eval_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) eval_result = model.evaluate([self.x, self.x], [self.y1, self.y2], batch_size=3, sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) self.assertAllClose(eval_result, self.expected_batch_result_with_weights, 1e-3) run_with_different_sample_weight_mode_inputs( _eval_and_assert, partial_sw=False) def test_eval_with_partial_sample_weight(self): def _eval_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }) eval_result = model.evaluate([self.x, self.x], [self.y1, self.y2], batch_size=3, sample_weight={ 'output_2': self.sample_weight_2, }) self.assertAllClose(eval_result, self.expected_batch_result_with_weights_output_2, 1e-3) run_with_different_sample_weight_mode_inputs(_eval_and_assert) def test_train_on_batch(self): def _train_and_assert(model): for _ in range(2): result = model.train_on_batch([self.x, self.x], [self.y1, self.y2]) self.assertAllClose(result, self.expected_batch_result, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_train_on_batch_with_sample_weight(self): def _train_and_assert(model): for _ in range(2): result = model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) self.assertAllClose(result, self.expected_batch_result_with_weights, 1e-3) run_with_different_sample_weight_mode_inputs( _train_and_assert, partial_sw=False) def test_train_on_batch_with_partial_sample_weight(self): def _train_and_assert(model): for _ in range(2): result = model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }) self.assertAllClose(result, self.expected_batch_result_with_weights_output_2, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_test_on_batch(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2]) result = model.test_on_batch([self.x, self.x], [self.y1, self.y2]) self.assertAllClose(result, self.expected_batch_result, 1e-3) run_with_different_sample_weight_mode_inputs(_test_and_assert) def test_test_on_batch_with_sample_weight(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) result = model.test_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) self.assertAllClose(result, self.expected_batch_result_with_weights, 1e-3) run_with_different_sample_weight_mode_inputs( _test_and_assert, partial_sw=False) def test_test_on_batch_with_partial_sample_weight(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }) result = model.test_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }) self.assertAllClose(result, self.expected_batch_result_with_weights_output_2, 1e-3) run_with_different_sample_weight_mode_inputs(_test_and_assert) def test_fit_generator(self): def _train_and_assert(model): history = model.fit_generator( self.custom_generator_multi_io_temporal(), steps_per_epoch=1, epochs=2) for key, value in self.expected_fit_result.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_fit_generator_with_sample_weight(self): def _train_and_assert(model): history = model.fit_generator( self.custom_generator_multi_io_temporal( sample_weights=[self.sample_weight_1, self.sample_weight_2]), steps_per_epoch=1, epochs=2) for key, value in self.expected_fit_result_with_weights.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs( _train_and_assert, partial_sw=False) def test_fit_generator_with_partial_sample_weight(self): def _train_and_assert(model): history = model.fit_generator( self.custom_generator_multi_io_temporal( sample_weights={'output_2': self.sample_weight_2}), steps_per_epoch=1, epochs=2) for key, value in self.expected_fit_result_with_weights_output_2.items(): self.assertAllClose(history.history[key], value, 1e-3) run_with_different_sample_weight_mode_inputs(_train_and_assert) def test_eval_generator(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2]) eval_result = model.evaluate_generator( self.custom_generator_multi_io_temporal(), steps=1) self.assertAllClose(eval_result, self.expected_batch_result, 1e-3) run_with_different_sample_weight_mode_inputs(_test_and_assert) def test_eval_generator_with_sample_weight(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_1': self.sample_weight_1, 'output_2': self.sample_weight_2, }) eval_result = model.evaluate_generator( self.custom_generator_multi_io_temporal( sample_weights=[self.sample_weight_1, self.sample_weight_2]), steps=2) self.assertAllClose(eval_result, self.expected_batch_result_with_weights, 1e-3) run_with_different_sample_weight_mode_inputs( _test_and_assert, partial_sw=False) def test_eval_generator_with_partial_sample_weight(self): def _test_and_assert(model): model.train_on_batch([self.x, self.x], [self.y1, self.y2], sample_weight={ 'output_2': self.sample_weight_2, }) eval_result = model.evaluate_generator( self.custom_generator_multi_io_temporal( sample_weights={'output_2': self.sample_weight_2}), steps=2) self.assertAllClose(eval_result, self.expected_batch_result_with_weights_output_2, 1e-3) run_with_different_sample_weight_mode_inputs(_test_and_assert) def test_error_on_fit_with_class_weight(self): def _train_and_assert(model): with self.assertRaises(ValueError): model.fit([self.x, self.x], [self.y1, self.y2], class_weight={'output_1': { .5: .5, 2.: .5, 3.5: .5 }}, batch_size=3, epochs=2, shuffle=False) run_with_different_sample_weight_mode_inputs(_train_and_assert) if __name__ == '__main__': tf.test.main()
20,210
38.168605
80
py
keras
keras-master/keras/tests/memory_test.py
# 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 memory leaks in eager execution. It is possible that this test suite will eventually become flaky due to taking too long to run (since the tests iterate many times), but for now they are helpful for finding memory leaks since not all PyObject leaks are found by introspection (test_util decorators). Please be careful adding new tests here. """ import tensorflow.compat.v2 as tf import keras from tensorflow.python.eager.memory_tests import memory_test_util class SingleLayerNet(keras.Model): """Simple keras model used to ensure that there are no leaks.""" def __init__(self): super(SingleLayerNet, self).__init__() self.fc1 = keras.layers.Dense(5) def call(self, x): return self.fc1(x) class MemoryTest(tf.test.TestCase): def testMemoryLeakInSimpleModelForwardOnly(self): if not memory_test_util.memory_profiler_is_available(): self.skipTest("memory_profiler required to run this test") inputs = tf.zeros([32, 100], tf.float32) net = SingleLayerNet() def f(): with tf.GradientTape(): net(inputs) memory_test_util.assert_no_leak(f) def testMemoryLeakInSimpleModelForwardAndBackward(self): if not memory_test_util.memory_profiler_is_available(): self.skipTest("memory_profiler required to run this test") inputs = tf.zeros([32, 100], tf.float32) net = SingleLayerNet() def f(): with tf.GradientTape() as tape: result = net(inputs) tape.gradient(result, net.variables) del tape memory_test_util.assert_no_leak(f) if __name__ == "__main__": tf.test.main()
2,293
29.586667
80
py
keras
keras-master/keras/tests/automatic_outside_compilation_test.py
# 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 automatic outside compilation for TF 2.0/Keras.""" import collections import os from absl import flags from keras import callbacks from keras.distribute import distribute_strategy_test from keras.engine import base_layer from keras.engine import sequential as sequential_model_lib from keras.engine import training from keras.layers import convolutional as conv_layer_lib from keras.layers import core as layer_lib from keras.layers import pooling as pool_layer_lib import numpy as np import tensorflow.compat.v2 as tf from tensorboard.plugins.histogram import summary_v2 as histogram_summary_v2 from tensorboard.plugins.image import summary_v2 as image_summary_v2 from tensorboard.plugins.scalar import summary_v2 as scalar_summary_v2 from tensorflow.python.eager.context import set_soft_device_placement # pylint: disable=g-direct-tensorflow-import from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import NUM_CLASSES = 4 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.') 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 LayerForScalarSummary(base_layer.Layer): """A pass-through layer that only records scalar values to summary.""" def call(self, x): # Add summary scalar using compat v2 implementation. scalar_summary_v2.scalar('custom_scalar_summary_v2', tf.reduce_sum(x)) return x class LayerForImageSummary(base_layer.Layer): """A pass-through layer that only records image values to summary.""" def call(self, x): # Add summary image using compat v2 implementation. image_summary_v2.image('custom_image_summary_v2', x) return x class LayerForHistogramSummary(base_layer.Layer): """A pass-through layer that records histogram values to summary.""" def call(self, x): # Add summary histogram using compat v2 implementation. histogram_summary_v2.histogram('custom_histogram_summary_v2', x) return x class CustomModel(training.Model): """Custom model with summary ops in model call definition.""" def __init__(self, name=None, enable_histograms=True): super(CustomModel, self).__init__() self._my_layers = [ layer_lib.Dense( 4096, name='dense1', kernel_initializer=tf.compat.v1.glorot_normal_initializer(seed=0), use_bias=False), layer_lib.Dense( 4, name='dense2', kernel_initializer=tf.compat.v1.glorot_normal_initializer(seed=0), use_bias=False), ] if enable_histograms: self.histogram_summary_layer = LayerForHistogramSummary() else: self.histogram_summary_layer = base_layer.Layer() # no-op pass through self.scalar_summary_layer = LayerForScalarSummary() def call(self, x): for layer in self._my_layers: x = layer(x) x = self.scalar_summary_layer(x) return self.histogram_summary_layer(x) def get_image_dataset(): inputs = np.zeros((10, 28, 28, 3), dtype=np.float32) targets = np.zeros((10, NUM_CLASSES), dtype=np.float32) dataset = tf.data.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) dataset = dataset.batch(10, drop_remainder=True) return dataset def mnist_model(input_shape, enable_histograms=True): """Creates a MNIST model.""" model = sequential_model_lib.Sequential() # Adding custom pass-through layer to visualize input images. model.add(LayerForImageSummary()) model.add( conv_layer_lib.Conv2D( 32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(conv_layer_lib.Conv2D(64, (3, 3), activation='relu')) model.add(pool_layer_lib.MaxPooling2D(pool_size=(2, 2))) model.add(layer_lib.Dropout(0.25)) model.add(layer_lib.Flatten()) model.add(layer_lib.Dense(128, activation='relu')) model.add(layer_lib.Dropout(0.5)) model.add(layer_lib.Dense(NUM_CLASSES, activation='softmax')) # Adding custom pass-through layer for summary recording. if enable_histograms: model.add(LayerForHistogramSummary()) return model class AutoOutsideCompilationWithKerasTest(tf.test.TestCase): def setUp(self): super(AutoOutsideCompilationWithKerasTest, self).setUp() tf.compat.v1.enable_v2_behavior() set_soft_device_placement(True) self.summary_dir = self.get_temp_dir() def validate_recorded_sumary_file(self, event_files, expected_event_counts): event_counts = collections.defaultdict(int) for event_file in event_files: for e in tf.compat.v1.train.summary_iterator(event_file): for v in e.summary.value: event_counts[v.tag] += 1 event_counts = dict(event_counts) # Avoid defaultdict type in repr below. # Populate a count of 0 for tags that were expected but not found. actual_event_counts = { tag: event_counts.get(tag, 0) for tag in expected_event_counts } self.assertEqual( expected_event_counts, actual_event_counts, msg='expected counts not found; all event counts: %r' % event_counts) def testV2SummaryWithKerasSequentialModel(self): # Histogram summaries require the MLIR bridge; see b/178826597#comment107. # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove this # if histogram summaries are supported fully on non-MLIR bridge or # non-MLIR bridge is no longer run. enable_histograms = test_util.is_mlir_bridge_enabled() strategy = get_tpu_strategy() with strategy.scope(): model = mnist_model((28, 28, 3), enable_histograms=enable_histograms) model.compile('sgd', 'mse') dataset = get_image_dataset() tensorboard_callback = callbacks.TensorBoard( self.summary_dir, update_freq=2) model.fit( dataset, steps_per_epoch=10, epochs=1, callbacks=[tensorboard_callback]) event_files = tf.io.gfile.glob( os.path.join(self.summary_dir, 'train', 'event*')) # Since total of 10 steps are ran and summary ops should be invoked # every 2 batches, we should see total of 5 event logs for each summary. expected_event_counts = { 'sequential/layer_for_histogram_summary/custom_histogram_summary_v2': 5 if enable_histograms else 0, 'sequential/layer_for_image_summary/custom_image_summary_v2': 5, } self.validate_recorded_sumary_file(event_files, expected_event_counts) def testV2SummaryWithKerasSubclassedModel(self): # Histogram summaries require the MLIR bridge; see b/178826597#comment107. # TODO(https://github.com/tensorflow/tensorboard/issues/2885): remove this # if histogram summaries are supported fully on non-MLIR bridge or # non-MLIR bridge is no longer run. enable_histograms = test_util.is_mlir_bridge_enabled() strategy = get_tpu_strategy() with strategy.scope(): model = CustomModel(enable_histograms=enable_histograms) model.compile('sgd', 'mse') dataset = distribute_strategy_test.get_dataset(strategy) tensorboard_callback = callbacks.TensorBoard( self.summary_dir, update_freq=2) model.fit( dataset, steps_per_epoch=10, epochs=1, callbacks=[tensorboard_callback]) event_files = tf.io.gfile.glob( os.path.join(self.summary_dir, 'train', 'event*')) # Since total of 10 steps are ran and summary ops should be invoked # every 2 batches, we should see total of 5 event logs for each summary. expected_event_counts = { ('custom_model/layer_for_scalar_summary/' 'custom_scalar_summary_v2'): 5, ('custom_model/layer_for_histogram_summary/' 'custom_histogram_summary_v2'): 5 if enable_histograms else 0, } self.validate_recorded_sumary_file(event_files, expected_event_counts) def testSummaryWithCustomTrainingLoop(self): strategy = get_tpu_strategy() writer = tf.summary.create_file_writer(self.summary_dir) with strategy.scope(): model = distribute_strategy_test.get_model() model.compile('sgd', 'mse') @tf.function def custom_function(dataset): def _custom_step(features, labels): del labels logits = model(features) with tf.summary.record_if(True), writer.as_default(): scalar_summary_v2.scalar( 'logits', tf.reduce_sum(logits), step=model.optimizer.iterations) return logits iterator = iter(dataset) output = strategy.unwrap( strategy.run(_custom_step, args=(next(iterator)))) return output dataset = strategy.experimental_distribute_dataset( distribute_strategy_test.get_dataset(strategy)) custom_function(dataset) writer.close() event_files = tf.io.gfile.glob( os.path.join(self.summary_dir, 'event*')) expected_event_counts = { 'logits': 1, } self.validate_recorded_sumary_file(event_files, expected_event_counts) if __name__ == '__main__': tf.compat.v1.enable_eager_execution() tf.test.main()
10,349
34.813149
115
py
keras
keras-master/keras/tests/saved_model_test.py
# 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 tensorflow.compat.v2 as tf import os from tensorflow.python.framework import test_util from keras.layers import core from keras.optimizer_v2 import adam 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.) 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(MemoryTests, self).setUp() self._model = _ModelWithOptimizerUsingDefun() @test_util.assert_no_garbage_created def test_no_reference_cycles(self): x = tf.constant([[3., 4.]]) y = tf.constant([2.]) 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()
2,004
31.868852
80
py
keras
keras-master/keras/tests/tracking_test.py
# 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. # ============================================================================== import os import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy from keras import combinations from keras import keras_parameterized from keras.engine import sequential from keras.engine import training from keras.layers import core from keras.layers.normalization import batch_normalization_v1 from tensorflow.python.training.tracking import data_structures from tensorflow.python.training.tracking import util class HasList(training.Model): def __init__(self): super(HasList, self).__init__() self.layer_list = tf.__internal__.tracking.wrap([core.Dense(3)]) self.layer_list.append(core.Dense(4)) self.layer_list.extend( [core.Dense(5), core.Dense(6, kernel_regularizer=tf.reduce_sum)]) self.layer_list += [ core.Dense(7, bias_regularizer=tf.reduce_sum), core.Dense(8) ] self.layer_list += ( tf.__internal__.tracking.wrap([core.Dense(9)]) + tf.__internal__.tracking.wrap([core.Dense(10)])) self.layer_list.extend( tf.__internal__.tracking.wrap( list([core.Dense(11)]) + [core.Dense(12)])) self.layers_with_updates = tf.__internal__.tracking.wrap( [batch_normalization_v1.BatchNormalization()]) def call(self, x): aggregation = 0. for l in self.layer_list: x = l(x) aggregation += tf.reduce_sum(x) bn, = self.layers_with_updates return bn(x) / aggregation class ListTests(keras_parameterized.TestCase): @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testTracking(self): with self.test_session(): model = HasList() output = model(tf.ones([32, 2])) self.assertAllEqual([32, 12], output.shape) self.assertEqual(11, len(model.layers)) self.assertEqual(10, len(model.layer_list.layers)) self.assertEqual( len(model.layers), len(model.layer_list.layers + model.layers_with_updates)) for index in range(10): self.assertEqual(3 + index, model.layer_list.layers[index].units) self.assertEqual(2, len(model._checkpoint_dependencies)) self.assertIs(model.layer_list, model._checkpoint_dependencies[0].ref) self.assertIs(model.layers_with_updates, model._checkpoint_dependencies[1].ref) self.assertEqual( 10, len(model._checkpoint_dependencies[0].ref._checkpoint_dependencies)) self.evaluate([v.initializer for v in model.variables]) self.evaluate(model.variables[0].assign([[1., 2., 3.], [4., 5., 6.]])) save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) self.evaluate(model.variables[0].assign(tf.zeros([2, 3]))) model.load_weights(save_path) self.assertAllEqual([[1., 2., 3.], [4., 5., 6.]], self.evaluate(model.variables[0])) v = tf.Variable(1.) model.var_list = [v] self.assertTrue(any(v is t for t in model.variables)) self.assertTrue(any(v is t for t in model.trainable_variables)) self.assertFalse(any(v is t for t in model.non_trainable_variables)) self.assertTrue(any(model.layer_list[0].trainable_weights[0] is t for t in model.trainable_weights)) def testSubModelTracking(self): model = training.Model() model.v = tf.Variable(1.) self.assertIn(model.v, model.trainable_weights) model2 = training.Model() model2.m = [model] self.assertIn(model.v, model2.trainable_weights) def testSubSequentialTracking(self): class _Subclassed(training.Model): def __init__(self, wrapped): super(_Subclassed, self).__init__() self._wrapped = wrapped def call(self, x): return self._wrapped(x) model = sequential.Sequential() layer = core.Dense(1) model.add(layer) model2 = _Subclassed(model) model2(tf.ones([1, 2])) model2.m = [model] self.assertIn(layer.kernel, model2.trainable_weights) def testLayerTrackedThroughSequential(self): class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self def ffnet(layer_sizes, name): ff = sequential.Sequential(name=name) for i, width in enumerate(layer_sizes): ff.add(core.Dense( width, activation=("relu" if i < len(layer_sizes)-1 else None))) return ff class MyModel2(training.Model): def __init__(self, config, name="my_model_2"): super(MyModel2, self).__init__(name=name) self._num_tokens = config.num_tokens # list of sub-models self._ffnet = [ffnet(config.module_layers + (self._num_tokens,), "ff")] def null_input(self): return tf.zeros([1, self._num_tokens], dtype=tf.float32) def call(self, input_, module_index=None): return self._ffnet[0](input_) m2 = MyModel2(AttrDict( num_tokens=5, module_layers=(50, 30))) # Construct m2(m2.null_input()) self.assertLen(m2.trainable_variables, 6) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testUpdatesForwarded(self): model = HasList() model_input = tf.ones([32, 2]) model(model_input) if tf.executing_eagerly(): self.assertEqual(0, len(model.updates)) else: self.assertGreater(len(model.layers_with_updates[0].updates), 0) self.assertEqual(set(model.layers_with_updates[0].updates), set(model.updates)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testLossesForwarded(self): model = HasList() model_input = tf.ones([32, 2]) model(model_input) self.assertEqual(2, len(model.losses)) def testModelContainersCompareEqual(self): class HasEqualContainers(training.Model): def __init__(self): super(HasEqualContainers, self).__init__() self.l1 = [] self.l2 = [] model = HasEqualContainers() first_layer = HasEqualContainers() model.l1.append(first_layer) second_layer = HasEqualContainers() model.l2.append(second_layer) self.assertEqual([first_layer, second_layer], model.layers) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testTensorConversion(self): class ListToTensor(training.Model): def __init__(self): super(ListToTensor, self).__init__() self.l = [1., 2., 3.] self.assertAllEqual( [1., 2., 3.], self.evaluate(tf.constant(ListToTensor().l))) self.assertAllEqual( [1., 2., 3.], self.evaluate(tf.raw_ops.Pack(values=ListToTensor().l))) class ListWrapperTest(tf.test.TestCase): def testLayerCollectionWithExternalMutation(self): l = [] l_wrapper = tf.__internal__.tracking.wrap(l) layer = core.Dense(1) l.append(layer) self.assertEqual([layer], l_wrapper.layers) class HasMapping(training.Model): def __init__(self): super(HasMapping, self).__init__() self.layer_dict = tf.__internal__.tracking.wrap(dict(output=core.Dense(7))) self.layer_dict["norm"] = tf.__internal__.tracking.wrap([]) self.layer_dict["dense"] = tf.__internal__.tracking.wrap([]) self.layer_dict["dense"].extend( [core.Dense(5), core.Dense(6, kernel_regularizer=tf.reduce_sum)]) self.layer_dict["norm"].append( batch_normalization_v1.BatchNormalization()) self.layer_dict["norm"].append( batch_normalization_v1.BatchNormalization()) def call(self, x): aggregation = 0. for norm, dense in zip(self.layer_dict["norm"], self.layer_dict["dense"]): x = norm(dense(x)) aggregation += tf.reduce_sum(x) return self.layer_dict["output"](x) / aggregation class MappingTests(keras_parameterized.TestCase): @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testTracking(self): with self.test_session(): model = HasMapping() output = model(tf.ones([32, 2])) self.assertAllEqual([32, 7], output.shape.as_list()) self.assertEqual(5, len(model.layers)) self.assertEqual(len(model.layers), len(model.layer_dict.layers)) self.assertEqual(1, len(model._checkpoint_dependencies)) self.assertIs(model.layer_dict, model._checkpoint_dependencies[0].ref) self.evaluate([v.initializer for v in model.variables]) test_var = model.layer_dict["output"].kernel self.evaluate(test_var.assign(tf.ones([6, 7]))) save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) self.evaluate(test_var.assign(tf.zeros([6, 7]))) model.load_weights(save_path) self.assertAllEqual(numpy.ones([6, 7]), self.evaluate(test_var)) def testLayerCollectionWithExternalMutation(self): d = {} root = tf.Module() root.wrapper = d self.assertEqual([], root.wrapper.layers) self.assertEqual([], root.wrapper.trainable_weights) layer1 = core.Dense(1) layer2 = core.Dense(1) d["a"] = layer1 d["b"] = layer2 self.assertEqual([layer1, layer2], root.wrapper.layers) # The layers have still not created variables self.assertEqual([], root.wrapper.trainable_weights) def testDictWrapperBadKeys(self): a = tf.Module() a.d = {} a.d[1] = tf.__internal__.tracking.wrap([]) model = training.Model() model.sub = a save_path = os.path.join(self.get_temp_dir(), "ckpt") with self.assertRaisesRegex(ValueError, "non-string key"): model.save_weights(save_path) def testDictWrapperNoDependency(self): a = tf.Module() a.d = data_structures.NoDependency({}) a.d[1] = [3] self.assertEqual([a], util.list_objects(a)) model = training.Model() model.sub = a save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) model.load_weights(save_path) def testNonStringKeyNotTrackableValue(self): a = tf.Module() a.d = {} a.d["a"] = [3] a.d[1] = data_structures.NoDependency([3]) self.assertEqual([a, a.d, a.d["a"]], util.list_objects(a)) model = training.Model() model.sub = a save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) model.load_weights(save_path) def testNonAppendNotTrackable(self): # Non-append mutations (deleting or overwriting values) are OK when the # values aren't tracked. a = tf.Module() a.d = {} a.d["a"] = [3] a.d[1] = 3 a.d[1] = 2 self.assertEqual(2, a.d[1]) del a.d[1] a.d[2] = data_structures.NoDependency(tf.Module()) second = tf.Module() a.d[2] = data_structures.NoDependency(second) self.assertIs(second, a.d[2]) self.assertEqual([a, a.d, a.d["a"]], util.list_objects(a)) model = training.Model() model.sub = a save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) model.load_weights(save_path) def testPopNoSave(self): model = training.Model() model.d = {} model.d["a"] = [] model.d.pop("a") save_path = os.path.join(self.get_temp_dir(), "ckpt") with self.assertRaisesRegex(ValueError, "Unable to save"): model.save_weights(save_path) def testExternalModificationNoSave(self): model = training.Model() external_reference = {} model.d = external_reference external_reference["a"] = [] save_path = os.path.join(self.get_temp_dir(), "ckpt") with self.assertRaisesRegex(ValueError, "modified outside the wrapper"): model.save_weights(save_path) def testOverwriteCanStillSave(self): model = training.Model() model.d = {} model.d["a"] = {} model.d["a"] = {} save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) def testIter(self): model = training.Model() model.d = {1: 3} model.d[1] = 3 self.assertEqual([1], list(model.d)) new_dict = {} # This update() is super tricky. If the dict wrapper subclasses dict, # CPython will access its storage directly instead of calling any # methods/properties on the object. So the options are either not to # subclass dict (in which case update will call normal iter methods, but the # object won't pass isinstance checks) or to subclass dict and keep that # storage updated (no shadowing all its methods like ListWrapper). new_dict.update(model.d) self.assertEqual({1: 3}, new_dict) class HasTuple(training.Model): def __init__(self): super(HasTuple, self).__init__() self.layer_list = ( core.Dense(3), core.Dense(4), core.Dense(5, kernel_regularizer=tf.reduce_sum)) self.layers_with_updates = (batch_normalization_v1.BatchNormalization(),) def call(self, x): aggregation = 0. for l in self.layer_list: x = l(x) aggregation += tf.reduce_sum(x) bn, = self.layers_with_updates return bn(x) / aggregation class TupleTests(keras_parameterized.TestCase): @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testTracking(self): with self.test_session(): model = HasTuple() output = model(tf.ones([32, 2])) self.assertAllEqual([32, 5], output.shape.as_list()) self.assertLen(model.layers, 4) self.assertLen(model.layer_list.layers, 3) self.assertEqual( len(model.layers), len(tuple(model.layer_list.layers) + model.layers_with_updates)) self.assertEqual(3, model.layer_list.layers[0].units) self.assertEqual(4, model.layer_list.layers[1].units) self.assertEqual(5, model.layer_list.layers[2].units) self.assertLen(model._checkpoint_dependencies, 2) self.assertIs(model.layer_list, model._checkpoint_dependencies[0].ref) self.assertIs(model.layers_with_updates, model._checkpoint_dependencies[1].ref) self.assertLen( model._checkpoint_dependencies[0].ref._checkpoint_dependencies, 3) self.evaluate([v.initializer for v in model.variables]) self.evaluate(model.variables[0].assign([[1., 2., 3.], [4., 5., 6.]])) save_path = os.path.join(self.get_temp_dir(), "ckpt") model.save_weights(save_path) self.evaluate(model.variables[0].assign(tf.zeros([2, 3]))) model.load_weights(save_path) self.assertAllEqual([[1., 2., 3.], [4., 5., 6.]], self.evaluate(model.variables[0])) v = tf.Variable(1.) model.var_list = (v,) self.assertIn(id(v), [id(obj) for obj in model.variables]) self.assertIn(id(v), [id(obj) for obj in model.trainable_variables]) self.assertNotIn(id(v), [id(obj) for obj in model.non_trainable_variables]) self.assertIn(id(model.layer_list[0].trainable_weights[0]), [id(obj) for obj in model.trainable_weights]) @parameterized.named_parameters( ("Module", tf.Module), ("Model", training.Model), ) def testSubModelTracking(self, module_subclass): model = module_subclass() model.v = tf.Variable(1.) self.assertIn(model.v, model.trainable_variables) model2 = module_subclass() model2.m = (model,) self.assertIn(model.v, model2.trainable_variables) def testSubSequentialTracking(self): class _Subclassed(training.Model): def __init__(self, wrapped): super(_Subclassed, self).__init__() self._wrapped = wrapped def call(self, x): return self._wrapped(x) model = sequential.Sequential() layer = core.Dense(1) model.add(layer) model2 = _Subclassed(model) model2(tf.ones([1, 2])) model2.m = (model,) self.assertIn(layer.kernel, model2.trainable_weights) def testUpdatesForwarded(self): with tf.Graph().as_default(): model = HasTuple() model_input = tf.ones([32, 2]) model(model_input) self.assertNotEmpty(model.layers_with_updates[0].updates) self.assertEqual(set(model.layers_with_updates[0].updates), set(model.updates)) model = HasTuple() model_input = tf.ones([32, 2]) model(model_input) self.assertEmpty(model.updates) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testLossesForwarded(self): model = HasTuple() model_input = tf.ones([32, 2]) model(model_input) self.assertLen(model.losses, 1) def testModelContainersCompareEqual(self): class HasEqualContainers(training.Model): def __init__(self): super(HasEqualContainers, self).__init__() self.l1 = () self.l2 = () model = HasEqualContainers() first_layer = HasEqualContainers() model.l1 = (first_layer,) second_layer = HasEqualContainers() model.l2 = (second_layer,) self.assertEqual((first_layer,), model.l1) d = {model.l1: 1, model.l2: 2} self.assertEqual(1, d[model.l1]) self.assertEqual(1, d[(first_layer,)]) self.assertEqual(2, d[model.l2]) self.assertEqual(2, d[(second_layer,)]) self.assertEqual([first_layer, second_layer], model.layers) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testTensorConversion(self): class TupleToTensor(training.Model): def __init__(self): super(TupleToTensor, self).__init__() self.l = (1., 2., 3.) self.assertAllEqual( (1., 2., 3.), self.evaluate(tf.constant(TupleToTensor().l))) self.assertAllEqual( (1., 2., 3.), self.evaluate(tf.raw_ops.Pack(values=TupleToTensor().l))) class InterfaceTests(keras_parameterized.TestCase): def testNoDependency(self): root = tf.Module() hasdep = tf.Module() root.hasdep = hasdep nodep = tf.Module() root.nodep = data_structures.NoDependency(nodep) self.assertEqual(1, len(root._checkpoint_dependencies)) self.assertIs(root._checkpoint_dependencies[0].ref, root.hasdep) self.assertIs(root.hasdep, hasdep) self.assertIs(root.nodep, nodep) class NoDependencyModel(training.Model): @tf.__internal__.tracking.no_automatic_dependency_tracking def __init__(self): super(NoDependencyModel, self).__init__() self.a = [] self.b = tf.Module() nodeps = NoDependencyModel() self.assertEqual([nodeps], util.list_objects(nodeps)) @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testDictionariesBasic(self): a = training.Model() b = training.Model() a.attribute = {"b": b} c = training.Model() a.attribute["c"] = [] a.attribute["c"].append(c) a_deps = util.list_objects(a) self.assertIn(b, a_deps) self.assertIn(c, a_deps) self.assertIs(b, a.attribute["b"]) self.assertEqual( len(["b", "c"]), len([dep.name for dep in a.attribute._checkpoint_dependencies])) self.assertEqual([b, c], a.layers) self.assertEqual([b, c], a.attribute.layers) self.assertEqual([c], a.attribute["c"].layers) checkpoint = tf.train.Checkpoint(a=a) save_path = checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt")) with self.cached_session(): checkpoint.restore(save_path).assert_consumed().initialize_or_restore() @combinations.generate(combinations.combine(mode=["graph", "eager"])) def testNoDepList(self): a = training.Model() a.l1 = data_structures.NoDependency([]) a.l1.insert(1, 0) self.assertIsInstance(a.l1, list) checkpoint = tf.train.Checkpoint(a=a) checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt")) a.l2 = [] a.l2.insert(1, tf.Module()) with self.assertRaisesRegex(ValueError, "A list element was replaced"): checkpoint.save(os.path.join(self.get_temp_dir(), "ckpt")) if __name__ == "__main__": tf.compat.v1.enable_eager_execution() tf.test.main()
20,535
33.514286
80
py
keras
keras-master/keras/tests/tracking_util_xla_test.py
# Copyright 2017 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. # ============================================================================== from tensorflow.compiler.tests import xla_test import tensorflow.compat.v2 as tf from keras.engine import training from keras.layers import core from keras.optimizer_v2 import adam from tensorflow.python.training.tracking import util as trackable_utils class NonLayerTrackable(tf.Module): def __init__(self): super(NonLayerTrackable, self).__init__() self.a_variable = trackable_utils.add_variable( self, name="a_variable", shape=[]) class Subclassed(training.Model): """A concrete Model for testing.""" def __init__(self): super(Subclassed, self).__init__() self._named_dense = core.Dense(1, use_bias=True) self._second = core.Dense(1, use_bias=False) # We can still track Trackables which aren't Layers. self._non_layer = NonLayerTrackable() def call(self, values): ret = self._second(self._named_dense(values)) return ret class CheckpointingTests(xla_test.XLATestCase): def testDeferredRestorationUsageEager(self): """An idiomatic eager execution example.""" num_training_steps = 10 checkpoint_directory = self.get_temp_dir() for training_continuation in range(3): with self.test_scope(): model = Subclassed() optimizer = adam.Adam(0.001) root = tf.train.Checkpoint( optimizer=optimizer, model=model) manager = tf.train.CheckpointManager( root, checkpoint_directory, max_to_keep=2) root.restore(manager.latest_checkpoint) for _ in range(num_training_steps): input_value = tf.constant([[3.]]) with tf.GradientTape() as tape: loss = model(input_value) variables = model.trainable_variables gradients = tape.gradient(loss, variables) optimizer.apply_gradients(zip(gradients, variables)) manager.save() self.assertEqual((training_continuation + 1) * num_training_steps, root.optimizer.iterations.numpy()) if __name__ == "__main__": tf.compat.v1.enable_eager_execution() tf.test.main()
2,742
34.166667
80
py
keras
keras-master/keras/tests/graph_util_test.py
# 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 tensorflow.python.client.graph_util.""" import tensorflow.compat.v2 as tf import numpy as np from tensorflow.core.protobuf import meta_graph_pb2 import keras from tensorflow.python.grappler import tf_optimizer from tensorflow.python.training.saver import export_meta_graph class ConvertVariablesToConstantsTest(tf.test.TestCase): def _get_tensors(self, sess, tensor_list): """Returns a list of Tensor objects from the Session.""" return [ sess.graph.get_tensor_by_name(tensor.name) for tensor in tensor_list ] def _get_tensor_names(self, tensors): """Returns a list of string names for the tensors specified.""" return [tensor.name.split(":")[0] for tensor in tensors] def _evaluate_graph_def(self, graph_def, inputs, outputs, input_data): """Evaluates the GraphDef using Sessions.""" with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def, name="") sess = tf.compat.v1.Session(graph=graph) input_tensors = self._get_tensors(sess, inputs) output_tensors = self._get_tensors(sess, outputs) return sess.run( output_tensors, feed_dict=dict(zip(input_tensors, input_data))) def _ensure_no_variables_in_graph(self, graph_def): """Ensures there are no variables in the graph.""" for node in graph_def.node: self.assertNotIn( node.op, ["Variable", "VariableV2", "VarHandleOp", "ReadVariableOp"]) def _test_converted_keras_model(self, model, constant_graph_def, input_data): """Compares the converted Keras model.""" expected_value = model.predict(input_data) actual_value = self._evaluate_graph_def(constant_graph_def, model.inputs, model.outputs, [input_data]) np.testing.assert_almost_equal(np.array([expected_value]), actual_value, 5) def _inline_functions(self, graph_def, arrays): meta_graph = export_meta_graph(graph_def=graph_def) fetch_collection = meta_graph_pb2.CollectionDef() for name in arrays: fetch_collection.node_list.value.append(name) meta_graph.collection_def["train_op"].CopyFrom(fetch_collection) # Initialize RewriterConfig with everything disabled except function # inlining. config = tf.compat.v1.ConfigProto() rewrite_options = config.graph_options.rewrite_options rewrite_options.optimizers.append("function") return tf_optimizer.OptimizeGraph(config, meta_graph) def testWithEmbeddings(self): """Freezes a graph with embeddings.""" state_input = keras.layers.Input( shape=(1,), name="state_input", dtype="int32") output = keras.layers.Embedding( output_dim=16, input_dim=100, input_length=1, name="state")( state_input) model = keras.models.Model(inputs=[state_input], outputs=[output]) model.compile( loss={"state": "sparse_categorical_crossentropy"}, optimizer="adam") # Freeze the graph. sess = keras.backend.get_session() variable_graph_def = sess.graph_def output_tensor = self._get_tensor_names(model.outputs) constant_graph_def = tf.compat.v1.graph_util.convert_variables_to_constants( sess, variable_graph_def, output_tensor) # Validate converted graph. input_data = np.array(np.random.random_sample([1, 1]), dtype=np.int32) self._ensure_no_variables_in_graph(constant_graph_def) self._test_converted_keras_model(model, constant_graph_def, input_data) def testKerasBatchNorm(self): """Freezes a graph with Keras batch norm.""" inputs = keras.layers.Input(shape=(128, 128, 1)) batch_norm = keras.layers.BatchNormalization()(inputs) model = keras.models.Model(inputs, batch_norm, name="test") model.compile( optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) tensor_names = [tensor.name for tensor in model.inputs + model.outputs] # Freeze the graph. sess = keras.backend.get_session() variable_graph_def = sess.graph_def variable_graph_def = self._inline_functions(variable_graph_def, tensor_names) output_tensor = self._get_tensor_names(model.outputs) constant_graph_def = tf.compat.v1.graph_util.convert_variables_to_constants( sess, variable_graph_def, output_tensor) # Validate converted graph. input_data = np.array( np.random.random_sample([1, 128, 128, 1]), dtype=np.int32) self._ensure_no_variables_in_graph(constant_graph_def) self._test_converted_keras_model(model, constant_graph_def, input_data) def testLSTM(self): """Freezes a Keras LSTM.""" model = keras.models.Sequential( [keras.layers.LSTM(units=10, input_shape=(10, 10))]) tensor_names = [tensor.name for tensor in model.inputs + model.outputs] # Freeze the model. sess = keras.backend.get_session() variable_graph_def = sess.graph_def variable_graph_def = self._inline_functions(variable_graph_def, tensor_names) output_tensor = self._get_tensor_names(model.outputs) constant_graph_def = tf.compat.v1.graph_util.convert_variables_to_constants( sess, variable_graph_def, output_tensor) # Validate converted graph. input_data = np.array(np.random.random_sample([10, 10, 10]), dtype=np.int32) self._ensure_no_variables_in_graph(constant_graph_def) self._test_converted_keras_model(model, constant_graph_def, input_data) if __name__ == "__main__": tf.compat.v1.disable_eager_execution() tf.test.main()
6,229
41.380952
80
py
keras
keras-master/keras/layers/pooling.py
# 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. # ============================================================================== """Pooling layers.""" import tensorflow.compat.v2 as tf import functools from keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils from tensorflow.python.util.tf_export import keras_export class Pooling1D(Layer): """Pooling layer for arbitrary pooling functions, for 1D inputs. This class only exists for code reuse. It will never be an exposed API. Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of a single integer, representing the size of the pooling window. strides: An integer or tuple/list of a single integer, specifying the strides of the pooling operation. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. 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)`. name: A string, the name of the layer. """ def __init__(self, pool_function, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs): super(Pooling1D, self).__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format() if strides is None: strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 1, 'pool_size') self.strides = conv_utils.normalize_tuple(strides, 1, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=3) def call(self, inputs): pad_axis = 2 if self.data_format == 'channels_last' else 3 inputs = tf.expand_dims(inputs, pad_axis) outputs = self.pool_function( inputs, self.pool_size + (1,), strides=self.strides + (1,), padding=self.padding, data_format=self.data_format) return tf.squeeze(outputs, pad_axis) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': steps = input_shape[2] features = input_shape[1] else: steps = input_shape[1] features = input_shape[2] length = conv_utils.conv_output_length(steps, self.pool_size[0], self.padding, self.strides[0]) if self.data_format == 'channels_first': return tf.TensorShape([input_shape[0], features, length]) else: return tf.TensorShape([input_shape[0], length, features]) def get_config(self): config = { 'strides': self.strides, 'pool_size': self.pool_size, 'padding': self.padding, 'data_format': self.data_format, } base_config = super(Pooling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.MaxPool1D', 'keras.layers.MaxPooling1D') class MaxPooling1D(Pooling1D): """Max pooling operation for 1D temporal data. Downsamples the input representation by taking the maximum value over a spatial window of size `pool_size`. The window is shifted by `strides`. The resulting output, when using the `"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]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=1, padding='valid') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy= array([[[2.], [3.], [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]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=2, padding='valid') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy= array([[[2.], [4.]]], 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]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=1, padding='same') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[2.], [3.], [4.], [5.], [5.]]], dtype=float32)> Args: pool_size: Integer, size of the max pooling window. strides: Integer, or None. Specifies how much the pooling window moves for each pooling step. 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(MaxPooling1D, self).__init__( functools.partial(backend.pool2d, pool_mode='max'), pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) @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(AveragePooling1D, self).__init__( functools.partial(backend.pool2d, pool_mode='avg'), pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) class Pooling2D(Layer): """Pooling layer for arbitrary pooling functions, for 2D inputs (e.g. images). This class only exists for code reuse. It will never be an exposed API. Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) specifying the size of the pooling 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 pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. 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)`. name: A string, the name of the layer. """ def __init__(self, pool_function, pool_size, strides, padding='valid', data_format=None, name=None, **kwargs): super(Pooling2D, self).__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format() if strides is None: strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size') self.strides = conv_utils.normalize_tuple(strides, 2, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=4) def call(self, inputs): if self.data_format == 'channels_last': pool_shape = (1,) + self.pool_size + (1,) strides = (1,) + self.strides + (1,) else: pool_shape = (1, 1) + self.pool_size strides = (1, 1) + self.strides outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper(), data_format=conv_utils.convert_data_format(self.data_format, 4)) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] else: rows = input_shape[1] cols = input_shape[2] rows = conv_utils.conv_output_length(rows, self.pool_size[0], self.padding, self.strides[0]) cols = conv_utils.conv_output_length(cols, self.pool_size[1], self.padding, self.strides[1]) if self.data_format == 'channels_first': return tf.TensorShape( [input_shape[0], input_shape[1], rows, cols]) else: return tf.TensorShape( [input_shape[0], rows, cols, input_shape[3]]) def get_config(self): config = { 'pool_size': self.pool_size, 'padding': self.padding, 'strides': self.strides, 'data_format': self.data_format } base_config = super(Pooling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.MaxPool2D', 'keras.layers.MaxPooling2D') class MaxPooling2D(Pooling2D): """Max pooling operation for 2D spatial data. Downsamples the input along its spatial dimensions (height and width) by taking the maximum value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each dimension. The resulting output, when using the `"valid"` padding option, has a spatial shape (number of rows or columns) of: `output_shape = math.floor((input_shape - pool_size) / strides) + 1` (when `input_shape >= pool_size`) The resulting output shape when using the `"same"` padding option is: `output_shape = math.floor((input_shape - 1) / strides) + 1` For example, for `strides=(1, 1)` and `padding="valid"`: >>> x = tf.constant([[1., 2., 3.], ... [4., 5., 6.], ... [7., 8., 9.]]) >>> x = tf.reshape(x, [1, 3, 3, 1]) >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), ... strides=(1, 1), padding='valid') >>> max_pool_2d(x) <tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy= array([[[[5.], [6.]], [[8.], [9.]]]], dtype=float32)> For example, for `strides=(2, 2)` and `padding="valid"`: >>> x = tf.constant([[1., 2., 3., 4.], ... [5., 6., 7., 8.], ... [9., 10., 11., 12.]]) >>> x = tf.reshape(x, [1, 3, 4, 1]) >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), ... strides=(2, 2), padding='valid') >>> max_pool_2d(x) <tf.Tensor: shape=(1, 1, 2, 1), dtype=float32, numpy= array([[[[6.], [8.]]]], dtype=float32)> Usage Example: >>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]], ... [[2.], [2.], [3.], [2.]], ... [[4.], [1.], [1.], [1.]], ... [[2.], [2.], [1.], [4.]]]]) >>> output = tf.constant([[[[1], [0]], ... [[0], [1]]]]) >>> model = tf.keras.models.Sequential() >>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), ... input_shape=(4, 4, 1))) >>> model.compile('adam', 'mean_squared_error') >>> model.predict(input_image, steps=1) array([[[[2.], [4.]], [[4.], [4.]]]], dtype=float32) For example, for stride=(1, 1) and padding="same": >>> x = tf.constant([[1., 2., 3.], ... [4., 5., 6.], ... [7., 8., 9.]]) >>> x = tf.reshape(x, [1, 3, 3, 1]) >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), ... strides=(1, 1), padding='same') >>> max_pool_2d(x) <tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy= array([[[[5.], [6.], [6.]], [[8.], [9.], [9.]], [[8.], [9.], [9.]]]], dtype=float32)> Args: pool_size: integer or tuple of 2 integers, window size over which to take the maximum. `(2, 2)` will take the max value over a 2x2 pooling window. If only one integer is specified, the same window length will be used for both dimensions. strides: Integer, tuple of 2 integers, or None. Strides values. Specifies how far the pooling window moves for each pooling step. 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, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. 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". Input shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, rows, cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, rows, cols)`. Output shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`. Returns: A tensor of rank 4 representing the maximum pooled values. See above for output shape. """ def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format=None, **kwargs): super(MaxPooling2D, self).__init__( tf.compat.v1.nn.max_pool, pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) @keras_export('keras.layers.AveragePooling2D', 'keras.layers.AvgPool2D') class AveragePooling2D(Pooling2D): """Average pooling operation for spatial data. Downsamples the input along its spatial dimensions (height and width) by taking the average value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each dimension. The resulting output when using `"valid"` padding option has a shape (number of rows or columns) of: `output_shape = math.floor((input_shape - pool_size) / strides) + 1` (when `input_shape >= pool_size`) The resulting output shape when using the `"same"` padding option is: `output_shape = math.floor((input_shape - 1) / strides) + 1` For example, for `strides=(1, 1)` and `padding="valid"`: >>> x = tf.constant([[1., 2., 3.], ... [4., 5., 6.], ... [7., 8., 9.]]) >>> x = tf.reshape(x, [1, 3, 3, 1]) >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), ... strides=(1, 1), padding='valid') >>> avg_pool_2d(x) <tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy= array([[[[3.], [4.]], [[6.], [7.]]]], dtype=float32)> For example, for `stride=(2, 2)` and `padding="valid"`: >>> x = tf.constant([[1., 2., 3., 4.], ... [5., 6., 7., 8.], ... [9., 10., 11., 12.]]) >>> x = tf.reshape(x, [1, 3, 4, 1]) >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), ... strides=(2, 2), padding='valid') >>> avg_pool_2d(x) <tf.Tensor: shape=(1, 1, 2, 1), dtype=float32, numpy= array([[[[3.5], [5.5]]]], dtype=float32)> For example, for `strides=(1, 1)` and `padding="same"`: >>> x = tf.constant([[1., 2., 3.], ... [4., 5., 6.], ... [7., 8., 9.]]) >>> x = tf.reshape(x, [1, 3, 3, 1]) >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), ... strides=(1, 1), padding='same') >>> avg_pool_2d(x) <tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy= array([[[[3.], [4.], [4.5]], [[6.], [7.], [7.5]], [[7.5], [8.5], [9.]]]], dtype=float32)> Args: pool_size: integer or tuple of 2 integers, factors by which to downscale (vertical, horizontal). `(2, 2)` will halve the input in both spatial dimension. If only one integer is specified, the same window length will be used for both dimensions. strides: Integer, tuple of 2 integers, or None. Strides values. 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, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. 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". Input shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, rows, cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, rows, cols)`. Output shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`. """ def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format=None, **kwargs): super(AveragePooling2D, self).__init__( tf.nn.avg_pool, pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) class Pooling3D(Layer): """Pooling layer for arbitrary pooling functions, for 3D inputs. This class only exists for code reuse. It will never be an exposed API. Args: pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. 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, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. name: A string, the name of the layer. """ def __init__(self, pool_function, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs): super(Pooling3D, self).__init__(name=name, **kwargs) if data_format is None: data_format = backend.image_data_format() if strides is None: strides = pool_size self.pool_function = pool_function self.pool_size = conv_utils.normalize_tuple(pool_size, 3, 'pool_size') self.strides = conv_utils.normalize_tuple(strides, 3, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) def call(self, inputs): pool_shape = (1,) + self.pool_size + (1,) strides = (1,) + self.strides + (1,) if self.data_format == 'channels_first': # TF does not support `channels_first` with 3D pooling operations, # so we must handle this case manually. # TODO(fchollet): remove this when TF pooling is feature-complete. inputs = tf.transpose(inputs, (0, 2, 3, 4, 1)) outputs = self.pool_function( inputs, ksize=pool_shape, strides=strides, padding=self.padding.upper()) if self.data_format == 'channels_first': outputs = tf.transpose(outputs, (0, 4, 1, 2, 3)) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] else: len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] len_dim1 = conv_utils.conv_output_length(len_dim1, self.pool_size[0], self.padding, self.strides[0]) len_dim2 = conv_utils.conv_output_length(len_dim2, self.pool_size[1], self.padding, self.strides[1]) len_dim3 = conv_utils.conv_output_length(len_dim3, self.pool_size[2], self.padding, self.strides[2]) if self.data_format == 'channels_first': return tf.TensorShape( [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3]) else: return tf.TensorShape( [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]]) def get_config(self): config = { 'pool_size': self.pool_size, 'padding': self.padding, 'strides': self.strides, 'data_format': self.data_format } base_config = super(Pooling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.MaxPool3D', 'keras.layers.MaxPooling3D') class MaxPooling3D(Pooling3D): """Max pooling operation for 3D data (spatial or spatio-temporal). Downsamples the input along its spatial dimensions (depth, height, and width) by taking the maximum value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each dimension. Args: pool_size: Tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). `(2, 2, 2)` will halve the size of the 3D input in each dimension. strides: tuple of 3 integers, or None. Strides values. 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, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. 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". Input shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)` Example: ```python depth = 30 height = 30 width = 30 input_channels = 3 inputs = tf.keras.Input(shape=(depth, height, width, input_channels)) layer = tf.keras.layers.MaxPooling3D(pool_size=3) outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3) ``` """ def __init__(self, pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs): super(MaxPooling3D, self).__init__( tf.nn.max_pool3d, pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) @keras_export('keras.layers.AveragePooling3D', 'keras.layers.AvgPool3D') class AveragePooling3D(Pooling3D): """Average pooling operation for 3D data (spatial or spatio-temporal). Downsamples the input along its spatial dimensions (depth, height, and width) by taking the average value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each dimension. Args: pool_size: tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). `(2, 2, 2)` will halve the size of the 3D input in each dimension. strides: tuple of 3 integers, or None. Strides values. 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, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. 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". Input shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)` Example: ```python depth = 30 height = 30 width = 30 input_channels = 3 inputs = tf.keras.Input(shape=(depth, height, width, input_channels)) layer = tf.keras.layers.AveragePooling3D(pool_size=3) outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3) ``` """ def __init__(self, pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None, **kwargs): super(AveragePooling3D, self).__init__( tf.nn.avg_pool3d, pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs) class GlobalPooling1D(Layer): """Abstract class for different global pooling 1D layers.""" def __init__(self, data_format='channels_last', keepdims=False, **kwargs): super(GlobalPooling1D, self).__init__(**kwargs) self.input_spec = InputSpec(ndim=3) self.data_format = conv_utils.normalize_data_format(data_format) self.keepdims = keepdims def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if self.keepdims: return tf.TensorShape([input_shape[0], input_shape[1], 1]) else: return tf.TensorShape([input_shape[0], input_shape[1]]) else: if self.keepdims: return tf.TensorShape([input_shape[0], 1, input_shape[2]]) else: return tf.TensorShape([input_shape[0], input_shape[2]]) def call(self, inputs): raise NotImplementedError def get_config(self): config = {'data_format': self.data_format, 'keepdims': self.keepdims} base_config = super(GlobalPooling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.GlobalAveragePooling1D', 'keras.layers.GlobalAvgPool1D') class GlobalAveragePooling1D(GlobalPooling1D): """Global average pooling operation for temporal data. Examples: >>> input_shape = (2, 3, 4) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalAveragePooling1D()(x) >>> print(y.shape) (2, 4) Args: 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)`. keepdims: A boolean, whether to keep the temporal dimension or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the temporal dimension are retained with length 1. The behavior is the same as for `tf.reduce_mean` or `np.mean`. Call arguments: inputs: A 3D tensor. mask: Binary tensor of shape `(batch_size, steps)` indicating whether a given step should be masked (excluded from the average). 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 `keepdims`=False: 2D tensor with shape `(batch_size, features)`. - If `keepdims`=True: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, 1, features)` - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, 1)` """ def __init__(self, data_format='channels_last', **kwargs): super(GlobalAveragePooling1D, self).__init__(data_format=data_format, **kwargs) self.supports_masking = True def call(self, inputs, mask=None): steps_axis = 1 if self.data_format == 'channels_last' else 2 if mask is not None: mask = tf.cast(mask, inputs[0].dtype) mask = tf.expand_dims( mask, 2 if self.data_format == 'channels_last' else 1) inputs *= mask return backend.sum( inputs, axis=steps_axis, keepdims=self.keepdims) / tf.reduce_sum( mask, axis=steps_axis, keepdims=self.keepdims) else: return backend.mean(inputs, axis=steps_axis, keepdims=self.keepdims) def compute_mask(self, inputs, mask=None): return None @keras_export('keras.layers.GlobalMaxPool1D', 'keras.layers.GlobalMaxPooling1D') class GlobalMaxPooling1D(GlobalPooling1D): """Global max pooling operation for 1D temporal data. Downsamples the input representation by taking the maximum value over the time dimension. For example: >>> x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) >>> x = tf.reshape(x, [3, 3, 1]) >>> x <tf.Tensor: shape=(3, 3, 1), dtype=float32, numpy= array([[[1.], [2.], [3.]], [[4.], [5.], [6.]], [[7.], [8.], [9.]]], dtype=float32)> >>> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D() >>> max_pool_1d(x) <tf.Tensor: shape=(3, 1), dtype=float32, numpy= array([[3.], [6.], [9.], dtype=float32)> Args: 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)`. keepdims: A boolean, whether to keep the temporal dimension or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the temporal dimension are retained with length 1. The behavior is the same as for `tf.reduce_max` or `np.max`. 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 `keepdims`=False: 2D tensor with shape `(batch_size, features)`. - If `keepdims`=True: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, 1, features)` - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, 1)` """ def call(self, inputs): steps_axis = 1 if self.data_format == 'channels_last' else 2 return backend.max(inputs, axis=steps_axis, keepdims=self.keepdims) class GlobalPooling2D(Layer): """Abstract class for different global pooling 2D layers. """ def __init__(self, data_format=None, keepdims=False, **kwargs): super(GlobalPooling2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=4) self.keepdims = keepdims def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_last': if self.keepdims: return tf.TensorShape([input_shape[0], 1, 1, input_shape[3]]) else: return tf.TensorShape([input_shape[0], input_shape[3]]) else: if self.keepdims: return tf.TensorShape([input_shape[0], input_shape[1], 1, 1]) else: return tf.TensorShape([input_shape[0], input_shape[1]]) def call(self, inputs): raise NotImplementedError def get_config(self): config = {'data_format': self.data_format, 'keepdims': self.keepdims} base_config = super(GlobalPooling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.GlobalAveragePooling2D', 'keras.layers.GlobalAvgPool2D') class GlobalAveragePooling2D(GlobalPooling2D): """Global average pooling operation for spatial data. Examples: >>> input_shape = (2, 4, 5, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalAveragePooling2D()(x) >>> print(y.shape) (2, 3) Args: 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)`. 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". keepdims: A boolean, whether to keep the spatial dimensions or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimensions are retained with length 1. The behavior is the same as for `tf.reduce_mean` or `np.mean`. Input shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, rows, cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, rows, cols)`. Output shape: - If `keepdims`=False: 2D tensor with shape `(batch_size, channels)`. - If `keepdims`=True: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, 1, 1, channels)` - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, 1, 1)` """ def call(self, inputs): if self.data_format == 'channels_last': return backend.mean(inputs, axis=[1, 2], keepdims=self.keepdims) else: return backend.mean(inputs, axis=[2, 3], keepdims=self.keepdims) @keras_export('keras.layers.GlobalMaxPool2D', 'keras.layers.GlobalMaxPooling2D') class GlobalMaxPooling2D(GlobalPooling2D): """Global max pooling operation for spatial data. Examples: >>> input_shape = (2, 4, 5, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalMaxPool2D()(x) >>> print(y.shape) (2, 3) Args: 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)`. 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". keepdims: A boolean, whether to keep the spatial dimensions or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimensions are retained with length 1. The behavior is the same as for `tf.reduce_max` or `np.max`. Input shape: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, rows, cols, channels)`. - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, rows, cols)`. Output shape: - If `keepdims`=False: 2D tensor with shape `(batch_size, channels)`. - If `keepdims`=True: - If `data_format='channels_last'`: 4D tensor with shape `(batch_size, 1, 1, channels)` - If `data_format='channels_first'`: 4D tensor with shape `(batch_size, channels, 1, 1)` """ def call(self, inputs): if self.data_format == 'channels_last': return backend.max(inputs, axis=[1, 2], keepdims=self.keepdims) else: return backend.max(inputs, axis=[2, 3], keepdims=self.keepdims) class GlobalPooling3D(Layer): """Abstract class for different global pooling 3D layers.""" def __init__(self, data_format=None, keepdims=False, **kwargs): super(GlobalPooling3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=5) self.keepdims = keepdims def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_last': if self.keepdims: return tf.TensorShape( [input_shape[0], 1, 1, 1, input_shape[4]]) else: return tf.TensorShape([input_shape[0], input_shape[4]]) else: if self.keepdims: return tf.TensorShape( [input_shape[0], input_shape[1], 1, 1, 1]) else: return tf.TensorShape([input_shape[0], input_shape[1]]) def call(self, inputs): raise NotImplementedError def get_config(self): config = {'data_format': self.data_format, 'keepdims': self.keepdims} base_config = super(GlobalPooling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.GlobalAveragePooling3D', 'keras.layers.GlobalAvgPool3D') class GlobalAveragePooling3D(GlobalPooling3D): """Global Average pooling operation for 3D data. Args: 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, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. 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". keepdims: A boolean, whether to keep the spatial dimensions or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimensions are retained with length 1. The behavior is the same as for `tf.reduce_mean` or `np.mean`. Input shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `keepdims`=False: 2D tensor with shape `(batch_size, channels)`. - If `keepdims`=True: - If `data_format='channels_last'`: 5D tensor with shape `(batch_size, 1, 1, 1, channels)` - If `data_format='channels_first'`: 5D tensor with shape `(batch_size, channels, 1, 1, 1)` """ def call(self, inputs): if self.data_format == 'channels_last': return backend.mean(inputs, axis=[1, 2, 3], keepdims=self.keepdims) else: return backend.mean(inputs, axis=[2, 3, 4], keepdims=self.keepdims) @keras_export('keras.layers.GlobalMaxPool3D', 'keras.layers.GlobalMaxPooling3D') class GlobalMaxPooling3D(GlobalPooling3D): """Global Max pooling operation for 3D data. Args: 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, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. 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". keepdims: A boolean, whether to keep the spatial dimensions or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimensions are retained with length 1. The behavior is the same as for `tf.reduce_max` or `np.max`. Input shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `keepdims`=False: 2D tensor with shape `(batch_size, channels)`. - If `keepdims`=True: - If `data_format='channels_last'`: 5D tensor with shape `(batch_size, 1, 1, 1, channels)` - If `data_format='channels_first'`: 5D tensor with shape `(batch_size, channels, 1, 1, 1)` """ def call(self, inputs): if self.data_format == 'channels_last': return backend.max(inputs, axis=[1, 2, 3], keepdims=self.keepdims) else: return backend.max(inputs, axis=[2, 3, 4], keepdims=self.keepdims) # Aliases AvgPool1D = AveragePooling1D MaxPool1D = MaxPooling1D AvgPool2D = AveragePooling2D MaxPool2D = MaxPooling2D AvgPool3D = AveragePooling3D MaxPool3D = MaxPooling3D GlobalMaxPool1D = GlobalMaxPooling1D GlobalMaxPool2D = GlobalMaxPooling2D GlobalMaxPool3D = GlobalMaxPooling3D GlobalAvgPool1D = GlobalAveragePooling1D GlobalAvgPool2D = GlobalAveragePooling2D GlobalAvgPool3D = GlobalAveragePooling3D
49,866
36.522197
80
py
keras
keras-master/keras/layers/cudnn_recurrent.py
# 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. # ============================================================================== """Recurrent layers backed by cuDNN.""" import tensorflow.compat.v2 as tf import collections from keras import backend from keras import constraints from keras import initializers from keras import regularizers from keras.engine.input_spec import InputSpec from keras.layers import recurrent_v2 from keras.layers.recurrent import RNN from tensorflow.python.util.tf_export import keras_export class _CuDNNRNN(RNN): """Private base class for CuDNNGRU and CuDNNLSTM layers. Args: return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state in addition to the output. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. time_major: Boolean (default False). If true, the inputs and outputs will be in shape `(timesteps, batch, ...)`, whereas in the False case, it will be `(batch, timesteps, ...)`. """ def __init__(self, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, **kwargs): # We invoke the base layer's initializer directly here because we do not # want to create RNN cell instance. super(RNN, self).__init__(**kwargs) # pylint: disable=bad-super-call self.return_sequences = return_sequences self.return_state = return_state self.go_backwards = go_backwards self.stateful = stateful self.time_major = time_major self.supports_masking = False self.input_spec = [InputSpec(ndim=3)] if hasattr(self.cell.state_size, '__len__'): state_size = self.cell.state_size else: state_size = [self.cell.state_size] self.state_spec = [InputSpec(shape=(None, dim)) for dim in state_size] self.constants_spec = None self._states = None self._num_constants = 0 self._vector_shape = tf.constant([-1]) def call(self, inputs, mask=None, training=None, initial_state=None): if isinstance(mask, list): mask = mask[0] if mask is not None: raise ValueError('Masking is not supported for CuDNN RNNs.') # input shape: `(samples, time (padded with zeros), input_dim)` # note that the .build() method of subclasses MUST define # self.input_spec and self.state_spec with complete input shapes. if isinstance(inputs, list): initial_state = inputs[1:] inputs = inputs[0] elif initial_state is not None: pass elif self.stateful: initial_state = self.states else: initial_state = self.get_initial_state(inputs) if len(initial_state) != len(self.states): raise ValueError('Layer has ' + str(len(self.states)) + ' states but was passed ' + str(len(initial_state)) + ' initial states.') if self.go_backwards: # Reverse time axis. inputs = backend.reverse(inputs, 1) output, states = self._process_batch(inputs, initial_state) if self.stateful: updates = [ tf.compat.v1.assign(self_state, state) for self_state, state in zip(self.states, states) ] self.add_update(updates) if self.return_state: return [output] + states else: return output def get_config(self): config = { 'return_sequences': self.return_sequences, 'return_state': self.return_state, 'go_backwards': self.go_backwards, 'stateful': self.stateful, 'time_major': self.time_major, } base_config = super( # pylint: disable=bad-super-call RNN, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): return cls(**config) @property def trainable_weights(self): if self.trainable and self.built: return [self.kernel, self.recurrent_kernel, self.bias] return [] @property def non_trainable_weights(self): if not self.trainable and self.built: return [self.kernel, self.recurrent_kernel, self.bias] return [] @property def losses(self): return super(RNN, self).losses def get_losses_for(self, inputs=None): return super( # pylint: disable=bad-super-call RNN, self).get_losses_for(inputs=inputs) @keras_export(v1=['keras.layers.CuDNNGRU']) class CuDNNGRU(_CuDNNRNN): """Fast GRU implementation backed by cuDNN. More information about cuDNN can be found on the [NVIDIA developer website](https://developer.nvidia.com/cudnn). Can only be run on GPU. Args: units: Positive integer, dimensionality of the output space. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_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` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state in addition to the output. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. """ def __init__(self, units, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, **kwargs): self.units = units cell_spec = collections.namedtuple('cell', 'state_size') self._cell = cell_spec(state_size=self.units) super(CuDNNGRU, self).__init__( return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, **kwargs) self.kernel_initializer = initializers.get(kernel_initializer) self.recurrent_initializer = initializers.get(recurrent_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.recurrent_regularizer = regularizers.get(recurrent_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.recurrent_constraint = constraints.get(recurrent_constraint) self.bias_constraint = constraints.get(bias_constraint) @property def cell(self): return self._cell def build(self, input_shape): super(CuDNNGRU, self).build(input_shape) if isinstance(input_shape, list): input_shape = input_shape[0] input_dim = int(input_shape[-1]) self.kernel = self.add_weight( shape=(input_dim, self.units * 3), name='kernel', initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.recurrent_kernel = self.add_weight( shape=(self.units, self.units * 3), name='recurrent_kernel', initializer=self.recurrent_initializer, regularizer=self.recurrent_regularizer, constraint=self.recurrent_constraint) self.bias = self.add_weight( shape=(self.units * 6,), name='bias', initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint) self.built = True def _process_batch(self, inputs, initial_state): if not self.time_major: inputs = tf.transpose(inputs, perm=(1, 0, 2)) input_h = initial_state[0] input_h = tf.expand_dims(input_h, axis=0) params = recurrent_v2._canonical_to_params( # pylint: disable=protected-access weights=[ self.kernel[:, self.units:self.units * 2], self.kernel[:, :self.units], self.kernel[:, self.units * 2:], self.recurrent_kernel[:, self.units:self.units * 2], self.recurrent_kernel[:, :self.units], self.recurrent_kernel[:, self.units * 2:], ], biases=[ self.bias[self.units:self.units * 2], self.bias[:self.units], self.bias[self.units * 2:self.units * 3], self.bias[self.units * 4:self.units * 5], self.bias[self.units * 3:self.units * 4], self.bias[self.units * 5:], ], shape=self._vector_shape) args = { 'input': inputs, 'input_h': input_h, 'input_c': 0, 'params': params, 'is_training': True, 'rnn_mode': 'gru', } outputs, h, _, _, _ = tf.raw_ops.CudnnRNNV2(**args) if self.stateful or self.return_state: h = h[0] if self.return_sequences: if self.time_major: output = outputs else: output = tf.transpose(outputs, perm=(1, 0, 2)) else: output = outputs[-1] return output, [h] def get_config(self): config = { 'units': self.units, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(CuDNNGRU, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export(v1=['keras.layers.CuDNNLSTM']) class CuDNNLSTM(_CuDNNRNN): """Fast LSTM implementation backed by cuDNN. More information about cuDNN can be found on the [NVIDIA developer website](https://developer.nvidia.com/cudnn). Can only be run on GPU. Args: units: Positive integer, dimensionality of the output space. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_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` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output. in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state in addition to the output. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. """ def __init__(self, units, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, **kwargs): self.units = units cell_spec = collections.namedtuple('cell', 'state_size') self._cell = cell_spec(state_size=(self.units, self.units)) super(CuDNNLSTM, self).__init__( return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, **kwargs) self.kernel_initializer = initializers.get(kernel_initializer) self.recurrent_initializer = initializers.get(recurrent_initializer) self.bias_initializer = initializers.get(bias_initializer) self.unit_forget_bias = unit_forget_bias self.kernel_regularizer = regularizers.get(kernel_regularizer) self.recurrent_regularizer = regularizers.get(recurrent_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.recurrent_constraint = constraints.get(recurrent_constraint) self.bias_constraint = constraints.get(bias_constraint) @property def cell(self): return self._cell def build(self, input_shape): super(CuDNNLSTM, self).build(input_shape) if isinstance(input_shape, list): input_shape = input_shape[0] input_dim = int(input_shape[-1]) self.kernel = self.add_weight( shape=(input_dim, self.units * 4), name='kernel', initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.recurrent_kernel = self.add_weight( shape=(self.units, self.units * 4), name='recurrent_kernel', initializer=self.recurrent_initializer, regularizer=self.recurrent_regularizer, constraint=self.recurrent_constraint) if self.unit_forget_bias: def bias_initializer(_, *args, **kwargs): return tf.concat([ self.bias_initializer((self.units * 5,), *args, **kwargs), tf.compat.v1.ones_initializer()((self.units,), *args, **kwargs), self.bias_initializer((self.units * 2,), *args, **kwargs), ], axis=0) else: bias_initializer = self.bias_initializer self.bias = self.add_weight( shape=(self.units * 8,), name='bias', initializer=bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint) self.built = True def _process_batch(self, inputs, initial_state): if not self.time_major: inputs = tf.transpose(inputs, perm=(1, 0, 2)) input_h = initial_state[0] input_c = initial_state[1] input_h = tf.expand_dims(input_h, axis=0) input_c = tf.expand_dims(input_c, axis=0) params = recurrent_v2._canonical_to_params( # pylint: disable=protected-access weights=[ self.kernel[:, :self.units], self.kernel[:, self.units:self.units * 2], self.kernel[:, self.units * 2:self.units * 3], self.kernel[:, self.units * 3:], self.recurrent_kernel[:, :self.units], self.recurrent_kernel[:, self.units:self.units * 2], self.recurrent_kernel[:, self.units * 2:self.units * 3], self.recurrent_kernel[:, self.units * 3:], ], biases=[ self.bias[:self.units], self.bias[self.units:self.units * 2], self.bias[self.units * 2:self.units * 3], self.bias[self.units * 3:self.units * 4], self.bias[self.units * 4:self.units * 5], self.bias[self.units * 5:self.units * 6], self.bias[self.units * 6:self.units * 7], self.bias[self.units * 7:], ], shape=self._vector_shape) args = { 'input': inputs, 'input_h': input_h, 'input_c': input_c, 'params': params, 'is_training': True, } outputs, h, c, _, _ = tf.raw_ops.CudnnRNNV2(**args) if self.stateful or self.return_state: h = h[0] c = c[0] if self.return_sequences: if self.time_major: output = outputs else: output = tf.transpose(outputs, perm=(1, 0, 2)) else: output = outputs[-1] return output, [h, c] def get_config(self): config = { 'units': self.units, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'unit_forget_bias': self.unit_forget_bias, 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(CuDNNLSTM, self).get_config() return dict(list(base_config.items()) + list(config.items()))
20,506
37.330841
85
py
keras
keras-master/keras/layers/gru_v2_test.py
# 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 GRU V2 layer.""" import tensorflow.compat.v2 as tf import copy import os import shutil from absl.testing import parameterized import numpy as np from tensorflow.core.protobuf import rewriter_config_pb2 import keras from tensorflow.python.framework import test_util as tf_test_util from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.layers import recurrent as rnn_v1 from keras.layers import recurrent_v2 as rnn from keras.utils import np_utils # Global config for grappler setting that is used for graph mode test. _rewrites = rewriter_config_pb2.RewriterConfig() _rewrites.implementation_selector = rewriter_config_pb2.RewriterConfig.ON _rewrites.min_graph_nodes = -1 _graph_options = tf.compat.v1.GraphOptions(rewrite_options=_rewrites) _config = tf.compat.v1.ConfigProto(graph_options=_graph_options) @testing_utils.run_all_without_tensor_float_32('RNN GRU can use TF32 on GPU') @keras_parameterized.run_all_keras_modes(config=_config) class GRUV2Test(keras_parameterized.TestCase): @parameterized.named_parameters( ('non_tan_activation', 'relu', 'sigmoid', 0, False, True, True), ('non_sigmoid_recur_activation', 'tanh', 'relu', 0, False, True, True), ('use_recurrent_dropout', 'tanh', 'sigmoid', 0.1, False, True, True), ('unroll', 'tanh', 'sigmoid', 0, True, True, True), ('not_use_bias', 'tanh', 'sigmoid', 0, False, False, True), ('not_reset_after', 'tanh', 'sigmoid', 0, False, True, False) ) def test_could_use_defun_backend(self, activation, recurrent_activation, recurrent_dropout, unroll, use_bias, reset_after): layer = rnn.GRU(1, activation=activation, recurrent_activation=recurrent_activation, recurrent_dropout=recurrent_dropout, unroll=unroll, use_bias=use_bias, reset_after=reset_after) self.assertFalse(layer._could_use_gpu_kernel) @testing_utils.run_v2_only def test_use_on_default_activation_with_gpu_kernel(self): layer = rnn.GRU(1, activation=tf.tanh) self.assertTrue(layer._could_use_gpu_kernel) layer = rnn.GRU(1, recurrent_activation=tf.sigmoid) self.assertTrue(layer._could_use_gpu_kernel) def test_keras_model_with_gru(self): input_shape = 10 rnn_state_size = 8 output_shape = 8 timestep = 4 batch = 100 epoch = 10 (x_train, y_train), _ = testing_utils.get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=output_shape) y_train = np_utils.to_categorical(y_train, output_shape) layer = rnn.GRU(rnn_state_size) inputs = keras.layers.Input( shape=[timestep, input_shape], dtype=tf.float32) outputs = layer(inputs) model = keras.models.Model(inputs, outputs) model.compile('rmsprop', loss='mse') model.fit(x_train, y_train, epochs=epoch) model.evaluate(x_train, y_train) model.predict(x_train) def test_dynamic_behavior_GRU(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer = rnn.GRU(units, input_shape=(None, embedding_dim)) model = keras.models.Sequential() model.add(layer) model.compile(tf.compat.v1.train.GradientDescentOptimizer(0.001), 'mse') x = np.random.random((num_samples, timesteps, embedding_dim)) y = np.random.random((num_samples, units)) model.train_on_batch(x, y) def test_stacking_GRU(self): inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(rnn.GRU(10, return_sequences=True, unroll=False)) model.add(rnn.GRU(5, return_sequences=True, unroll=False)) model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01)) model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) def test_from_config_GRU(self): layer_class = rnn.GRU for stateful in (False, True): l1 = layer_class(units=1, stateful=stateful) l2 = layer_class.from_config(l1.get_config()) assert l1.get_config() == l2.get_config() @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') @testing_utils.run_v2_only def test_gru_v2_feature_parity_with_canonical_gru(self): input_shape = 10 rnn_state_size = 8 timestep = 4 batch = 20 (x_train, y_train), _ = testing_utils.get_test_data( train_samples=batch, test_samples=0, input_shape=(timestep, input_shape), num_classes=rnn_state_size, random_seed=87654321) y_train = np_utils.to_categorical(y_train, rnn_state_size) # For the last batch item of the test data, we filter out the last # timestep to simulate the variable length sequence and masking test. x_train[-2:, -1, :] = 0.0 y_train[-2:] = 0 inputs = keras.layers.Input( shape=[timestep, input_shape], dtype=tf.float32) masked_input = keras.layers.Masking()(inputs) gru_layer = rnn_v1.GRU(rnn_state_size, recurrent_activation='sigmoid', reset_after=True) output = gru_layer(masked_input) gru_model = keras.models.Model(inputs, output) weights = gru_model.get_weights() y_1 = gru_model.predict(x_train) gru_model.compile('rmsprop', 'mse') gru_model.fit(x_train, y_train) y_2 = gru_model.predict(x_train) with testing_utils.device(should_use_gpu=True): cudnn_layer = rnn.GRU(rnn_state_size, recurrent_activation='sigmoid', reset_after=True) cudnn_model = keras.models.Model(inputs, cudnn_layer(masked_input)) cudnn_model.set_weights(weights) y_3 = cudnn_model.predict(x_train) cudnn_model.compile('rmsprop', 'mse') cudnn_model.fit(x_train, y_train) y_4 = cudnn_model.predict(x_train) self.assertAllClose(y_1, y_3, rtol=2e-5, atol=2e-5) self.assertAllClose(y_2, y_4, rtol=2e-5, atol=2e-5) @parameterized.named_parameters( # test_name, use_bias, bias_initializer, activation ('normal', True, 'zeros'), ('no_bias', False, 'zeros'), ('random_bias', True, 'random_uniform'), ) def test_gru_v2_model_save_load(self, use_bias, bias_initializer): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir) h5_path = os.path.join(temp_dir, 'test.h5') batch = 10 timestep = 3 input_dim = 5 units = 2 x = np.random.random((batch, timestep, input_dim)) def build_model(): inputs = keras.layers.Input( shape=[timestep, input_dim], dtype=tf.float32) layer = rnn.GRU( units, use_bias=use_bias, bias_initializer=bias_initializer) output = layer(inputs) return keras.models.Model(inputs, output), layer model, layer = build_model() y_ref = model.predict(x) model.save_weights(h5_path) cloned_model, new_layer = build_model() cloned_model.load_weights(h5_path) y = cloned_model.predict(x) self.assertAllClose(y, y_ref) self.assertAllClose(layer.get_weights(), new_layer.get_weights()) def test_gru_v2_output_on_multiple_kernel(self): input_shape = 10 rnn_state_size = 8 timestep = 4 batch = 100 x_train = np.random.random((batch, timestep, input_shape)) inputs = keras.layers.Input( shape=[timestep, input_shape], dtype=tf.float32) with testing_utils.device(should_use_gpu=False): layer = rnn.GRU(rnn_state_size) output = layer(inputs) cpu_model = keras.models.Model(inputs, output) weights = cpu_model.get_weights() y_1 = cpu_model.predict(x_train) with testing_utils.device(should_use_gpu=True): layer = rnn.GRU(rnn_state_size) output = layer(inputs) gpu_model = keras.models.Model(inputs, output) gpu_model.set_weights(weights) y_2 = gpu_model.predict(x_train) # Note that cuDNN uses 'sigmoid' as activation, so the GRU V2 uses # 'sigmoid' as default. Construct the canonical GRU with sigmoid to achieve # the same output. with testing_utils.device(should_use_gpu=True): layer = rnn_v1.GRU(rnn_state_size, recurrent_activation='sigmoid', reset_after=True) output = layer(inputs) canonical_model = keras.models.Model(inputs, output) canonical_model.set_weights(weights) y_3 = canonical_model.predict(x_train) self.assertAllClose(y_1, y_2, rtol=1e-5, atol=1e-5) self.assertAllClose(y_2, y_3, rtol=1e-5, atol=1e-5) @parameterized.named_parameters( # test_name, time_major, go_backwards ('normal', False, False), ('time_major', True, False), ('go_backwards', False, True), ('both', True, True), ) def test_time_major_and_go_backward(self, time_major, go_backwards): input_shape = 10 rnn_state_size = 8 timestep = 4 batch = 100 x_train = np.random.random((batch, timestep, input_shape)) def build_model(layer_cls): inputs = keras.layers.Input( shape=[timestep, input_shape], dtype=tf.float32) layer = layer_cls(rnn_state_size, recurrent_activation='sigmoid', time_major=time_major, return_sequences=True, go_backwards=go_backwards, reset_after=True) if time_major: converted_input = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(inputs) outputs = layer(converted_input) outputs = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(outputs) else: outputs = layer(inputs) return keras.models.Model(inputs, outputs) gru_model = build_model(rnn_v1.GRU) y_ref = gru_model.predict(x_train) weights = gru_model.get_weights() gru_v2_model = build_model(rnn.GRU) gru_v2_model.set_weights(weights) y = gru_v2_model.predict(x_train) self.assertAllClose(y, y_ref) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') def test_with_masking_layer_GRU(self): layer_class = rnn.GRU inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) model.add(layer_class(units=5, return_sequences=True, unroll=False)) model.compile(loss='categorical_crossentropy', optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.001)) model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') def test_masking_with_stacking_GRU(self): inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) model.add(rnn.GRU(10, return_sequences=True, unroll=False)) model.add(rnn.GRU(5, return_sequences=True, unroll=False)) model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01)) model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) def test_return_sequences_GRU(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( rnn.GRU, kwargs={'units': units, 'return_sequences': True}, input_shape=(num_samples, timesteps, embedding_dim)) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Double type is not yet supported in ROCm') @testing_utils.run_v2_only def test_float64_GRU(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( rnn.GRU, kwargs={'units': units, 'return_sequences': True, 'dtype': 'float64'}, input_shape=(num_samples, timesteps, embedding_dim), input_dtype='float64') @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') def test_return_states_GRU(self): layer_class = rnn.GRU x = np.random.random((2, 3, 4)) y = np.abs(np.random.random((2, 5))) s = np.abs(np.random.random((2, 5))) inputs = keras.layers.Input( shape=[3, 4], dtype=tf.float32) masked = keras.layers.Masking()(inputs) outputs, states = layer_class(units=5, return_state=True)(masked) model = keras.models.Model(inputs, [outputs, states]) model.compile(loss='categorical_crossentropy', optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.001)) model.fit(x, [y, s], epochs=1, batch_size=2, verbose=1) def test_dropout_GRU(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( rnn.GRU, kwargs={'units': units, 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) def test_constraints_GRU(self): embedding_dim = 4 layer_class = rnn.GRU k_constraint = keras.constraints.max_norm(0.01) r_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_constraint=k_constraint, recurrent_constraint=r_constraint, bias_constraint=b_constraint) layer.build((None, None, embedding_dim)) self.assertEqual(layer.cell.kernel.constraint, k_constraint) self.assertEqual(layer.cell.recurrent_kernel.constraint, r_constraint) self.assertEqual(layer.cell.bias.constraint, b_constraint) @parameterized.parameters([0, 1, 2]) def test_implementation_mode_GRU(self, implementation_mode): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( rnn.GRU, kwargs={'units': units, 'implementation': implementation_mode}, input_shape=(num_samples, timesteps, embedding_dim)) def test_regularizers_GRU(self): embedding_dim = 4 layer_class = rnn.GRU layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_regularizer=keras.regularizers.l1(0.01), recurrent_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l2', activity_regularizer='l1') layer.build((None, None, 2)) self.assertEqual(len(layer.losses), 3) x = keras.backend.variable(np.ones((2, 3, 2))) layer(x) if tf.executing_eagerly(): self.assertEqual(len(layer.losses), 4) else: self.assertEqual(len(layer.get_losses_for(x)), 1) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') def test_statefulness_GRU(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer_class = rnn.GRU model = keras.models.Sequential() model.add( keras.layers.Embedding( 4, embedding_dim, mask_zero=True, input_length=timesteps, batch_input_shape=(num_samples, timesteps))) layer = layer_class( units, return_sequences=False, stateful=True, weights=None) model.add(layer) model.compile( optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01), loss='mse', run_eagerly=testing_utils.should_run_eagerly()) out1 = model.predict(np.ones((num_samples, timesteps))) self.assertEqual(out1.shape, (num_samples, units)) # train once so that the states change model.train_on_batch( np.ones((num_samples, timesteps)), np.ones((num_samples, units))) out2 = model.predict(np.ones((num_samples, timesteps))) # if the state is not reset, output should be different self.assertNotEqual(out1.max(), out2.max()) # check that output changes after states are reset # (even though the model itself didn't change) layer.reset_states() out3 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out2.max(), out3.max()) # check that container-level reset_states() works model.reset_states() out4 = model.predict(np.ones((num_samples, timesteps))) np.testing.assert_allclose(out3, out4, atol=1e-5) # check that the call to `predict` updated the states out5 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out4.max(), out5.max()) # Check masking layer.reset_states() left_padded_input = np.ones((num_samples, timesteps)) left_padded_input[0, :1] = 0 left_padded_input[1, :2] = 0 out6 = model.predict(left_padded_input) layer.reset_states() right_padded_input = np.ones((num_samples, timesteps)) right_padded_input[0, -1:] = 0 right_padded_input[1, -2:] = 0 out7 = model.predict(right_padded_input) layer.reset_states() mix_padded_input = np.ones((num_samples, timesteps)) mix_padded_input[0, 1] = 0 mix_padded_input[1, 0] = 0 mix_padded_input[1, 2] = 0 out8 = model.predict(mix_padded_input) self.assertAllClose(out7, out6, atol=1e-5) self.assertAllClose(out8, out7, atol=1e-5) def test_stateful_GRU_training(self): # See b/123587692 for more context. vocab_size = 20 embedding_dim = 10 batch_size = 8 timestep = 12 units = 5 x = np.random.randint(0, vocab_size, size=(batch_size, timestep)) y = np.random.randint(0, vocab_size, size=(batch_size, timestep)) model = keras.Sequential([ keras.layers.Embedding(vocab_size, embedding_dim, batch_input_shape=[batch_size, timestep]), rnn.GRU(units, return_sequences=True, stateful=True), keras.layers.Dense(vocab_size) ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', run_eagerly=testing_utils.should_run_eagerly()) model.fit(x, y, epochs=1, shuffle=False) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') @testing_utils.run_v2_only def test_explicit_device_with_go_backward_and_mask(self): batch_size = 8 timestep = 7 masksteps = 5 units = 4 inputs = np.random.randn(batch_size, timestep, units).astype(np.float32) mask = np.ones((batch_size, timestep)).astype(np.bool) mask[:, masksteps:] = 0 # Test for V1 behavior. lstm_v1 = rnn_v1.GRU(units, return_sequences=True, go_backwards=True) with testing_utils.device(should_use_gpu=True): outputs_masked_v1 = lstm_v1(inputs, mask=tf.constant(mask)) outputs_trimmed_v1 = lstm_v1(inputs[:, :masksteps]) self.assertAllClose(outputs_masked_v1[:, -masksteps:], outputs_trimmed_v1) # Test for V2 behavior. lstm = rnn.GRU(units, return_sequences=True, go_backwards=True) with testing_utils.device(should_use_gpu=True): outputs_masked = lstm(inputs, mask=tf.constant(mask)) outputs_trimmed = lstm(inputs[:, :masksteps]) self.assertAllClose(outputs_masked[:, -masksteps:], outputs_trimmed) @tf_test_util.enable_output_all_intermediates def test_v1_session_behavior(self): with tf.compat.v1.get_default_graph().as_default(): # See b/139132348 for more details. x = np.random.uniform(size=(100, 4, 8)) y = np.random.uniform(size=(100, 1)) dataset = tf.data.Dataset.from_tensor_slices( (x, y)).shuffle(100).batch(32) inp = keras.layers.Input(shape=(4, 8)) layer = rnn.GRU(1)(inp) layer = keras.layers.Dense(1)(layer) model = keras.models.Model(inp, layer) model.compile(loss='mse', optimizer='sgd') model.fit(dataset) def test_with_fully_masked_inputs(self): num_samples = 8 timestep = 5 embedding_dim = 4 vocab_size = 20 units = 2 inputs = np.random.randint(0, vocab_size, size=(num_samples, timestep)) # Set the first inputs to be fully zero. inputs[0, :] = 0.0 model = keras.models.Sequential() model.add( keras.layers.Embedding( vocab_size, embedding_dim, mask_zero=True, input_length=timestep, batch_input_shape=(num_samples, timestep))) layer = rnn.GRU(units) model.add(layer) model.compile( optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01), loss='mse', run_eagerly=testing_utils.should_run_eagerly()) # Make sure it doesn't crash with cudnn kernel. model.predict(inputs) # TODO (b/169895267): test with xla_gpu is disabled. def test_deepcopy(self): if not tf.executing_eagerly(): self.skipTest('v2-only test') original_layer = rnn.GRU(5) copied_layer = copy.deepcopy(original_layer) self.assertEqual(copied_layer.units, 5) self.assertEqual(original_layer.get_config(), original_layer.get_config()) # Copy layer before layer call on inputs without weight initialization. inputs = np.random.normal(size=[32, 10, 8]).astype(np.float32) original_layer = rnn.GRU(4) copied_layer = copy.deepcopy(original_layer) outputs = original_layer(inputs) copied_outputs = copied_layer(inputs) self.assertNotAllClose( self.evaluate(outputs), self.evaluate(copied_outputs)) # Copy layer after layer call on inputs with weight initialization. original_layer = rnn.GRU(4) outputs = original_layer(inputs) copied_layer = copy.deepcopy(original_layer) copied_outputs = copied_layer(inputs) self.assertAllClose(self.evaluate(outputs), self.evaluate(copied_outputs)) @testing_utils.run_all_without_tensor_float_32('RNN GRU can use TF32 on GPU') class GRULayerGradientTapeTest(keras_parameterized.TestCase): @combinations.generate(combinations.combine(mode=['eager'])) def test_in_tape(self): with self.test_session(config=_config): time_steps = 10 embedding_size = 11 gru_unit_size = 12 gru = rnn.GRU(gru_unit_size, return_sequences=True, return_state=True, recurrent_activation='sigmoid', recurrent_initializer='glorot_uniform') x = tf.random.uniform([1, time_steps, embedding_size]) y = tf.random.uniform([1, gru_unit_size]) with tf.GradientTape() as tape: hidden_state = tf.zeros([1, gru_unit_size], dtype=tf.float32) _, state = gru(x, initial_state=hidden_state) loss = tf.reduce_mean(tf.square(state - y)) tape.gradient(loss, gru.variables) @testing_utils.run_all_without_tensor_float_32('RNN GRU can use TF32 on GPU') @keras_parameterized.run_all_keras_modes(config=_config) class GRUGraphRewriteTest(keras_parameterized.TestCase): input_shape = 10 output_shape = 8 rnn_state_size = 8 timestep = 4 batch = 100 epoch = 1 def _test_runtime_with_model(self, model): (x_train, y_train), _ = testing_utils.get_test_data( train_samples=self.batch, test_samples=0, input_shape=(self.timestep, self.input_shape), num_classes=self.output_shape) y_train = np_utils.to_categorical(y_train, self.output_shape) model.compile( optimizer='sgd', loss=['categorical_crossentropy', None]) existing_loss = 0 for _ in range(self.epoch): history = model.fit(x_train, y_train) loss_value = history.history['loss'][0] self.assertNotEqual(existing_loss, loss_value) existing_loss = loss_value _, runtime_value = model.predict(x_train) if tf.test.is_gpu_available(): self.assertEqual(runtime_value[0], rnn._RUNTIME_GPU) else: self.assertEqual(runtime_value[0], rnn._RUNTIME_CPU) @testing_utils.run_v2_only def test_GRU_runtime(self): layer = rnn.GRU(self.rnn_state_size, return_runtime=True) inputs = keras.layers.Input( shape=[self.timestep, self.input_shape], dtype=tf.float32) outputs, runtime = layer(inputs) # Expand the runtime so that it is a 1D tensor instead of scalar. # TF model does not work with scalar model output, specially during # aggregation. runtime = keras.layers.Lambda( lambda x: tf.expand_dims(x, axis=-1))(runtime) model = keras.models.Model(inputs=inputs, outputs=[outputs, runtime]) self._test_runtime_with_model(model) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input yet.') @testing_utils.run_v2_only def test_GRU_runtime_with_mask(self): # Masking will affect which backend is selected based on whether the mask # is strictly right padded. layer = rnn.GRU(self.rnn_state_size, return_runtime=True) inputs = keras.layers.Input( shape=[self.timestep, self.input_shape], dtype=tf.float32) masked_inputs = keras.layers.Masking()(inputs) outputs, runtime = layer(masked_inputs) # Expand the runtime so that it is a 1D tensor instead of scalar. # TF model does not work with scalar model output, specially during # aggregation. runtime = keras.layers.Lambda( lambda x: tf.expand_dims(x, axis=-1))(runtime) model = keras.models.Model(inputs=inputs, outputs=[outputs, runtime]) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=self.batch, test_samples=0, input_shape=(self.timestep, self.input_shape), num_classes=self.output_shape) y_train = np_utils.to_categorical(y_train, self.output_shape) model.compile( optimizer='sgd', loss=['categorical_crossentropy', None], run_eagerly=testing_utils.should_run_eagerly()) model.fit(x_train, y_train) # Verify unpadded data. _, runtime_value = model.predict(x_train) if tf.test.is_gpu_available(): self.assertEqual(runtime_value[0], rnn._RUNTIME_GPU) else: self.assertEqual(runtime_value[0], rnn._RUNTIME_CPU) # Update x/y to be right padded by setting the last timestep to 0 x_train[:, -1, :] = 0 y_train[:, -1] = 0 _, runtime_value = model.predict(x_train) if tf.test.is_gpu_available(): self.assertEqual(runtime_value[0], rnn._RUNTIME_GPU) else: self.assertEqual(runtime_value[0], rnn._RUNTIME_CPU) # Further update x/y to be mix padded (masks in the middle), and verify # only cpu kernel can be selected. x_train[:, -3, :] = 0 y_train[:, -3] = 0 _, runtime_value = model.predict(x_train) self.assertEqual(runtime_value[0], rnn._RUNTIME_CPU) @testing_utils.run_v2_only def test_GRU_runtime_with_cond(self): # This test is to demonstrate the graph rewrite of grappler plugin under # the condition that the function returns different number of internal # states. layer = rnn.GRU(self.rnn_state_size, return_runtime=True) inputs = keras.layers.Input( shape=[self.timestep, self.input_shape], dtype=tf.float32) zeros = tf.zeros([self.batch, self.output_shape]) dummy_runtime = rnn._runtime(rnn._RUNTIME_UNKNOWN) a = tf.constant(0) b = tf.constant(1) # Will always run the GRU layer. outputs, runtime = tf.cond( tf.less(a, b), lambda: layer(inputs), lambda: (zeros, dummy_runtime)) # Expand the runtime so that it is a 1D tensor instead of scalar. # TF model does not work with scalar model output, specially during # aggregation. runtime = keras.layers.Lambda( lambda x: tf.expand_dims(x, axis=-1))(runtime) model = keras.models.Model(inputs=inputs, outputs=[outputs, runtime]) self._test_runtime_with_model(model) if __name__ == '__main__': tf.test.main()
29,359
34.936353
80
py
keras
keras-master/keras/layers/kernelized_test.py
# 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 kernelized.py.""" import tensorflow.compat.v2 as tf import functools import math import os import shutil from absl.testing import parameterized import numpy as np from tensorflow.python.framework import test_util from keras import backend as keras_backend from keras import combinations from keras import initializers from keras import testing_utils from keras.engine import base_layer_utils from keras.engine import input_layer from keras.engine import training from keras.layers import kernelized as kernel_layers from keras.saving import save from keras.utils import kernelized_utils def _exact_gaussian(stddev): return functools.partial( kernelized_utils.exact_gaussian_kernel, stddev=stddev) def _exact_laplacian(stddev): return functools.partial( kernelized_utils.exact_laplacian_kernel, stddev=stddev) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class RandomFourierFeaturesTest(tf.test.TestCase, parameterized.TestCase): def _assert_all_close(self, expected, actual, atol=0.001): if not tf.executing_eagerly(): with self.cached_session() as sess: keras_backend._initialize_variables(sess) self.assertAllClose(expected, actual, atol=atol) else: self.assertAllClose(expected, actual, atol=atol) @testing_utils.run_v2_only def test_state_saving_and_loading(self): with self.cached_session(): input_data = np.random.random((1, 2)) rff_layer = kernel_layers.RandomFourierFeatures(output_dim=10, scale=3.0) inputs = input_layer.Input((2,)) outputs = rff_layer(inputs) model = training.Model(inputs, outputs) output_data = model.predict(input_data) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir) saved_model_dir = os.path.join(temp_dir, 'rff_model') model.save(saved_model_dir) new_model = save.load_model(saved_model_dir) new_output_data = new_model.predict(input_data) self.assertAllClose(output_data, new_output_data, atol=1e-4) def test_invalid_output_dim(self): with self.assertRaisesRegex( ValueError, '`output_dim` should be a positive integer'): _ = kernel_layers.RandomFourierFeatures(output_dim=-3, scale=2.0) def test_unsupported_kernel_type(self): with self.assertRaisesRegex( ValueError, 'Unsupported `kernel_initializer`'): _ = kernel_layers.RandomFourierFeatures( 3, 'unsupported_kernel', stddev=2.0) def test_invalid_scale(self): with self.assertRaisesRegex( ValueError, 'When provided, `scale` should be a positive float'): _ = kernel_layers.RandomFourierFeatures(output_dim=10, scale=0.0) def test_invalid_input_shape(self): inputs = tf.random.uniform((3, 2, 4), seed=1) rff_layer = kernel_layers.RandomFourierFeatures(output_dim=10, scale=3.0) with self.assertRaisesRegex( ValueError, 'The rank of the input tensor should be 2'): _ = rff_layer(inputs) @parameterized.named_parameters( ('gaussian', 'gaussian', 10.0, False), ('random', tf.compat.v1.random_uniform_initializer, 1.0, True)) def test_random_features_properties(self, initializer, scale, trainable): rff_layer = kernel_layers.RandomFourierFeatures( output_dim=10, kernel_initializer=initializer, scale=scale, trainable=trainable) self.assertEqual(rff_layer.output_dim, 10) self.assertEqual(rff_layer.kernel_initializer, initializer) self.assertEqual(rff_layer.scale, scale) self.assertEqual(rff_layer.trainable, trainable) @parameterized.named_parameters(('gaussian', 'gaussian', False), ('laplacian', 'laplacian', True), ('other', tf.compat.v1.ones_initializer, True)) def test_call(self, initializer, trainable): rff_layer = kernel_layers.RandomFourierFeatures( output_dim=10, kernel_initializer=initializer, scale=1.0, trainable=trainable, name='random_fourier_features') inputs = tf.random.uniform((3, 2), seed=1) outputs = rff_layer(inputs) self.assertListEqual([3, 10], outputs.shape.as_list()) num_trainable_vars = 1 if trainable else 0 self.assertLen(rff_layer.non_trainable_variables, 3 - num_trainable_vars) @test_util.assert_no_new_pyobjects_executing_eagerly def test_no_eager_Leak(self): # Tests that repeatedly constructing and building a Layer does not leak # Python objects. inputs = tf.random.uniform((5, 4), seed=1) kernel_layers.RandomFourierFeatures(output_dim=4, name='rff')(inputs) kernel_layers.RandomFourierFeatures(output_dim=10, scale=2.0)(inputs) def test_output_shape(self): inputs = tf.random.uniform((3, 2), seed=1) rff_layer = kernel_layers.RandomFourierFeatures( output_dim=7, name='random_fourier_features', trainable=True) outputs = rff_layer(inputs) self.assertEqual([3, 7], outputs.shape.as_list()) @parameterized.named_parameters( ('gaussian', 'gaussian'), ('laplacian', 'laplacian'), ('other', tf.compat.v1.random_uniform_initializer)) def test_call_on_placeholder(self, initializer): with tf.Graph().as_default(): inputs = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, None]) rff_layer = kernel_layers.RandomFourierFeatures( output_dim=5, kernel_initializer=initializer, name='random_fourier_features') with self.assertRaisesRegex( ValueError, 'The last dimension of the input tensor should be defined'): rff_layer(inputs) inputs = tf.compat.v1.placeholder(dtype=tf.float32, shape=[2, None]) rff_layer = kernel_layers.RandomFourierFeatures( output_dim=5, kernel_initializer=initializer, name='random_fourier_features') with self.assertRaisesRegex( ValueError, 'The last dimension of the input tensor should be defined'): rff_layer(inputs) inputs = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 3]) rff_layer = kernel_layers.RandomFourierFeatures( output_dim=5, name='random_fourier_features') rff_layer(inputs) @parameterized.named_parameters(('gaussian', 10, 'gaussian', 2.0), ('laplacian', 5, 'laplacian', None), ('other', 10, tf.compat.v1.ones_initializer, 1.0)) def test_compute_output_shape(self, output_dim, initializer, scale): rff_layer = kernel_layers.RandomFourierFeatures( output_dim, initializer, scale=scale, name='rff') with self.assertRaises(ValueError): rff_layer.compute_output_shape(tf.TensorShape(None)) with self.assertRaises(ValueError): rff_layer.compute_output_shape(tf.TensorShape([])) with self.assertRaises(ValueError): rff_layer.compute_output_shape(tf.TensorShape([3])) with self.assertRaises(ValueError): rff_layer.compute_output_shape(tf.TensorShape([3, 2, 3])) with self.assertRaisesRegex( ValueError, 'The last dimension of the input tensor should be defined'): rff_layer.compute_output_shape(tf.TensorShape([3, None])) self.assertEqual([None, output_dim], rff_layer.compute_output_shape((None, 3)).as_list()) self.assertEqual([None, output_dim], rff_layer.compute_output_shape( tf.TensorShape([None, 2])).as_list()) self.assertEqual([4, output_dim], rff_layer.compute_output_shape((4, 1)).as_list()) @parameterized.named_parameters( ('gaussian', 10, 'gaussian', 3.0, False), ('laplacian', 5, 'laplacian', 5.5, True), ('other', 7, tf.compat.v1.random_uniform_initializer(), None, True)) def test_get_config(self, output_dim, initializer, scale, trainable): rff_layer = kernel_layers.RandomFourierFeatures( output_dim, initializer, scale=scale, trainable=trainable, name='random_fourier_features', ) expected_initializer = initializer if not isinstance(initializer, str): expected_initializer = initializers.serialize(initializer) expected_dtype = ( 'float32' if base_layer_utils.v2_dtype_behavior_enabled() else None) expected_config = { 'output_dim': output_dim, 'kernel_initializer': expected_initializer, 'scale': scale, 'name': 'random_fourier_features', 'trainable': trainable, 'dtype': expected_dtype, } self.assertLen(expected_config, len(rff_layer.get_config())) self.assertSameElements( list(expected_config.items()), list(rff_layer.get_config().items())) @parameterized.named_parameters( ('gaussian', 5, 'gaussian', None, True), ('laplacian', 5, 'laplacian', 5.5, False), ('other', 7, tf.compat.v1.ones_initializer(), 2.0, True)) def test_from_config(self, output_dim, initializer, scale, trainable): model_config = { 'output_dim': output_dim, 'kernel_initializer': initializer, 'scale': scale, 'trainable': trainable, 'name': 'random_fourier_features', } rff_layer = kernel_layers.RandomFourierFeatures.from_config(model_config) self.assertEqual(rff_layer.output_dim, output_dim) self.assertEqual(rff_layer.kernel_initializer, initializer) self.assertEqual(rff_layer.scale, scale) self.assertEqual(rff_layer.trainable, trainable) inputs = tf.random.uniform((3, 2), seed=1) outputs = rff_layer(inputs) self.assertListEqual([3, output_dim], outputs.shape.as_list()) num_trainable_vars = 1 if trainable else 0 self.assertLen(rff_layer.trainable_variables, num_trainable_vars) if trainable: self.assertEqual('random_fourier_features/kernel_scale:0', rff_layer.trainable_variables[0].name) self.assertLen(rff_layer.non_trainable_variables, 3 - num_trainable_vars) @parameterized.named_parameters( ('gaussian', 10, 'gaussian', 3.0, True), ('laplacian', 5, 'laplacian', 5.5, False), ('other', 10, tf.compat.v1.random_uniform_initializer(), None, True)) def test_same_random_features_params_reused(self, output_dim, initializer, scale, trainable): """Applying the layer on the same input twice gives the same output.""" rff_layer = kernel_layers.RandomFourierFeatures( output_dim=output_dim, kernel_initializer=initializer, scale=scale, trainable=trainable, name='random_fourier_features') inputs = tf.constant( np.random.uniform(low=-1.0, high=1.0, size=(2, 4))) output1 = rff_layer(inputs) output2 = rff_layer(inputs) self._assert_all_close(output1, output2) @parameterized.named_parameters( ('gaussian', 'gaussian', 5.0), ('laplacian', 'laplacian', 3.0), ('other', tf.compat.v1.random_uniform_initializer(), 5.0)) def test_different_params_similar_approximation(self, initializer, scale): tf.compat.v1.set_random_seed(12345) rff_layer1 = kernel_layers.RandomFourierFeatures( output_dim=3000, kernel_initializer=initializer, scale=scale, name='rff1') rff_layer2 = kernel_layers.RandomFourierFeatures( output_dim=2000, kernel_initializer=initializer, scale=scale, name='rff2') # Two distinct inputs. x = tf.constant([[1.0, -1.0, 0.5]]) y = tf.constant([[-1.0, 1.0, 1.0]]) # Apply both layers to both inputs. output_x1 = math.sqrt(2.0 / 3000.0) * rff_layer1(x) output_y1 = math.sqrt(2.0 / 3000.0) * rff_layer1(y) output_x2 = math.sqrt(2.0 / 2000.0) * rff_layer2(x) output_y2 = math.sqrt(2.0 / 2000.0) * rff_layer2(y) # Compute the inner products of the outputs (on inputs x and y) for both # layers. For any fixed random features layer rff_layer, and inputs x, y, # rff_layer(x)^T * rff_layer(y) ~= K(x,y) up to a normalization factor. approx_kernel1 = kernelized_utils.inner_product(output_x1, output_y1) approx_kernel2 = kernelized_utils.inner_product(output_x2, output_y2) self._assert_all_close(approx_kernel1, approx_kernel2, atol=0.08) @parameterized.named_parameters( ('gaussian', 'gaussian', 5.0, _exact_gaussian(stddev=5.0)), ('laplacian', 'laplacian', 20.0, _exact_laplacian(stddev=20.0))) def test_bad_kernel_approximation(self, initializer, scale, exact_kernel_fn): """Approximation is bad when output dimension is small.""" # Two distinct inputs. x = tf.constant([[1.0, -1.0, 0.5]]) y = tf.constant([[-1.0, 1.0, 1.0]]) small_output_dim = 10 tf.compat.v1.set_random_seed(1234) # Initialize layer. rff_layer = kernel_layers.RandomFourierFeatures( output_dim=small_output_dim, kernel_initializer=initializer, scale=scale, name='random_fourier_features') # Apply layer to both inputs. output_x = math.sqrt(2.0 / small_output_dim) * rff_layer(x) output_y = math.sqrt(2.0 / small_output_dim) * rff_layer(y) # The inner products of the outputs (on inputs x and y) approximates the # real value of the RBF kernel but poorly since the output dimension of the # layer is small. exact_kernel_value = exact_kernel_fn(x, y) approx_kernel_value = kernelized_utils.inner_product(output_x, output_y) abs_error = tf.abs(exact_kernel_value - approx_kernel_value) if not tf.executing_eagerly(): with self.cached_session() as sess: keras_backend._initialize_variables(sess) abs_error_eval = sess.run([abs_error]) self.assertGreater(abs_error_eval[0][0], 0.05) self.assertLess(abs_error_eval[0][0], 0.5) else: self.assertGreater(abs_error, 0.05) self.assertLess(abs_error, 0.5) @parameterized.named_parameters( ('gaussian', 'gaussian', 5.0, _exact_gaussian(stddev=5.0)), ('laplacian', 'laplacian', 10.0, _exact_laplacian(stddev=10.0))) def test_good_kernel_approximation_multiple_inputs(self, initializer, scale, exact_kernel_fn): # Parameters. input_dim = 5 output_dim = 2000 x_rows = 20 y_rows = 30 x = tf.constant( np.random.uniform(size=(x_rows, input_dim)), dtype=tf.float32) y = tf.constant( np.random.uniform(size=(y_rows, input_dim)), dtype=tf.float32) tf.compat.v1.set_random_seed(1234) rff_layer = kernel_layers.RandomFourierFeatures( output_dim=output_dim, kernel_initializer=initializer, scale=scale, name='random_fourier_features') # The shapes of output_x and output_y are (x_rows, output_dim) and # (y_rows, output_dim) respectively. output_x = math.sqrt(2.0 / output_dim) * rff_layer(x) output_y = math.sqrt(2.0 / output_dim) * rff_layer(y) approx_kernel_matrix = kernelized_utils.inner_product(output_x, output_y) exact_kernel_matrix = exact_kernel_fn(x, y) self._assert_all_close(approx_kernel_matrix, exact_kernel_matrix, atol=0.05) if __name__ == '__main__': tf.test.main()
15,868
40.111399
84
py
keras
keras-master/keras/layers/pooling_test.py
# 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 pooling layers.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np import keras from keras import combinations from keras import testing_utils from keras.mixed_precision import policy @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class GlobalPoolingTest(tf.test.TestCase, parameterized.TestCase): @testing_utils.enable_v2_dtype_behavior def test_mixed_float16_policy(self): with policy.policy_scope('mixed_float16'): inputs1 = keras.Input(shape=(36, 512), dtype='float16') inputs2 = keras.Input(shape=(36,), dtype='bool') average_layer = keras.layers.pooling.GlobalAveragePooling1D() _ = average_layer(inputs1, inputs2) def test_globalpooling_1d(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling1D, input_shape=(3, 4, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling1D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling1D, input_shape=(3, 4, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling1D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 5)) def test_globalpooling_1d_masking_support(self): model = keras.Sequential() model.add(keras.layers.Masking(mask_value=0., input_shape=(None, 4))) model.add(keras.layers.GlobalAveragePooling1D()) model.compile(loss='mae', optimizer='rmsprop') model_input = np.random.random((2, 3, 4)) model_input[0, 1:, :] = 0 output = model.predict(model_input) self.assertAllClose(output[0], model_input[0, 0, :]) def test_globalpooling_1d_with_ragged(self): ragged_data = tf.ragged.constant( [[[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]], [[1.0, 1.0], [2.0, 2.0]]], ragged_rank=1) dense_data = ragged_data.to_tensor() inputs = keras.Input(shape=(None, 2), dtype='float32', ragged=True) out = keras.layers.GlobalAveragePooling1D()(inputs) model = keras.models.Model(inputs=inputs, outputs=out) output_ragged = model.predict(ragged_data, steps=1) inputs = keras.Input(shape=(None, 2), dtype='float32') masking = keras.layers.Masking(mask_value=0., input_shape=(3, 2))(inputs) out = keras.layers.GlobalAveragePooling1D()(masking) model = keras.models.Model(inputs=inputs, outputs=out) output_dense = model.predict(dense_data, steps=1) self.assertAllEqual(output_ragged, output_dense) def test_globalpooling_2d_with_ragged(self): ragged_data = tf.ragged.constant( [[[[1.0], [1.0]], [[2.0], [2.0]], [[3.0], [3.0]]], [[[1.0], [1.0]], [[2.0], [2.0]]]], ragged_rank=1) dense_data = ragged_data.to_tensor() inputs = keras.Input(shape=(None, 2, 1), dtype='float32', ragged=True) out = keras.layers.GlobalMaxPooling2D()(inputs) model = keras.models.Model(inputs=inputs, outputs=out) output_ragged = model.predict(ragged_data, steps=1) inputs = keras.Input(shape=(None, 2, 1), dtype='float32') out = keras.layers.GlobalMaxPooling2D()(inputs) model = keras.models.Model(inputs=inputs, outputs=out) output_dense = model.predict(dense_data, steps=1) self.assertAllEqual(output_ragged, output_dense) def test_globalpooling_3d_with_ragged(self): ragged_data = tf.ragged.constant( [[[[[1.0]], [[1.0]]], [[[2.0]], [[2.0]]], [[[3.0]], [[3.0]]]], [[[[1.0]], [[1.0]]], [[[2.0]], [[2.0]]]]], ragged_rank=1) inputs = keras.Input(shape=(None, 2, 1, 1), dtype='float32', ragged=True) out = keras.layers.GlobalAveragePooling3D()(inputs) model = keras.models.Model(inputs=inputs, outputs=out) output_ragged = model.predict(ragged_data, steps=1) # Because GlobalAveragePooling3D doesn't support masking, the results # cannot be compared with its dense equivalent. expected_output = tf.constant([[2.0], [1.5]]) self.assertAllEqual(output_ragged, expected_output) def test_globalpooling_2d(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling2D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 5, 6)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling2D, kwargs={'data_format': 'channels_last'}, input_shape=(3, 5, 6, 4)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling2D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 5, 6)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling2D, kwargs={'data_format': 'channels_last'}, input_shape=(3, 5, 6, 4)) def test_globalpooling_3d(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling3D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 3, 4, 3)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling3D, kwargs={'data_format': 'channels_last'}, input_shape=(3, 4, 3, 4, 3)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling3D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 4, 3, 4, 3)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling3D, kwargs={'data_format': 'channels_last'}, input_shape=(3, 4, 3, 4, 3)) def test_globalpooling_1d_keepdims(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling1D, kwargs={'keepdims': True}, input_shape=(3, 4, 5), expected_output_shape=(None, 1, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling1D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 5), expected_output_shape=(None, 4, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling1D, kwargs={'keepdims': True}, input_shape=(3, 4, 5), expected_output_shape=(None, 1, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling1D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 5), expected_output_shape=(None, 4, 1)) def test_globalpooling_2d_keepdims(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling2D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 5, 6), expected_output_shape=(None, 4, 1, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling2D, kwargs={'data_format': 'channels_last', 'keepdims': True}, input_shape=(3, 4, 5, 6), expected_output_shape=(None, 1, 1, 6)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling2D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 5, 6), expected_output_shape=(None, 4, 1, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling2D, kwargs={'data_format': 'channels_last', 'keepdims': True}, input_shape=(3, 4, 5, 6), expected_output_shape=(None, 1, 1, 6)) def test_globalpooling_3d_keepdims(self): testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling3D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 3, 4, 3), expected_output_shape=(None, 4, 1, 1, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalMaxPooling3D, kwargs={'data_format': 'channels_last', 'keepdims': True}, input_shape=(3, 4, 3, 4, 3), expected_output_shape=(None, 1, 1, 1, 3)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling3D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 3, 4, 3), expected_output_shape=(None, 4, 1, 1, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling3D, kwargs={'data_format': 'channels_last', 'keepdims': True}, input_shape=(3, 4, 3, 4, 3), expected_output_shape=(None, 1, 1, 1, 3)) def test_globalpooling_1d_keepdims_masking_support(self): model = keras.Sequential() model.add(keras.layers.Masking(mask_value=0., input_shape=(None, 4))) model.add(keras.layers.GlobalAveragePooling1D(keepdims=True)) model.compile(loss='mae', optimizer='rmsprop') model_input = np.random.random((2, 3, 4)) model_input[0, 1:, :] = 0 output = model.predict(model_input) self.assertAllEqual((2, 1, 4), output.shape) self.assertAllClose(output[0, 0], model_input[0, 0, :]) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class Pooling2DTest(tf.test.TestCase, parameterized.TestCase): def test_maxpooling_2d(self): pool_size = (3, 3) for strides in [(1, 1), (2, 2)]: testing_utils.layer_test( keras.layers.MaxPooling2D, kwargs={ 'strides': strides, 'padding': 'valid', 'pool_size': pool_size }, input_shape=(3, 5, 6, 4)) def test_averagepooling_2d(self): testing_utils.layer_test( keras.layers.AveragePooling2D, kwargs={ 'strides': (2, 2), 'padding': 'same', 'pool_size': (2, 2) }, input_shape=(3, 5, 6, 4)) testing_utils.layer_test( keras.layers.AveragePooling2D, kwargs={ 'strides': (2, 2), 'padding': 'valid', 'pool_size': (3, 3) }, input_shape=(3, 5, 6, 4)) # This part of the test can only run on GPU but doesn't appear # to be properly assigned to a GPU when running in eager mode. if not tf.executing_eagerly(): # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. if tf.test.is_gpu_available(cuda_only=True): testing_utils.layer_test( keras.layers.AveragePooling2D, kwargs={ 'strides': (1, 1), 'padding': 'valid', 'pool_size': (2, 2), 'data_format': 'channels_first' }, input_shape=(3, 4, 5, 6)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class Pooling3DTest(tf.test.TestCase, parameterized.TestCase): def test_maxpooling_3d(self): pool_size = (3, 3, 3) testing_utils.layer_test( keras.layers.MaxPooling3D, kwargs={ 'strides': 2, 'padding': 'valid', 'pool_size': pool_size }, input_shape=(3, 11, 12, 10, 4)) testing_utils.layer_test( keras.layers.MaxPooling3D, kwargs={ 'strides': 3, 'padding': 'valid', 'data_format': 'channels_first', 'pool_size': pool_size }, input_shape=(3, 4, 11, 12, 10)) def test_averagepooling_3d(self): pool_size = (3, 3, 3) testing_utils.layer_test( keras.layers.AveragePooling3D, kwargs={ 'strides': 2, 'padding': 'valid', 'pool_size': pool_size }, input_shape=(3, 11, 12, 10, 4)) testing_utils.layer_test( keras.layers.AveragePooling3D, kwargs={ 'strides': 3, 'padding': 'valid', 'data_format': 'channels_first', 'pool_size': pool_size }, input_shape=(3, 4, 11, 12, 10)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class Pooling1DTest(tf.test.TestCase, parameterized.TestCase): def test_maxpooling_1d(self): for padding in ['valid', 'same']: for stride in [1, 2]: testing_utils.layer_test( keras.layers.MaxPooling1D, kwargs={ 'strides': stride, 'padding': padding }, input_shape=(3, 5, 4)) testing_utils.layer_test( keras.layers.MaxPooling1D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 2, 6)) def test_averagepooling_1d(self): for padding in ['valid', 'same']: for stride in [1, 2]: testing_utils.layer_test( keras.layers.AveragePooling1D, kwargs={ 'strides': stride, 'padding': padding }, input_shape=(3, 5, 4)) testing_utils.layer_test( keras.layers.AveragePooling1D, kwargs={'data_format': 'channels_first'}, input_shape=(3, 2, 6)) if __name__ == '__main__': tf.test.main()
13,477
36.129477
80
py
keras
keras-master/keras/layers/cudnn_recurrent_test.py
# 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 cudnn recurrent layers.""" import tensorflow.compat.v2 as tf import os import tempfile from absl.testing import parameterized import numpy as np import keras from tensorflow.python.framework import test_util from keras import combinations from keras import keras_parameterized from keras import testing_utils from keras.optimizer_v2.rmsprop import RMSprop @keras_parameterized.run_all_keras_modes class CuDNNTest(keras_parameterized.TestCase): @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( layer_class=[keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM], return_sequences=[True, False])) @test_util.run_gpu_only def test_cudnn_rnn_return_sequence(self, layer_class, return_sequences): input_size = 10 timesteps = 6 units = 2 num_samples = 32 testing_utils.layer_test( layer_class, kwargs={'units': units, 'return_sequences': return_sequences}, input_shape=(num_samples, timesteps, input_size)) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( layer_class=[keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM], go_backwards=[True, False])) @test_util.run_gpu_only def test_cudnn_rnn_go_backward(self, layer_class, go_backwards): input_size = 10 timesteps = 6 units = 2 num_samples = 32 testing_utils.layer_test( layer_class, kwargs={'units': units, 'go_backwards': go_backwards}, input_shape=(num_samples, timesteps, input_size)) @parameterized.named_parameters( ('cudnngru', keras.layers.CuDNNGRU), ('cudnnlstm', keras.layers.CuDNNLSTM), ) @test_util.run_gpu_only def test_return_state(self, layer_class): input_size = 10 timesteps = 6 units = 2 num_samples = 32 num_states = 2 if layer_class is keras.layers.CuDNNLSTM else 1 inputs = keras.Input(batch_shape=(num_samples, timesteps, input_size)) layer = layer_class(units, return_state=True, stateful=True) outputs = layer(inputs) _, state = outputs[0], outputs[1:] self.assertEqual(len(state), num_states) model = keras.models.Model(inputs, state[0]) model.run_eagerly = testing_utils.should_run_eagerly() inputs = np.random.random((num_samples, timesteps, input_size)) state = model.predict(inputs) np.testing.assert_allclose( keras.backend.eval(layer.states[0]), state, atol=1e-4) @parameterized.named_parameters( ('cudnngru', keras.layers.CuDNNGRU), ('cudnnlstm', keras.layers.CuDNNLSTM), ) @test_util.run_gpu_only def test_time_major_input(self, layer_class): input_size = 10 timesteps = 6 units = 2 num_samples = 32 model = keras.models.Sequential() model.add( keras.layers.Lambda(lambda t: tf.transpose(t, [1, 0, 2]))) layer = layer_class(units, time_major=True, return_sequences=True) model.add(layer) model.add( keras.layers.Lambda(lambda t: tf.transpose(t, [1, 0, 2]))) model.compile(loss='categorical_crossentropy', optimizer=RMSprop(learning_rate=0.001)) model.fit( np.ones((num_samples, timesteps, input_size)), np.ones((num_samples, timesteps, units))) out = model.predict(np.ones((num_samples, timesteps, input_size))) self.assertEqual(out.shape, (num_samples, timesteps, units)) @parameterized.named_parameters( ('cudnngru', keras.layers.CuDNNGRU), ('cudnnlstm', keras.layers.CuDNNLSTM), ) @test_util.run_gpu_only def test_specify_initial_state_keras_tensor(self, layer_class): input_size = 10 timesteps = 6 units = 2 num_samples = 32 num_states = 2 if layer_class is keras.layers.CuDNNLSTM else 1 inputs = keras.Input((timesteps, input_size)) initial_state = [keras.Input((units,)) for _ in range(num_states)] layer = layer_class(units) if len(initial_state) == 1: output = layer(inputs, initial_state=initial_state[0]) else: output = layer(inputs, initial_state=initial_state) self.assertTrue( any(initial_state[0] is t for t in layer._inbound_nodes[0].input_tensors)) model = keras.models.Model([inputs] + initial_state, output) model.compile( loss='categorical_crossentropy', optimizer=RMSprop(learning_rate=0.001), run_eagerly=testing_utils.should_run_eagerly()) inputs = np.random.random((num_samples, timesteps, input_size)) initial_state = [ np.random.random((num_samples, units)) for _ in range(num_states) ] targets = np.random.random((num_samples, units)) model.fit([inputs] + initial_state, targets) class CuDNNGraphOnlyTest(keras_parameterized.TestCase): @parameterized.named_parameters( ('cudnngru', keras.layers.CuDNNGRU), ('cudnnlstm', keras.layers.CuDNNLSTM), ) @test_util.run_gpu_only def test_regularizer(self, layer_class): input_size = 10 timesteps = 6 units = 2 num_samples = 32 with tf.Graph().as_default(): layer = layer_class( units, return_sequences=False, input_shape=(timesteps, input_size), kernel_regularizer=keras.regularizers.l1(0.01), recurrent_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l2') layer.build((None, None, input_size)) self.assertEqual(len(layer.losses), 3) layer = layer_class( units, return_sequences=False, input_shape=(timesteps, input_size), activity_regularizer='l2') self.assertTrue(layer.activity_regularizer) x = keras.backend.variable( np.ones((num_samples, timesteps, input_size))) layer(x) self.assertEqual(len(layer.get_losses_for(x)), 1) @parameterized.named_parameters( ('cudnngru', keras.layers.CuDNNGRU), ('cudnnlstm', keras.layers.CuDNNLSTM), ) @test_util.run_gpu_only @test_util.run_v1_only('b/120941292') def test_statefulness(self, layer_class): input_size = 10 timesteps = 6 units = 2 num_samples = 32 with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.Embedding( 10, input_size, input_length=timesteps, batch_input_shape=(num_samples, timesteps))) layer = layer_class( units, return_sequences=False, stateful=True, weights=None) model.add(layer) model.compile(optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01), loss='mse') out1 = model.predict(np.ones((num_samples, timesteps))) self.assertEqual(out1.shape, (num_samples, units)) # train once so that the states change model.train_on_batch( np.ones((num_samples, timesteps)), np.ones((num_samples, units))) out2 = model.predict(np.ones((num_samples, timesteps))) # if the state is not reset, output should be different self.assertNotEqual(out1.max(), out2.max()) # check that output changes after states are reset # (even though the model itself didn't change) layer.reset_states() out3 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out2.max(), out3.max()) # check that container-level reset_states() works model.reset_states() out4 = model.predict(np.ones((num_samples, timesteps))) self.assertAllClose(out3, out4, atol=1e-5) # check that the call to `predict` updated the states out5 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out4.max(), out5.max()) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class CuDNNV1OnlyTest(keras_parameterized.TestCase): @test_util.run_gpu_only def test_trainability(self): input_size = 10 units = 2 for layer_class in [keras.layers.CuDNNGRU, keras.layers.CuDNNLSTM]: layer = layer_class(units) layer.build((None, None, input_size)) self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 0) layer.trainable = False self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.non_trainable_weights), 3) self.assertEqual(len(layer.trainable_weights), 0) layer.trainable = True self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 0) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( rnn_type=['LSTM', 'GRU'], to_cudnn=[True, False], bidirectional=[True, False], implementation=[1, 2], model_nest_level=[1, 2], model_type=['seq', 'func'])) @test_util.run_v1_only('b/120911602, b/112083752') @test_util.run_gpu_only def test_load_weights_between_noncudnn_rnn(self, rnn_type, to_cudnn, bidirectional, implementation, model_nest_level, model_type): input_size = 10 timesteps = 6 input_shape = (timesteps, input_size) units = 2 num_samples = 32 inputs = np.random.random((num_samples, timesteps, input_size)) rnn_layer_kwargs = { 'recurrent_activation': 'sigmoid', # ensure biases are non-zero and properly converted 'bias_initializer': 'random_uniform', 'implementation': implementation } if rnn_type == 'LSTM': rnn_layer_class = keras.layers.LSTM cudnn_rnn_layer_class = keras.layers.CuDNNLSTM else: rnn_layer_class = keras.layers.GRU cudnn_rnn_layer_class = keras.layers.CuDNNGRU rnn_layer_kwargs['reset_after'] = True layer = rnn_layer_class(units, **rnn_layer_kwargs) if bidirectional: layer = keras.layers.Bidirectional(layer) cudnn_layer = cudnn_rnn_layer_class(units) if bidirectional: cudnn_layer = keras.layers.Bidirectional(cudnn_layer) model = self._make_nested_model(input_shape, layer, model_nest_level, model_type) cudnn_model = self._make_nested_model(input_shape, cudnn_layer, model_nest_level, model_type) if to_cudnn: self._convert_model_weights(model, cudnn_model) else: self._convert_model_weights(cudnn_model, model) self.assertAllClose(model.predict(inputs), cudnn_model.predict(inputs), atol=1e-4) def _make_nested_model(self, input_shape, layer, level=1, model_type='func'): # example: make_nested_seq_model((1,), Dense(10), level=2).summary() def make_nested_seq_model(input_shape, layer, level=1): model = layer for i in range(1, level + 1): layers = [keras.layers.InputLayer(input_shape), model] if (i == 1) else [model] model = keras.models.Sequential(layers) if i > 1: model.build((None,) + input_shape) return model # example: make_nested_func_model((1,), Dense(10), level=2).summary() def make_nested_func_model(input_shape, layer, level=1): model_input = keras.layers.Input(input_shape) model = layer for _ in range(level): model = keras.models.Model(model_input, model(model_input)) return model if model_type == 'func': return make_nested_func_model(input_shape, layer, level) elif model_type == 'seq': return make_nested_seq_model(input_shape, layer, level) def _convert_model_weights(self, source_model, target_model): _, fname = tempfile.mkstemp('.h5') source_model.save_weights(fname) target_model.load_weights(fname) os.remove(fname) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( rnn_type=['LSTM', 'GRU'], to_cudnn=[True, False])) @test_util.run_v1_only('b/120911602') @test_util.run_gpu_only def test_load_weights_between_noncudnn_rnn_time_distributed(self, rnn_type, to_cudnn): # Similar test as test_load_weights_between_noncudnn_rnn() but has different # rank of input due to usage of TimeDistributed. Issue: #10356. input_size = 10 steps = 6 timesteps = 6 input_shape = (timesteps, steps, input_size) units = 2 num_samples = 32 inputs = np.random.random((num_samples, timesteps, steps, input_size)) rnn_layer_kwargs = { 'recurrent_activation': 'sigmoid', # ensure biases are non-zero and properly converted 'bias_initializer': 'random_uniform', } if rnn_type == 'LSTM': rnn_layer_class = keras.layers.LSTM cudnn_rnn_layer_class = keras.layers.CuDNNLSTM else: rnn_layer_class = keras.layers.GRU cudnn_rnn_layer_class = keras.layers.CuDNNGRU rnn_layer_kwargs['reset_after'] = True layer = rnn_layer_class(units, **rnn_layer_kwargs) layer = keras.layers.TimeDistributed(layer) cudnn_layer = cudnn_rnn_layer_class(units) cudnn_layer = keras.layers.TimeDistributed(cudnn_layer) model = self._make_nested_model(input_shape, layer) cudnn_model = self._make_nested_model(input_shape, cudnn_layer) if to_cudnn: self._convert_model_weights(model, cudnn_model) else: self._convert_model_weights(cudnn_model, model) self.assertAllClose(model.predict(inputs), cudnn_model.predict(inputs), atol=1e-4) @test_util.run_gpu_only def test_cudnnrnn_bidirectional(self): rnn = keras.layers.CuDNNGRU samples = 2 dim = 2 timesteps = 2 output_dim = 2 mode = 'concat' x = np.random.random((samples, timesteps, dim)) target_dim = 2 * output_dim if mode == 'concat' else output_dim y = np.random.random((samples, target_dim)) # test with Sequential model model = keras.Sequential() model.add( keras.layers.Bidirectional( rnn(output_dim), merge_mode=mode, input_shape=(None, dim))) model.compile(loss='mse', optimizer='rmsprop') model.fit(x, y, epochs=1, batch_size=1) # test config model.get_config() model = keras.models.model_from_json(model.to_json()) model.summary() # test stacked bidirectional layers model = keras.Sequential() model.add( keras.layers.Bidirectional( rnn(output_dim, return_sequences=True), merge_mode=mode, input_shape=(None, dim))) model.add(keras.layers.Bidirectional(rnn(output_dim), merge_mode=mode)) model.compile(loss='mse', optimizer=R'rmsprop') model.fit(x, y, epochs=1, batch_size=1) # test with functional API inputs = keras.Input((timesteps, dim)) outputs = keras.layers.Bidirectional( rnn(output_dim), merge_mode=mode)( inputs) model = keras.Model(inputs, outputs) model.compile(loss='mse', optimizer=R'rmsprop') model.fit(x, y, epochs=1, batch_size=1) # Bidirectional and stateful inputs = keras.Input(batch_shape=(1, timesteps, dim)) outputs = keras.layers.Bidirectional( rnn(output_dim, stateful=True), merge_mode=mode)( inputs) model = keras.Model(inputs, outputs) model.compile(loss='mse', optimizer='rmsprop') model.fit(x, y, epochs=1, batch_size=1) @test_util.run_gpu_only def test_preprocess_weights_for_loading_gru_incompatible(self): """Test loading weights between incompatible layers. Should fail fast with an exception. """ input_shape = (3, 5) def gru(cudnn=False, **kwargs): layer_class = keras.layers.CuDNNGRU if cudnn else keras.layers.GRUV1 return layer_class(2, input_shape=input_shape, **kwargs) def get_layer_weights(layer): layer.build(input_shape=input_shape) return layer.get_weights() def assert_not_compatible(src, dest, message): with self.assertRaises(ValueError) as ex: keras.saving.hdf5_format.preprocess_weights_for_loading( dest, get_layer_weights(src)) self.assertIn(message, str(ex.exception)) assert_not_compatible( gru(), gru(cudnn=True), 'GRU(reset_after=False) is not compatible with CuDNNGRU') assert_not_compatible( gru(cudnn=True), gru(), 'CuDNNGRU is not compatible with GRU(reset_after=False)') assert_not_compatible( gru(), gru(reset_after=True), 'GRU(reset_after=False) is not compatible with ' 'GRU(reset_after=True)') assert_not_compatible( gru(reset_after=True), gru(), 'GRU(reset_after=True) is not compatible with ' 'GRU(reset_after=False)') if __name__ == '__main__': tf.test.main()
17,576
34.580972
80
py
keras
keras-master/keras/layers/recurrent_test.py
# Copyright 2017 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 recurrent layers functionality other than GRU, LSTM, SimpleRNN. See also: lstm_test.py, gru_test.py, simplernn_test.py. """ import tensorflow.compat.v2 as tf import collections from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import testing_utils from keras.engine import base_layer_utils from keras.layers import recurrent as rnn_v1 from keras.layers import recurrent_v2 as rnn_v2 from keras.layers.legacy_rnn import rnn_cell_impl from keras.utils import generic_utils from tensorflow.python.training.tracking import util as trackable_util # Used for nested input/output/state RNN test. NestedInput = collections.namedtuple('NestedInput', ['t1', 't2']) NestedState = collections.namedtuple('NestedState', ['s1', 's2']) @keras_parameterized.run_all_keras_modes class RNNTest(keras_parameterized.TestCase): def test_minimal_rnn_cell_non_layer(self): class MinimalRNNCell: def __init__(self, units, input_dim): self.units = units self.state_size = units self.kernel = keras.backend.variable( np.random.random((input_dim, units))) def call(self, inputs, states): prev_output = states[0] output = keras.backend.dot(inputs, self.kernel) + prev_output return output, [output] # Basic test case. cell = MinimalRNNCell(32, 5) x = keras.Input((None, 5)) layer = keras.layers.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [MinimalRNNCell(8, 5), MinimalRNNCell(32, 8), MinimalRNNCell(32, 32)] layer = keras.layers.RNN(cells) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) def test_minimal_rnn_cell_non_layer_multiple_states(self): class MinimalRNNCell: def __init__(self, units, input_dim): self.units = units self.state_size = (units, units) self.kernel = keras.backend.variable( np.random.random((input_dim, units))) def call(self, inputs, states): prev_output_1 = states[0] prev_output_2 = states[1] output = keras.backend.dot(inputs, self.kernel) output += prev_output_1 output -= prev_output_2 return output, [output * 2, output * 3] # Basic test case. cell = MinimalRNNCell(32, 5) x = keras.Input((None, 5)) layer = keras.layers.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [MinimalRNNCell(8, 5), MinimalRNNCell(16, 8), MinimalRNNCell(32, 16)] layer = keras.layers.RNN(cells) self.assertEqual(layer.cell.state_size, ((8, 8), (16, 16), (32, 32))) self.assertEqual(layer.cell.output_size, 32) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) def test_minimal_rnn_cell_layer(self): class MinimalRNNCell(keras.layers.Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = keras.backend.dot(inputs, self.kernel) output = h + keras.backend.dot(prev_output, self.recurrent_kernel) return output, [output] def get_config(self): config = {'units': self.units} base_config = super(MinimalRNNCell, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = keras.Input((None, 5)) cell = MinimalRNNCell(32) layer = keras.layers.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # 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() with generic_utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}): layer = keras.layers.RNN.from_config(config) y = layer(x) model = 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) # Test stacking. cells = [MinimalRNNCell(8), MinimalRNNCell(12), MinimalRNNCell(32)] layer = keras.layers.RNN(cells) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacked RNN serialization. x_np = np.random.random((6, 5, 5)) y_np = model.predict(x_np) weights = model.get_weights() config = layer.get_config() with generic_utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}): layer = keras.layers.RNN.from_config(config) y = layer(x) model = 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 test_minimal_rnn_cell_abstract_rnn_cell(self): class MinimalRNNCell(keras.layers.AbstractRNNCell): def __init__(self, units, **kwargs): self.units = units super(MinimalRNNCell, self).__init__(**kwargs) @property def state_size(self): return self.units def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = keras.backend.dot(inputs, self.kernel) output = h + keras.backend.dot(prev_output, self.recurrent_kernel) return output, output @property def output_size(self): return self.units cell = MinimalRNNCell(32) x = keras.Input((None, 5)) layer = keras.layers.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer="rmsprop", loss="mse", run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [MinimalRNNCell(8), MinimalRNNCell(16), MinimalRNNCell(32)] layer = keras.layers.RNN(cells) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) def test_rnn_with_time_major(self): batch = 10 time_step = 5 embedding_dim = 4 units = 3 # Test basic case. x = keras.Input((time_step, embedding_dim)) time_major_x = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(x) layer = keras.layers.SimpleRNN( units, time_major=True, return_sequences=True) self.assertEqual( layer.compute_output_shape((time_step, None, embedding_dim)).as_list(), [time_step, None, units]) y = layer(time_major_x) self.assertEqual(layer.output_shape, (time_step, None, units)) y = keras.layers.Lambda(lambda t: tf.transpose(t, [1, 0, 2]))(y) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, embedding_dim)), np.zeros((batch, time_step, units))) # Test stacking. x = keras.Input((time_step, embedding_dim)) time_major_x = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(x) cell_units = [10, 8, 6] cells = [keras.layers.SimpleRNNCell(cell_units[i]) for i in range(3)] layer = keras.layers.RNN(cells, time_major=True, return_sequences=True) y = layer(time_major_x) self.assertEqual(layer.output_shape, (time_step, None, cell_units[-1])) y = keras.layers.Lambda(lambda t: tf.transpose(t, [1, 0, 2]))(y) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, embedding_dim)), np.zeros((batch, time_step, cell_units[-1]))) # Test masking. x = keras.Input((time_step, embedding_dim)) time_major = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(x) mask = keras.layers.Masking()(time_major) rnn = keras.layers.SimpleRNN( units, time_major=True, return_sequences=True)(mask) y = keras.layers.Lambda(lambda t: tf.transpose(t, [1, 0, 2]))(rnn) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, embedding_dim)), np.zeros((batch, time_step, units))) # Test layer output x = keras.Input((time_step, embedding_dim)) rnn_1 = keras.layers.SimpleRNN(units, return_sequences=True) y = rnn_1(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, embedding_dim)), np.zeros((batch, time_step, units))) x_np = np.random.random((batch, time_step, embedding_dim)) y_np_1 = model.predict(x_np) time_major = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(x) rnn_2 = keras.layers.SimpleRNN( units, time_major=True, return_sequences=True) y_2 = rnn_2(time_major) y_2 = keras.layers.Lambda( lambda t: tf.transpose(t, [1, 0, 2]))(y_2) model_2 = keras.models.Model(x, y_2) rnn_2.set_weights(rnn_1.get_weights()) y_np_2 = model_2.predict(x_np) self.assertAllClose(y_np_1, y_np_2, atol=1e-4) def test_rnn_cell_with_constants_layer(self): # Test basic case. x = keras.Input((None, 5)) c = keras.Input((3,)) cell = RNNCellWithConstants(32, constant_size=3) layer = keras.layers.RNN(cell) y = layer(x, constants=c) model = keras.models.Model([x, c], y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 3))], np.zeros((6, 32)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, c_np]) weights = model.get_weights() config = layer.get_config() custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with generic_utils.CustomObjectScope(custom_objects): layer = keras.layers.RNN.from_config(config.copy()) y = layer(x, constants=c) model = keras.models.Model([x, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, c_np]) self.assertAllClose(y_np, y_np_2, atol=1e-4) # test flat list inputs. with generic_utils.CustomObjectScope(custom_objects): layer = keras.layers.RNN.from_config(config.copy()) y = layer([x, c]) model = keras.models.Model([x, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, c_np]) self.assertAllClose(y_np, y_np_3, atol=1e-4) # Test stacking. cells = [keras.layers.recurrent.GRUCell(8), RNNCellWithConstants(12, constant_size=3), RNNCellWithConstants(32, constant_size=3)] layer = keras.layers.recurrent.RNN(cells) y = layer(x, constants=c) model = keras.models.Model([x, c], y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 3))], np.zeros((6, 32)) ) # Test GRUCell reset_after property. x = keras.Input((None, 5)) c = keras.Input((3,)) cells = [keras.layers.recurrent.GRUCell(32, reset_after=True)] layer = keras.layers.recurrent.RNN(cells) y = layer(x, constants=c) model = keras.models.Model([x, c], y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 3))], np.zeros((6, 32)) ) # Test stacked RNN serialization x_np = np.random.random((6, 5, 5)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, c_np]) weights = model.get_weights() config = layer.get_config() with generic_utils.CustomObjectScope(custom_objects): layer = keras.layers.recurrent.RNN.from_config(config.copy()) y = layer(x, constants=c) model = keras.models.Model([x, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, c_np]) self.assertAllClose(y_np, y_np_2, atol=1e-4) def test_rnn_cell_with_non_keras_constants(self): # Test basic case. x = keras.Input((None, 5)) c = tf.zeros([6, 3], dtype=tf.float32) cell = RNNCellWithConstants(32, constant_size=3) layer = keras.layers.RNN(cell) y = layer(x, constants=c) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [keras.layers.recurrent.GRUCell(8), RNNCellWithConstants(12, constant_size=3), RNNCellWithConstants(32, constant_size=3)] layer = keras.layers.recurrent.RNN(cells) y = layer(x, constants=c) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) def test_rnn_cell_with_constants_layer_passing_initial_state(self): # Test basic case. x = keras.Input((None, 5)) c = keras.Input((3,)) s = keras.Input((32,)) cell = RNNCellWithConstants(32, constant_size=3) layer = keras.layers.RNN(cell) y = layer(x, initial_state=s, constants=c) model = keras.models.Model([x, s, c], y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 32)), np.zeros((6, 3))], np.zeros((6, 32)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) s_np = np.random.random((6, 32)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, s_np, c_np]) weights = model.get_weights() config = layer.get_config() custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with generic_utils.CustomObjectScope(custom_objects): layer = keras.layers.RNN.from_config(config.copy()) y = layer(x, initial_state=s, constants=c) model = keras.models.Model([x, s, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, s_np, c_np]) self.assertAllClose(y_np, y_np_2, atol=1e-4) # verify that state is used y_np_2_different_s = model.predict([x_np, s_np + 10., c_np]) with self.assertRaises(AssertionError): self.assertAllClose(y_np, y_np_2_different_s, atol=1e-4) # test flat list inputs with generic_utils.CustomObjectScope(custom_objects): layer = keras.layers.RNN.from_config(config.copy()) y = layer([x, s, c]) model = keras.models.Model([x, s, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, s_np, c_np]) self.assertAllClose(y_np, y_np_3, atol=1e-4) def test_rnn_cell_with_non_keras_constants_and_initial_state(self): # Test basic case. x = keras.Input((None, 5)) c = tf.zeros([6, 3], dtype=tf.float32) s = tf.zeros([6, 32], dtype=tf.float32) cell = RNNCellWithConstants(32, constant_size=3) layer = keras.layers.RNN(cell) y = layer(x, initial_state=s, constants=c) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) # Test stacking. cells = [keras.layers.recurrent.GRUCell(8), RNNCellWithConstants(12, constant_size=3), RNNCellWithConstants(32, constant_size=3)] layer = keras.layers.recurrent.RNN(cells) s = [tf.zeros([6, 8], dtype=tf.float32), tf.zeros([6, 12], dtype=tf.float32), tf.zeros([6, 32], dtype=tf.float32)] y = layer(x, initial_state=s, constants=c) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32))) def test_stacked_rnn_attributes(self): if tf.executing_eagerly(): self.skipTest('reduce_sum is not available in eager mode.') cells = [keras.layers.LSTMCell(1), keras.layers.LSTMCell(1)] layer = keras.layers.RNN(cells) layer.build((None, None, 1)) # Test weights self.assertEqual(len(layer.trainable_weights), 6) cells[0].trainable = False self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 3) # Test `get_losses_for` and `losses` x = keras.Input((None, 1)) loss_1 = tf.reduce_sum(x) loss_2 = tf.reduce_sum(cells[0].kernel) cells[0].add_loss(loss_1, inputs=x) cells[0].add_loss(loss_2) self.assertEqual(len(layer.losses), 2) self.assertEqual(layer.get_losses_for(None), [loss_2]) self.assertEqual(layer.get_losses_for(x), [loss_1]) # Test `updates` cells = [keras.layers.LSTMCell(1), keras.layers.LSTMCell(1)] layer = keras.layers.RNN(cells) x = keras.Input((None, 1)) _ = layer(x) update_1 = tf.compat.v1.assign_add(cells[0].kernel, x[0, 0, 0] * cells[0].kernel) update_2 = tf.compat.v1.assign_add(cells[0].kernel, tf.ones_like(cells[0].kernel)) # TODO(b/128682878): Remove when RNNCells are __call__'d. with base_layer_utils.call_context().enter(layer, x, True, None): cells[0].add_update(update_1, inputs=x) cells[0].add_update(update_2) self.assertEqual(len(layer.updates), 2) def test_rnn_dynamic_trainability(self): layer_class = keras.layers.SimpleRNN embedding_dim = 4 units = 3 layer = layer_class(units) layer.build((None, None, embedding_dim)) self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 0) layer.trainable = False self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.trainable_weights), 0) self.assertEqual(len(layer.non_trainable_weights), 3) layer.trainable = True self.assertEqual(len(layer.weights), 3) self.assertEqual(len(layer.trainable_weights), 3) self.assertEqual(len(layer.non_trainable_weights), 0) @parameterized.parameters( [keras.layers.SimpleRNN, keras.layers.GRU, keras.layers.LSTM]) def test_rnn_cell_trainability(self, layer_cls): # https://github.com/tensorflow/tensorflow/issues/32369. layer = layer_cls(3, trainable=False) self.assertFalse(layer.cell.trainable) layer.trainable = True self.assertTrue(layer.cell.trainable) def test_state_reuse_with_dropout(self): layer_class = keras.layers.SimpleRNN embedding_dim = 4 units = 3 timesteps = 2 num_samples = 2 input1 = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) layer = layer_class(units, return_state=True, return_sequences=True, dropout=0.2) state = layer(input1)[1:] input2 = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) output = layer_class(units)(input2, initial_state=state) model = keras.Model([input1, input2], output) inputs = [np.random.random((num_samples, timesteps, embedding_dim)), np.random.random((num_samples, timesteps, embedding_dim))] model.predict(inputs) def test_builtin_and_custom_rnn_cell_serialization(self): @keras.utils.generic_utils.register_keras_serializable(package='TestOnly') class CustomRNNCell(keras.layers.Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(CustomRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states[0] h = keras.backend.dot(inputs, self.kernel) output = h + keras.backend.dot(prev_output, self.recurrent_kernel) return output, [output] def get_config(self): config = {'units': self.units} base_config = super(CustomRNNCell, self).get_config() return dict(list(base_config.items()) + list(config.items())) for cell_class in [keras.layers.SimpleRNNCell, keras.layers.GRUCell, keras.layers.LSTMCell, CustomRNNCell]: # Test basic case. x = keras.Input((None, 5)) cell = cell_class(32) layer = keras.layers.RNN(cell) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) # 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() layer = keras.layers.RNN.from_config(config) y = layer(x) model = 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) # Test stacking. cells = [cell_class(8), cell_class(12), cell_class(32)] layer = keras.layers.RNN(cells) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) # Test stacked RNN serialization. x_np = np.random.random((6, 5, 5)) y_np = model.predict(x_np) weights = model.get_weights() config = layer.get_config() layer = keras.layers.RNN.from_config(config) y = layer(x) model = 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) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( layer=[rnn_v1.SimpleRNN, rnn_v1.GRU, rnn_v1.LSTM, rnn_v2.GRU, rnn_v2.LSTM], unroll=[True, False])) def test_rnn_dropout(self, layer, unroll): rnn_layer = layer(3, dropout=0.1, recurrent_dropout=0.1, unroll=unroll) if not unroll: x = keras.Input((None, 5)) else: x = keras.Input((5, 5)) y = rnn_layer(x) model = keras.models.Model(x, y) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) x_np = np.random.random((6, 5, 5)) y_np = np.random.random((6, 3)) model.train_on_batch(x_np, y_np) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name( cell=[keras.layers.SimpleRNNCell, keras.layers.GRUCell, keras.layers.LSTMCell], unroll=[True, False])) def test_stacked_rnn_dropout(self, cell, unroll): cells = [cell(3, dropout=0.1, recurrent_dropout=0.1), cell(3, dropout=0.1, recurrent_dropout=0.1)] layer = keras.layers.RNN(cells, unroll=unroll) if not unroll: x = keras.Input((None, 5)) else: x = keras.Input((5, 5)) y = layer(x) model = keras.models.Model(x, y) model.compile( 'sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly()) x_np = np.random.random((6, 5, 5)) y_np = np.random.random((6, 3)) model.train_on_batch(x_np, y_np) def test_dropout_mask_reuse(self): # The layer is created with recurrent_initializer = zero, so that the # the recurrent state won't affect the output. By doing this, we can verify # the output and see if the same mask is applied to for each timestep. layer_1 = keras.layers.SimpleRNN(3, dropout=0.5, kernel_initializer='ones', recurrent_initializer='zeros', return_sequences=True, unroll=True) layer_2 = keras.layers.RNN( keras.layers.SimpleRNNCell(3, dropout=0.5, kernel_initializer='ones', recurrent_initializer='zeros'), return_sequences=True, unroll=True) layer_3 = keras.layers.RNN( [keras.layers.SimpleRNNCell(3, dropout=0.5, kernel_initializer='ones', recurrent_initializer='zeros'), keras.layers.SimpleRNNCell(3, dropout=0.5, kernel_initializer='ones', recurrent_initializer='zeros') ], return_sequences=True, unroll=True) def verify(rnn_layer): inputs = tf.constant(1.0, shape=(6, 2, 5)) out = rnn_layer(inputs, training=True) if not tf.executing_eagerly(): self.evaluate(tf.compat.v1.global_variables_initializer()) batch_1 = self.evaluate(out) batch_1_t0, batch_1_t1 = batch_1[:, 0, :], batch_1[:, 1, :] self.assertAllClose(batch_1_t0, batch_1_t1) # This simulate the layer called with multiple batches in eager mode if tf.executing_eagerly(): out2 = rnn_layer(inputs, training=True) else: out2 = out batch_2 = self.evaluate(out2) batch_2_t0, batch_2_t1 = batch_2[:, 0, :], batch_2[:, 1, :] self.assertAllClose(batch_2_t0, batch_2_t1) # Also validate that different dropout is used by between batches. self.assertNotAllClose(batch_1_t0, batch_2_t0) self.assertNotAllClose(batch_1_t1, batch_2_t1) for l in [layer_1, layer_2, layer_3]: verify(l) def test_stacked_rnn_compute_output_shape(self): cells = [keras.layers.LSTMCell(3), keras.layers.LSTMCell(6)] embedding_dim = 4 timesteps = 2 layer = keras.layers.RNN(cells, return_state=True, return_sequences=True) output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) expected_output_shape = [(None, timesteps, 6), (None, 3), (None, 3), (None, 6), (None, 6)] self.assertEqual( [tuple(o.as_list()) for o in output_shape], expected_output_shape) # Test reverse_state_order = True for stacked cell. stacked_cell = keras.layers.StackedRNNCells( cells, reverse_state_order=True) layer = keras.layers.RNN( stacked_cell, return_state=True, return_sequences=True) output_shape = layer.compute_output_shape((None, timesteps, embedding_dim)) expected_output_shape = [(None, timesteps, 6), (None, 6), (None, 6), (None, 3), (None, 3)] self.assertEqual( [tuple(o.as_list()) for o in output_shape], expected_output_shape) def test_stacked_rnn_with_training_param(self): # See https://github.com/tensorflow/tensorflow/issues/32586 class CellWrapper(keras.layers.AbstractRNNCell): def __init__(self, cell): super(CellWrapper, self).__init__() self.cell = cell @property def state_size(self): return self.cell.state_size @property def output_size(self): return self.cell.output_size def build(self, input_shape): self.cell.build(input_shape) self.built = True def get_initial_state(self, inputs=None, batch_size=None, dtype=None): return self.cell.get_initial_state( inputs=inputs, batch_size=batch_size, dtype=dtype) def call(self, inputs, states, training=None, **kwargs): assert training is not None return self.cell(inputs, states=states, training=training) cell = keras.layers.LSTMCell(32) cell = CellWrapper(cell) cell = keras.layers.StackedRNNCells([cell]) rnn = keras.layers.RNN(cell) inputs = np.ones((8, 4, 16), dtype=np.float32) rnn(inputs, training=True) def test_stacked_rnn_with_nested_cell(self): batch = 10 t = 5 i1, i2, i3 = 3, 4, 5 o11, o12, o13 = 2, 3, 4 o21, o22, o23 = 4, 5, 6 # test 1: use_tuple=False cells = [NestedCell(o11, o12, o13), NestedCell(o21, o22, o23)] rnn = keras.layers.RNN(cells, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) output1, output2, state1, state2 = rnn((input_1, input_2)) s11, s12 = state1 s21, s22 = state2 self.assertEqual(output1.shape.as_list(), [None, t, o21]) self.assertEqual(output2.shape.as_list(), [None, t, o22, o23]) self.assertEqual(s11.shape.as_list(), [None, o11]) self.assertEqual(s12.shape.as_list(), [None, o12, o13]) self.assertEqual(s21.shape.as_list(), [None, o21]) self.assertEqual(s22.shape.as_list(), [None, o22, o23]) model = keras.models.Model([input_1, input_2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, t, o21)), np.zeros((batch, t, o22, o23))]) self.assertEqual(model.output_shape, [(None, t, o21), (None, t, o22, o23)]) # test 2: use_tuple=True cells = [ NestedCell(o11, o12, o13, use_tuple=True), NestedCell(o21, o22, o23) ] rnn = keras.layers.RNN(cells, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) output1, output2, state1, state2 = rnn(NestedInput(t1=input_1, t2=input_2)) s11, s12 = state1 s21, s22 = state2 self.assertEqual(output1.shape.as_list(), [None, t, o21]) self.assertEqual(output2.shape.as_list(), [None, t, o22, o23]) self.assertEqual(s11.shape.as_list(), [None, o11]) self.assertEqual(s12.shape.as_list(), [None, o12, o13]) self.assertEqual(s21.shape.as_list(), [None, o21]) self.assertEqual(s22.shape.as_list(), [None, o22, o23]) model = keras.models.Model([input_1, input_2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, t, o21)), np.zeros((batch, t, o22, o23))]) self.assertEqual(model.output_shape, [(None, t, o21), (None, t, o22, o23)]) def test_trackable_dependencies(self): rnn = keras.layers.SimpleRNN x = np.random.random((2, 2, 2)) y = np.random.random((2, 2)) model = keras.models.Sequential() model.add(rnn(2)) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.fit(x, y, epochs=1, batch_size=1) # check whether the model variables are present in the # trackable list of objects checkpointed_objects = {id(o) for o in trackable_util.list_objects(model)} for v in model.variables: self.assertIn(id(v), checkpointed_objects) def test_high_dimension_RNN(self): # Basic test case. unit_a = 10 unit_b = 20 input_a = 5 input_b = 10 batch = 32 time_step = 4 cell = Minimal2DRNNCell(unit_a, unit_b) x = keras.Input((None, input_a, input_b)) layer = keras.layers.RNN(cell) y = layer(x) self.assertEqual(cell.state_size.as_list(), [unit_a, unit_b]) if not tf.executing_eagerly(): init_state = layer.get_initial_state(x) self.assertEqual(len(init_state), 1) self.assertEqual(init_state[0].shape.as_list(), [None, unit_a, unit_b]) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, input_a, input_b)), np.zeros((batch, unit_a, unit_b))) self.assertEqual(model.output_shape, (None, unit_a, unit_b)) # Test stacking. cells = [ Minimal2DRNNCell(unit_a, unit_b), Minimal2DRNNCell(unit_a * 2, unit_b * 2), Minimal2DRNNCell(unit_a * 4, unit_b * 4) ] layer = keras.layers.RNN(cells) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, input_a, input_b)), np.zeros((batch, unit_a * 4, unit_b * 4))) self.assertEqual(model.output_shape, (None, unit_a * 4, unit_b * 4)) def test_high_dimension_RNN_with_init_state(self): unit_a = 10 unit_b = 20 input_a = 5 input_b = 10 batch = 32 time_step = 4 # Basic test case. cell = Minimal2DRNNCell(unit_a, unit_b) x = keras.Input((None, input_a, input_b)) s = keras.Input((unit_a, unit_b)) layer = keras.layers.RNN(cell) y = layer(x, initial_state=s) model = keras.models.Model([x, s], y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch([ np.zeros((batch, time_step, input_a, input_b)), np.zeros((batch, unit_a, unit_b)) ], np.zeros((batch, unit_a, unit_b))) self.assertEqual(model.output_shape, (None, unit_a, unit_b)) # Bad init state shape. bad_shape_a = unit_a * 2 bad_shape_b = unit_b * 2 cell = Minimal2DRNNCell(unit_a, unit_b) x = keras.Input((None, input_a, input_b)) s = keras.Input((bad_shape_a, bad_shape_b)) layer = keras.layers.RNN(cell) with self.assertRaisesWithPredicateMatch(ValueError, 'however `cell.state_size` is'): layer(x, initial_state=s) def test_inconsistent_output_state_size(self): batch = 32 time_step = 4 state_size = 5 input_size = 6 cell = PlusOneRNNCell(state_size) x = keras.Input((None, input_size)) layer = keras.layers.RNN(cell) y = layer(x) self.assertEqual(cell.state_size, state_size) if not tf.executing_eagerly(): init_state = layer.get_initial_state(x) self.assertEqual(len(init_state), 1) self.assertEqual(init_state[0].shape.as_list(), [None, state_size]) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, time_step, input_size)), np.zeros((batch, input_size))) self.assertEqual(model.output_shape, (None, input_size)) def test_get_initial_state(self): cell = keras.layers.SimpleRNNCell(5) with self.assertRaisesRegex(ValueError, 'batch_size and dtype cannot be None'): cell.get_initial_state(None, None, None) if not tf.executing_eagerly(): inputs = keras.Input((None, 10)) initial_state = cell.get_initial_state(inputs, None, None) self.assertEqual(initial_state.shape.as_list(), [None, 5]) self.assertEqual(initial_state.dtype, inputs.dtype) batch = tf.shape(inputs)[0] dtype = inputs.dtype initial_state = cell.get_initial_state(None, batch, dtype) self.assertEqual(initial_state.shape.as_list(), [None, 5]) self.assertEqual(initial_state.dtype, inputs.dtype) else: batch = 8 inputs = np.random.random((batch, 10)) initial_state = cell.get_initial_state(inputs, None, None) self.assertEqual(initial_state.shape.as_list(), [8, 5]) self.assertEqual(initial_state.dtype, inputs.dtype) dtype = inputs.dtype initial_state = cell.get_initial_state(None, batch, dtype) self.assertEqual(initial_state.shape.as_list(), [batch, 5]) self.assertEqual(initial_state.dtype, inputs.dtype) @parameterized.parameters([True, False]) def test_nested_input_output(self, stateful): batch = 10 t = 5 i1, i2, i3 = 3, 4, 5 o1, o2, o3 = 2, 3, 4 cell = NestedCell(o1, o2, o3) rnn = keras.layers.RNN(cell, stateful=stateful) batch_size = batch if stateful else None input_1 = keras.Input((t, i1), batch_size=batch_size) input_2 = keras.Input((t, i2, i3), batch_size=batch_size) outputs = rnn((input_1, input_2)) self.assertEqual(len(outputs), 2) self.assertEqual(outputs[0].shape.as_list(), [batch_size, o1]) self.assertEqual(outputs[1].shape.as_list(), [batch_size, o2, o3]) model = keras.models.Model((input_1, input_2), outputs) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, o1)), np.zeros((batch, o2, o3))]) self.assertEqual(model.output_shape, [(batch_size, o1), (batch_size, o2, o3)]) cell = NestedCell(o1, o2, o3, use_tuple=True) rnn = keras.layers.RNN(cell, stateful=stateful) input_1 = keras.Input((t, i1), batch_size=batch_size) input_2 = keras.Input((t, i2, i3), batch_size=batch_size) outputs = rnn(NestedInput(t1=input_1, t2=input_2)) self.assertEqual(len(outputs), 2) self.assertEqual(outputs[0].shape.as_list(), [batch_size, o1]) self.assertEqual(outputs[1].shape.as_list(), [batch_size, o2, o3]) model = keras.models.Model([input_1, input_2], outputs) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, o1)), np.zeros((batch, o2, o3))]) self.assertEqual(model.output_shape, [(batch_size, o1), (batch_size, o2, o3)]) def test_nested_input_output_with_state(self): batch = 10 t = 5 i1, i2, i3 = 3, 4, 5 o1, o2, o3 = 2, 3, 4 cell = NestedCell(o1, o2, o3) rnn = keras.layers.RNN(cell, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) output1, output2, s1, s2 = rnn((input_1, input_2)) self.assertEqual(output1.shape.as_list(), [None, t, o1]) self.assertEqual(output2.shape.as_list(), [None, t, o2, o3]) self.assertEqual(s1.shape.as_list(), [None, o1]) self.assertEqual(s2.shape.as_list(), [None, o2, o3]) model = keras.models.Model([input_1, input_2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, t, o1)), np.zeros((batch, t, o2, o3))]) self.assertEqual(model.output_shape, [(None, t, o1), (None, t, o2, o3)]) cell = NestedCell(o1, o2, o3, use_tuple=True) rnn = keras.layers.RNN(cell, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) output1, output2, s1, s2 = rnn(NestedInput(t1=input_1, t2=input_2)) self.assertEqual(output1.shape.as_list(), [None, t, o1]) self.assertEqual(output2.shape.as_list(), [None, t, o2, o3]) self.assertEqual(s1.shape.as_list(), [None, o1]) self.assertEqual(s2.shape.as_list(), [None, o2, o3]) model = keras.models.Model([input_1, input_2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3))], [np.zeros((batch, t, o1)), np.zeros((batch, t, o2, o3))]) self.assertEqual(model.output_shape, [(None, t, o1), (None, t, o2, o3)]) def test_nest_input_output_with_init_state(self): batch = 10 t = 5 i1, i2, i3 = 3, 4, 5 o1, o2, o3 = 2, 3, 4 cell = NestedCell(o1, o2, o3) rnn = keras.layers.RNN(cell, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) init_s1 = keras.Input((o1,)) init_s2 = keras.Input((o2, o3)) output1, output2, s1, s2 = rnn((input_1, input_2), initial_state=(init_s1, init_s2)) self.assertEqual(output1.shape.as_list(), [None, t, o1]) self.assertEqual(output2.shape.as_list(), [None, t, o2, o3]) self.assertEqual(s1.shape.as_list(), [None, o1]) self.assertEqual(s2.shape.as_list(), [None, o2, o3]) model = keras.models.Model([input_1, input_2, init_s1, init_s2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3)), np.zeros((batch, o1)), np.zeros((batch, o2, o3))], [np.zeros((batch, t, o1)), np.zeros((batch, t, o2, o3))]) self.assertEqual(model.output_shape, [(None, t, o1), (None, t, o2, o3)]) cell = NestedCell(o1, o2, o3, use_tuple=True) rnn = keras.layers.RNN(cell, return_sequences=True, return_state=True) input_1 = keras.Input((t, i1)) input_2 = keras.Input((t, i2, i3)) init_s1 = keras.Input((o1,)) init_s2 = keras.Input((o2, o3)) init_state = NestedState(s1=init_s1, s2=init_s2) output1, output2, s1, s2 = rnn(NestedInput(t1=input_1, t2=input_2), initial_state=init_state) self.assertEqual(output1.shape.as_list(), [None, t, o1]) self.assertEqual(output2.shape.as_list(), [None, t, o2, o3]) self.assertEqual(s1.shape.as_list(), [None, o1]) self.assertEqual(s2.shape.as_list(), [None, o2, o3]) model = keras.models.Model([input_1, input_2, init_s1, init_s2], [output1, output2]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( [np.zeros((batch, t, i1)), np.zeros((batch, t, i2, i3)), np.zeros((batch, o1)), np.zeros((batch, o2, o3))], [np.zeros((batch, t, o1)), np.zeros((batch, t, o2, o3))]) self.assertEqual(model.output_shape, [(None, t, o1), (None, t, o2, o3)]) def test_peephole_lstm_cell(self): def _run_cell(cell_fn, **kwargs): inputs = tf.one_hot([1, 2, 3, 4], 4) cell = cell_fn(5, **kwargs) cell.build(inputs.shape) initial_state = cell.get_initial_state( inputs=inputs, batch_size=4, dtype=tf.float32) inputs, _ = cell(inputs, initial_state) output = inputs if not tf.executing_eagerly(): self.evaluate(tf.compat.v1.global_variables_initializer()) output = self.evaluate(output) return output tf.compat.v1.set_random_seed(12345) # `recurrent_activation` kwarg is set to sigmoid as that is hardcoded into # rnn_cell.LSTMCell. no_peephole_output = _run_cell( keras.layers.LSTMCell, kernel_initializer='ones', recurrent_activation='sigmoid', implementation=1) first_implementation_output = _run_cell( keras.layers.PeepholeLSTMCell, kernel_initializer='ones', recurrent_activation='sigmoid', implementation=1) second_implementation_output = _run_cell( keras.layers.PeepholeLSTMCell, kernel_initializer='ones', recurrent_activation='sigmoid', implementation=2) tf_lstm_cell_output = _run_cell( rnn_cell_impl.LSTMCell, use_peepholes=True, initializer=tf.compat.v1.ones_initializer) self.assertNotAllClose(first_implementation_output, no_peephole_output) self.assertAllClose(first_implementation_output, second_implementation_output) self.assertAllClose(first_implementation_output, tf_lstm_cell_output) def test_masking_rnn_with_output_and_states(self): class Cell(keras.layers.Layer): def __init__(self): self.state_size = None self.output_size = None super(Cell, self).__init__() def build(self, input_shape): self.state_size = input_shape[-1] self.output_size = input_shape[-1] def call(self, inputs, states): return inputs, [s + 1 for s in states] x = keras.Input((3, 1), name='x') x_masked = keras.layers.Masking()(x) s_0 = keras.Input((1,), name='s_0') y, s = keras.layers.RNN( Cell(), return_state=True)(x_masked, initial_state=s_0) model = keras.models.Model([x, s_0], [y, s]) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) # last time step masked x_np = np.array([[[1.], [2.], [0.]]]) s_0_np = np.array([[10.]]) y_np, s_np = model.predict([x_np, s_0_np]) # 1 is added to initial state two times self.assertAllClose(s_np, s_0_np + 2) # Expect last output to be the same as last output before masking self.assertAllClose(y_np, x_np[:, 1, :]) def test_zero_output_for_masking(self): for unroll in [True, False]: cell = keras.layers.SimpleRNNCell(5) x = keras.Input((5, 5)) mask = keras.layers.Masking() layer = keras.layers.RNN( cell, return_sequences=True, zero_output_for_mask=True, unroll=unroll) masked_input = mask(x) y = layer(masked_input) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) np_x = np.ones((6, 5, 5)) result_1 = model.predict(np_x) # set the time 4 and 5 for last record to be zero (masked). np_x[5, 3:] = 0 result_2 = model.predict(np_x) # expect the result_2 has same output, except the time 4,5 for last # record. result_1[5, 3:] = 0 self.assertAllClose(result_1, result_2) def test_unroll_single_step(self): """Even if the time dimension is only one, we should be able to unroll.""" cell = keras.layers.SimpleRNNCell(5) x = keras.Input((1, 5)) layer = keras.layers.RNN(cell, return_sequences=True, unroll=True) y = layer(x) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) np_x = np.ones((6, 1, 5)) result = model.predict(np_x) self.assertEqual((6, 1, 5), result.shape) def test_unroll_zero_step(self): """If the time dimension is None, we should fail to unroll.""" cell = keras.layers.SimpleRNNCell(5) x = keras.Input((None, 5)) layer = keras.layers.RNN(cell, return_sequences=True, unroll=True) with self.assertRaisesRegex(ValueError, 'Cannot unroll a RNN.*'): layer(x) def test_full_input_spec(self): # See https://github.com/tensorflow/tensorflow/issues/25985 inputs = keras.layers.Input(batch_shape=(1, 1, 1)) state_h = keras.layers.Input(batch_shape=(1, 1)) state_c = keras.layers.Input(batch_shape=(1, 1)) states = [state_h, state_c] decoder_out = keras.layers.LSTM(1, stateful=True)( inputs, initial_state=states ) model = keras.Model([inputs, state_h, state_c], decoder_out) output1 = model.predict( [np.ones((1, 1, 1)), np.ones((1, 1)), np.ones((1, 1))]) output2 = model.predict( [np.ones((1, 1, 1)), np.ones((1, 1)), np.ones((1, 1))]) model.reset_states() output3 = model.predict( [np.ones((1, 1, 1)), np.ones((1, 1)), np.ones((1, 1))]) self.assertAllClose(output1, output3) self.assertNotAllClose(output1, output2) def test_reset_states(self): # See https://github.com/tensorflow/tensorflow/issues/25852 with self.assertRaisesRegex(ValueError, 'it needs to know its batch size'): simple_rnn = keras.layers.SimpleRNN(1, stateful=True) simple_rnn.reset_states() with self.assertRaisesRegex(ValueError, 'it needs to know its batch size'): cell = Minimal2DRNNCell(1, 2) custom_rnn = keras.layers.RNN(cell, stateful=True) custom_rnn.reset_states() @parameterized.parameters( [keras.layers.SimpleRNNCell, keras.layers.GRUCell, keras.layers.LSTMCell]) def test_stateful_rnn_with_stacking(self, cell): # See https://github.com/tensorflow/tensorflow/issues/28614. batch = 12 timesteps = 10 input_dim = 8 output_dim = 64 cells = [cell(32), cell(64)] x = keras.Input(batch_shape=(batch, None, input_dim)) layer = keras.layers.RNN(cells, stateful=True) y = layer(x) model = keras.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, timesteps, input_dim)), np.zeros((batch, output_dim))) model.predict(np.ones((batch, timesteps, input_dim))) model.reset_states() model.predict(np.ones((batch, timesteps, input_dim))) new_states = tf.nest.map_structure(lambda s: np.ones((batch, s)), layer.cell.state_size) layer.reset_states(new_states) model.predict(np.ones((batch, timesteps, input_dim))) def test_stateful_rnn_with_initial_state(self): # See https://github.com/tensorflow/tensorflow/issues/32299. batch = 12 timesteps = 1 input_dim = 8 output_dim = 16 test_inputs = np.full((batch, timesteps, input_dim), 0.5) def make_model(stateful=False, with_initial_state=False): input_layer = keras.Input(shape=(None, input_dim), batch_size=batch) if with_initial_state: initial_states = keras.backend.constant(np.ones((batch, output_dim))) else: initial_states = None rnn_output = keras.layers.GRU( units=output_dim, return_sequences=True, stateful=stateful)( input_layer, initial_state=initial_states) model = keras.Model(input_layer, rnn_output) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) return model # Define a model with a constant state initialization model = make_model(stateful=True, with_initial_state=True) layer_weights = model.layers[1].get_weights() model.reset_states() predict_1 = model.predict(test_inputs) predict_2 = model.predict(test_inputs) model.reset_states() predict_3 = model.predict(test_inputs) # predict 1 and 2 should be different since the batch 2 should use the state # from batch 1 as the initial state. self.assertNotAllClose(predict_1, predict_2) self.assertAllClose(predict_1, predict_3) # Create a new model with same weights but without initial states. Make sure # the predict value is different from the model with non-zero initial state. model_2 = make_model(stateful=True, with_initial_state=False) model_2.layers[1].set_weights(layer_weights) model_2.reset_states() predict_4 = model_2.predict(test_inputs) predict_5 = model_2.predict(test_inputs) self.assertNotAllClose(predict_1, predict_4) self.assertNotAllClose(predict_4, predict_5) # Create models with stateful=False, and make sure they handle init state # correctly. model_3 = make_model(stateful=False, with_initial_state=True) model_3.layers[1].set_weights(layer_weights) model_3.reset_states() predict_6 = model_3.predict(test_inputs) predict_7 = model_3.predict(test_inputs) self.assertAllClose(predict_1, predict_6) self.assertAllClose(predict_6, predict_7) def test_stateful_rnn_with_customized_get_initial_state(self): class TestCell(keras.layers.AbstractRNNCell): state_size = 1 output_size = 2 def get_initial_state(self, inputs=None, batch_size=None, dtype=None): return np.ones((batch_size, 1), dtype=dtype) def call(self, inputs, states): return inputs, states layer = keras.layers.RNN(TestCell(), stateful=True, return_state=True) inputs = keras.Input(shape=(10, 2), batch_size=4) model = keras.Model(inputs, layer(inputs)) x = np.ones((4, 10, 2), dtype=np.float32) output, state = model.predict(x) self.assertAllClose(output, np.ones((4, 2))) self.assertAllClose(state, np.ones((4, 1))) def test_input_dim_length(self): simple_rnn = keras.layers.SimpleRNN(5, input_length=10, input_dim=8) self.assertEqual(simple_rnn._batch_input_shape, (None, 10, 8)) simple_rnn = keras.layers.SimpleRNN(5, input_dim=8) self.assertEqual(simple_rnn._batch_input_shape, (None, None, 8)) simple_rnn = keras.layers.SimpleRNN(5, input_length=10) self.assertEqual(simple_rnn._batch_input_shape, (None, 10, None)) @parameterized.parameters( [keras.layers.SimpleRNNCell, keras.layers.GRUCell, keras.layers.LSTMCell]) def test_state_spec_with_stack_cell(self, cell): # See https://github.com/tensorflow/tensorflow/issues/27817 for more detail. batch = 12 timesteps = 10 input_dim = 8 output_dim = 8 def create_cell(): return [cell(output_dim), cell(output_dim), cell(output_dim)] inputs = keras.Input((timesteps, input_dim)) encoder_output = keras.layers.RNN(create_cell(), return_state=True)(inputs) states = encoder_output[1:] decoder_output = keras.layers.RNN( create_cell())(inputs, initial_state=states) model = keras.models.Model(inputs, decoder_output) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch( np.zeros((batch, timesteps, input_dim)), np.zeros((batch, output_dim))) model.predict(np.ones((batch, timesteps, input_dim))) @parameterized.named_parameters( *testing_utils.generate_combinations_with_testcase_name(layer=[ rnn_v1.SimpleRNN, rnn_v1.GRU, rnn_v1.LSTM, rnn_v2.GRU, rnn_v2.LSTM ])) def test_rnn_with_ragged_input(self, layer): ragged_data = tf.ragged.constant( [[[1., 1., 1., 1., 1.], [1., 2., 3., 1., 1.]], [[2., 4., 1., 3., 1.]], [[2., 3., 4., 1., 5.], [2., 3., 1., 1., 1.], [1., 2., 3., 4., 5.]]], ragged_rank=1) label_data = np.array([[1, 0, 1], [1, 1, 0], [0, 0, 1]]) # Test results in feed forward np.random.seed(100) rnn_layer = layer(4, activation='sigmoid') x_ragged = keras.Input(shape=(None, 5), ragged=True) y_ragged = rnn_layer(x_ragged) model = keras.models.Model(x_ragged, y_ragged) output_ragged = model.predict(ragged_data, steps=1) x_dense = keras.Input(shape=(3, 5)) masking = keras.layers.Masking()(x_dense) y_dense = rnn_layer(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() output_dense = model_2.predict(dense_data, steps=1) self.assertAllClose(output_dense, output_ragged) # Test results with go backwards np.random.seed(200) back_rnn_layer = layer(8, go_backwards=True, activation='sigmoid') x_ragged = keras.Input(shape=(None, 5), ragged=True) y_ragged = back_rnn_layer(x_ragged) model = keras.models.Model(x_ragged, y_ragged) output_ragged = model.predict(ragged_data, steps=1) x_dense = keras.Input(shape=(3, 5)) masking = keras.layers.Masking()(x_dense) y_dense = back_rnn_layer(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() output_dense = model_2.predict(dense_data, steps=1) self.assertAllClose(output_dense, output_ragged) # Test densification of the ragged input dense_tensor, row_lengths = keras.backend.convert_inputs_if_ragged( ragged_data) self.assertAllClose(dense_data, dense_tensor) # Test optional params, all should work except unrolling inputs = keras.Input(shape=(None, 5), dtype=tf.float32, ragged=True) custom_rnn_layer = layer( 3, zero_output_for_mask=True, dropout=0.1, use_bias=True) outputs = custom_rnn_layer(inputs) model = keras.models.Model(inputs, outputs) model.compile( optimizer='sgd', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(ragged_data, label_data) # Test stateful and full shape specification inputs = keras.Input( shape=(None, 5), batch_size=3, dtype=tf.float32, ragged=True) stateful_rnn_layer = layer(3, stateful=True) outputs = stateful_rnn_layer(inputs) model = keras.models.Model(inputs, outputs) model.compile( optimizer='sgd', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(ragged_data, label_data) # Must raise error when unroll is set to True unroll_rnn_layer = layer(3, unroll=True) with self.assertRaisesRegex(ValueError, 'The input received contains RaggedTensors *'): unroll_rnn_layer(inputs) # Check if return sequences outputs are correct np.random.seed(100) returning_rnn_layer = layer(4, return_sequences=True) x_ragged = keras.Input(shape=(None, 5), ragged=True) y_ragged = returning_rnn_layer(x_ragged) model = keras.models.Model(x_ragged, y_ragged) output_ragged = model.predict(ragged_data, steps=1) self.assertAllClose(output_ragged.ragged_rank, ragged_data.ragged_rank) self.assertAllClose(output_ragged.row_splits, ragged_data.row_splits) x_dense = keras.Input(shape=(3, 5)) masking = keras.layers.Masking()(x_dense) y_dense = returning_rnn_layer(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() output_dense = model_2.predict(dense_data, steps=1) # Convert the output here to ragged for value comparison output_dense = tf.RaggedTensor.from_tensor( output_dense, lengths=row_lengths) self.assertAllClose(output_ragged, output_dense) # Check if return sequences and go_backwards outputs are correct np.random.seed(100) returning_rnn_layer = layer(4, go_backwards=True, return_sequences=True) x_ragged = keras.Input(shape=(None, 5), ragged=True) y_ragged = returning_rnn_layer(x_ragged) model = keras.models.Model(x_ragged, y_ragged) output_ragged = model.predict(ragged_data, steps=1) self.assertAllClose(output_ragged.ragged_rank, ragged_data.ragged_rank) self.assertAllClose(output_ragged.row_splits, ragged_data.row_splits) x_dense = keras.Input(shape=(3, 5)) masking = keras.layers.Masking()(x_dense) y_dense = returning_rnn_layer(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() output_dense = model_2.predict(dense_data, steps=1) # Note that the raw output for dense and ragged input when go_backward=True # will be different. Consider following input # [[a, b, 0], [c, 0, 0], [d, e, f]] where 0s are masked value. # The dense output will be [[0, b, a], [0, 0, c], [f, e, d]] since it will # process the whole sequence from the end. # While ragged output will be [[b, a], [c], [f, e, d]] since it just ignore # the 0s. And if we densify the ragged output, it will by default inserting # 0s to the end (rather than from the beginning), which make the output to # be [[b, a, 0], [c, 0, 0], [f, e, d]]. With this, we need to verify that # reverse(ragged_output.to_tensor()) == reverse(dense_output) output_dense = keras.backend.reverse(output_dense, [1]) output_dense = tf.RaggedTensor.from_tensor( output_dense, lengths=row_lengths) self.assertAllClose(keras.backend.reverse(output_ragged, [1]), output_dense) def test_stateless_rnn_cell(self): class StatelessCell(keras.layers.Layer): def __init__(self): self.state_size = ((), [], ()) self.output_size = None super(StatelessCell, self).__init__() def build(self, input_shape): self.output_size = input_shape[-1] def call(self, inputs, states): return inputs, states x = keras.Input((None, 5)) cell = StatelessCell() initial_state = tf.nest.map_structure(lambda t: None, cell.state_size) layer = keras.layers.RNN(cell) y = layer(x, initial_state=initial_state) model = keras.models.Model(x, y) model.compile( optimizer='rmsprop', loss='mse', run_eagerly=testing_utils.should_run_eagerly()) model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 5))) @parameterized.parameters( [rnn_v1.SimpleRNN, rnn_v1.GRU, rnn_v1.LSTM, rnn_v2.GRU, rnn_v2.LSTM]) def test_for_enable_caching_device_for_layer(self, layer_cls): expected_caching_device = tf.compat.v1.executing_eagerly_outside_functions() layer = layer_cls(1) self.assertEqual(layer.cell._enable_caching_device, expected_caching_device) # Make sure the config only appears when the none default value is used. config = layer.get_config() self.assertNotIn('enable_caching_device', config) non_default_value = not expected_caching_device layer = layer_cls(1, enable_caching_device=non_default_value) self.assertEqual(layer.cell._enable_caching_device, non_default_value) config = layer.get_config() self.assertEqual(config['enable_caching_device'], non_default_value) @parameterized.parameters( [rnn_v1.SimpleRNNCell, rnn_v1.GRUCell, rnn_v1.LSTMCell, rnn_v2.GRUCell, rnn_v2.LSTMCell]) def test_for_enable_caching_device_for_cell(self, cell_cls): expected_caching_device = tf.compat.v1.executing_eagerly_outside_functions() cell = cell_cls(1) self.assertEqual(cell._enable_caching_device, expected_caching_device) # Make sure the config only appears when the none default value is used. config = cell.get_config() self.assertNotIn('enable_caching_device', config) non_default_value = not expected_caching_device cell = cell_cls(1, enable_caching_device=non_default_value) self.assertEqual(cell._enable_caching_device, non_default_value) config = cell.get_config() self.assertEqual(config['enable_caching_device'], non_default_value) class RNNCellWithConstants(keras.layers.Layer): def __init__(self, units, constant_size, **kwargs): self.units = units self.state_size = units self.constant_size = constant_size super(RNNCellWithConstants, self).__init__(**kwargs) def build(self, input_shape): self.input_kernel = self.add_weight( shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.constant_kernel = self.add_weight( shape=(self.constant_size, self.units), initializer='uniform', name='constant_kernel') self.built = True def call(self, inputs, states, constants): [prev_output] = states [constant] = constants h_input = keras.backend.dot(inputs, self.input_kernel) h_state = keras.backend.dot(prev_output, self.recurrent_kernel) h_const = keras.backend.dot(constant, self.constant_kernel) output = h_input + h_state + h_const return output, [output] def get_config(self): config = {'units': self.units, 'constant_size': self.constant_size} base_config = super(RNNCellWithConstants, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Minimal2DRNNCell(keras.layers.Layer): """The minimal 2D RNN cell is a simple combination of 2 1-D RNN cell. Both internal state and output have 2 dimensions and are orthogonal between each other. """ def __init__(self, unit_a, unit_b, **kwargs): self.unit_a = unit_a self.unit_b = unit_b self.state_size = tf.TensorShape([unit_a, unit_b]) self.output_size = tf.TensorShape([unit_a, unit_b]) super(Minimal2DRNNCell, self).__init__(**kwargs) def build(self, input_shape): input_a = input_shape[-2] input_b = input_shape[-1] self.kernel = self.add_weight( shape=(input_a, input_b, self.unit_a, self.unit_b), initializer='uniform', name='kernel') self.recurring_kernel = self.add_weight( shape=(self.unit_a, self.unit_b, self.unit_a, self.unit_b), initializer='uniform', name='recurring_kernel') self.bias = self.add_weight( shape=(self.unit_a, self.unit_b), initializer='uniform', name='bias') self.built = True def call(self, inputs, states): prev_output = states[0] h = tf.einsum('bij,ijkl->bkl', inputs, self.kernel) h += tf.expand_dims(self.bias, axis=0) output = h + tf.einsum('bij,ijkl->bkl', prev_output, self.recurring_kernel) return output, [output] class PlusOneRNNCell(keras.layers.Layer): """Add one to the input and state. This cell is used for testing state_size and output_size.""" def __init__(self, num_unit, **kwargs): self.state_size = num_unit super(PlusOneRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.output_size = input_shape[-1] def call(self, inputs, states): return inputs + 1, [states[0] + 1] class NestedCell(keras.layers.Layer): def __init__(self, unit_1, unit_2, unit_3, use_tuple=False, **kwargs): self.unit_1 = unit_1 self.unit_2 = unit_2 self.unit_3 = unit_3 self.use_tuple = use_tuple super(NestedCell, self).__init__(**kwargs) # A nested state. if use_tuple: self.state_size = NestedState( s1=unit_1, s2=tf.TensorShape([unit_2, unit_3])) else: self.state_size = (unit_1, tf.TensorShape([unit_2, unit_3])) self.output_size = (unit_1, tf.TensorShape([unit_2, unit_3])) def build(self, inputs_shape): # expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)] if self.use_tuple: input_1 = inputs_shape.t1[1] input_2, input_3 = inputs_shape.t2[1:] else: input_1 = inputs_shape[0][1] input_2, input_3 = inputs_shape[1][1:] self.kernel_1 = self.add_weight( shape=(input_1, self.unit_1), initializer='uniform', name='kernel_1') self.kernel_2_3 = self.add_weight( shape=(input_2, input_3, self.unit_2, self.unit_3), initializer='uniform', name='kernel_2_3') def call(self, inputs, states): # inputs should be in [(batch, input_1), (batch, input_2, input_3)] # state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)] flatten_inputs = tf.nest.flatten(inputs) s1, s2 = states output_1 = tf.matmul(flatten_inputs[0], self.kernel_1) output_2_3 = tf.einsum('bij,ijkl->bkl', flatten_inputs[1], self.kernel_2_3) state_1 = s1 + output_1 state_2_3 = s2 + output_2_3 output = [output_1, output_2_3] new_states = NestedState(s1=state_1, s2=state_2_3) return output, new_states if __name__ == '__main__': tf.test.main()
71,327
34.987891
80
py
keras
keras-master/keras/layers/convolutional.py
# 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 convolution layers and image transformation layers.""" # pylint: disable=g-bad-import-order import tensorflow.compat.v2 as tf from keras import activations from keras import backend from keras import constraints from keras import initializers from keras import regularizers from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec # imports for backwards namespace compatibility # pylint: disable=unused-import from keras.layers.pooling import AveragePooling1D from keras.layers.pooling import AveragePooling2D from keras.layers.pooling import AveragePooling3D from keras.layers.pooling import MaxPooling1D from keras.layers.pooling import MaxPooling2D from keras.layers.pooling import MaxPooling3D # pylint: enable=unused-import from keras.utils import conv_utils from keras.utils import tf_utils from tensorflow.python.util.tf_export import keras_export # pylint: disable=g-classes-have-attributes class Conv(Layer): """Abstract N-D convolution layer (private, used as implementation base). This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. Note: layer attributes cannot be modified after the layer has been called once (except the `trainable` attribute). Args: rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). Could be "None", eg in the case of depth wise convolution. kernel_size: An integer or tuple/list of n integers, specifying the length of the convolution window. strides: An integer or tuple/list of n integers, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"same"`, or `"causal"` (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. `"causal"` results in causal (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. 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, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, ...)`. dilation_rate: An integer or tuple/list of n 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. groups: A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with `filters / groups` filters. The output is the concatenation of all the `groups` results along the channel axis. Input channels and `filters` must both be divisible by `groups`. activation: Activation function to use. If you don't specify anything, no activation is applied. use_bias: Boolean, whether the layer uses a bias. kernel_initializer: An initializer for the convolution kernel. If None, the default initializer (glorot_uniform) will be used. bias_initializer: An 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`. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, groups=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, trainable=True, name=None, conv_op=None, **kwargs): super(Conv, self).__init__( trainable=trainable, name=name, activity_regularizer=regularizers.get(activity_regularizer), **kwargs) self.rank = rank if isinstance(filters, float): filters = int(filters) if filters is not None and filters < 0: raise ValueError(f'Received a negative value for `filters`.' f'Was expecting a positive value. Received {filters}.') self.filters = filters self.groups = groups or 1 self.kernel_size = conv_utils.normalize_tuple( kernel_size, rank, 'kernel_size') self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.dilation_rate = conv_utils.normalize_tuple( dilation_rate, rank, 'dilation_rate') 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.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.input_spec = InputSpec(min_ndim=self.rank + 2) self._validate_init() self._is_causal = self.padding == 'causal' self._channels_first = self.data_format == 'channels_first' self._tf_data_format = conv_utils.convert_data_format( self.data_format, self.rank + 2) def _validate_init(self): if self.filters is not None and self.filters % self.groups != 0: raise ValueError( 'The number of filters must be evenly divisible by the number of ' 'groups. Received: groups={}, filters={}'.format( self.groups, self.filters)) if not all(self.kernel_size): raise ValueError('The argument `kernel_size` cannot contain 0(s). ' 'Received: %s' % (self.kernel_size,)) if not all(self.strides): raise ValueError('The argument `strides` cannot contains 0(s). ' 'Received: %s' % (self.strides,)) if (self.padding == 'causal' and not isinstance(self, (Conv1D, SeparableConv1D))): raise ValueError('Causal padding is only supported for `Conv1D`' 'and `SeparableConv1D`.') def build(self, input_shape): input_shape = tf.TensorShape(input_shape) input_channel = self._get_input_channel(input_shape) if input_channel % self.groups != 0: raise ValueError( 'The number of input channels must be evenly divisible by the number ' 'of groups. Received groups={}, but the input has {} channels ' '(full input shape is {}).'.format(self.groups, input_channel, input_shape)) kernel_shape = self.kernel_size + (input_channel // self.groups, self.filters) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None channel_axis = self._get_channel_axis() self.input_spec = InputSpec(min_ndim=self.rank + 2, axes={channel_axis: input_channel}) self.built = True def convolution_op(self, inputs, kernel): if self.padding == 'causal': tf_padding = 'VALID' # Causal padding handled in `call`. elif isinstance(self.padding, str): tf_padding = self.padding.upper() else: tf_padding = self.padding return tf.nn.convolution( inputs, kernel, strides=list(self.strides), padding=tf_padding, dilations=list(self.dilation_rate), data_format=self._tf_data_format, name=self.__class__.__name__) def call(self, inputs): input_shape = inputs.shape if self._is_causal: # Apply causal padding to inputs for Conv1D. inputs = tf.pad(inputs, self._compute_causal_padding(inputs)) outputs = self.convolution_op(inputs, self.kernel) if self.use_bias: output_rank = outputs.shape.rank if self.rank == 1 and self._channels_first: # nn.bias_add does not accept a 1D input tensor. bias = tf.reshape(self.bias, (1, self.filters, 1)) outputs += bias else: # Handle multiple batch dimensions. if output_rank is not None and output_rank > 2 + self.rank: def _apply_fn(o): return tf.nn.bias_add(o, self.bias, data_format=self._tf_data_format) outputs = conv_utils.squeeze_batch_dims( outputs, _apply_fn, inner_rank=self.rank + 1) else: outputs = tf.nn.bias_add( outputs, self.bias, data_format=self._tf_data_format) if not tf.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(input_shape) outputs.set_shape(out_shape) if self.activation is not None: return self.activation(outputs) return outputs def _spatial_output_shape(self, spatial_input_shape): return [ conv_utils.conv_output_length( length, self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i]) for i, length in enumerate(spatial_input_shape) ] def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() batch_rank = len(input_shape) - self.rank - 1 if self.data_format == 'channels_last': return tf.TensorShape( input_shape[:batch_rank] + self._spatial_output_shape(input_shape[batch_rank:-1]) + [self.filters]) else: return tf.TensorShape( input_shape[:batch_rank] + [self.filters] + self._spatial_output_shape(input_shape[batch_rank + 1:])) def _recreate_conv_op(self, inputs): # pylint: disable=unused-argument return False def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'groups': self.groups, '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) } base_config = super(Conv, self).get_config() return dict(list(base_config.items()) + list(config.items())) def _compute_causal_padding(self, inputs): """Calculates padding for 'causal' option for 1-d conv layers.""" left_pad = self.dilation_rate[0] * (self.kernel_size[0] - 1) if getattr(inputs.shape, 'ndims', None) is None: batch_rank = 1 else: batch_rank = len(inputs.shape) - 2 if self.data_format == 'channels_last': causal_padding = [[0, 0]] * batch_rank + [[left_pad, 0], [0, 0]] else: causal_padding = [[0, 0]] * batch_rank + [[0, 0], [left_pad, 0]] return causal_padding def _get_channel_axis(self): if self.data_format == 'channels_first': return -1 - self.rank else: return -1 def _get_input_channel(self, input_shape): channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') return int(input_shape[channel_axis]) def _get_padding_op(self): if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding if not isinstance(op_padding, (list, tuple)): op_padding = op_padding.upper() return op_padding @keras_export('keras.layers.Conv1D', 'keras.layers.Convolution1D') class Conv1D(Conv): """1D convolution layer (e.g. temporal convolution). This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide an `input_shape` argument (tuple of integers or `None`, e.g. `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors, or `(None, 128)` for variable-length sequences of 128-dimensional vectors. Examples: >>> # The inputs are 128-length vectors with 10 timesteps, and the batch size >>> # is 4. >>> input_shape = (4, 10, 128) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv1D( ... 32, 3, activation='relu',input_shape=input_shape[1:])(x) >>> print(y.shape) (4, 8, 32) >>> # With extended batch shape [4, 7] (e.g. weather data where batch >>> # dimensions correspond to spatial location and the third dimension >>> # corresponds to time.) >>> input_shape = (4, 7, 10, 128) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv1D( ... 32, 3, activation='relu', input_shape=input_shape[2:])(x) >>> print(y.shape) (4, 7, 8, 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 a single integer, specifying the length of the 1D convolution window. strides: An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"same"` or `"causal"` (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. `"causal"` results in causal (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. Useful when modeling temporal data where the model should not violate the temporal order. See [WaveNet: A Generative Model for Raw Audio, section 2.1](https://arxiv.org/abs/1609.03499). data_format: A string, one of `channels_last` (default) or `channels_first`. dilation_rate: an integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. groups: A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with `filters / groups` filters. The output is the concatenation of all the `groups` results along the channel axis. Input channels and `filters` must both be divisible by `groups`. 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 3+D tensor with shape: `batch_shape + (steps, input_dim)` Output shape: 3+D tensor with shape: `batch_shape + (new_steps, filters)` `steps` value might have changed due to padding or strides. Returns: A tensor of rank 3 representing `activation(conv1d(inputs, kernel) + bias)`. Raises: ValueError: when both `strides > 1` and `dilation_rate > 1`. """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, groups=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(Conv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, groups=groups, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv2D', 'keras.layers.Convolution2D') class Conv2D(Conv): """2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers or `None`, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. You can use `None` when a dimension has variable size. Examples: >>> # The inputs are 28x28 RGB images with `channels_last` and the batch >>> # size is 4. >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', input_shape=input_shape[1:])(x) >>> print(y.shape) (4, 26, 26, 2) >>> # With `dilation_rate` as 2. >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x) >>> print(y.shape) (4, 24, 24, 2) >>> # With `padding` as "same". >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', padding="same", input_shape=input_shape[1:])(x) >>> print(y.shape) (4, 28, 28, 2) >>> # With extended batch shape [4, 7]: >>> input_shape = (4, 7, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', input_shape=input_shape[2:])(x) >>> print(y.shape) (4, 7, 26, 26, 2) 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 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. 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. 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)`. 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: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. groups: A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with `filters / groups` filters. The output is the concatenation of all the `groups` results along the channel axis. Input channels and `filters` must both be divisible by `groups`. 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 4+D tensor with shape: `batch_shape + (channels, rows, cols)` if `data_format='channels_first'` or 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if `data_format='channels_last'`. Output shape: 4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if `data_format='channels_first'` or 4+D tensor with shape: `batch_shape + (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4+ representing `activation(conv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is `"causal"`. ValueError: when both `strides > 1` and `dilation_rate > 1`. """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), groups=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(Conv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, groups=groups, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv3D', 'keras.layers.Convolution3D') class Conv3D(Conv): """3D convolution layer (e.g. spatial convolution over volumes). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers or `None`, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes with a single channel, in `data_format="channels_last"`. Examples: >>> # The inputs are 28x28x28 volumes with a single channel, and the >>> # batch size is 4 >>> input_shape =(4, 28, 28, 28, 1) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv3D( ... 2, 3, activation='relu', input_shape=input_shape[1:])(x) >>> print(y.shape) (4, 26, 26, 26, 2) >>> # With extended batch shape [4, 7], e.g. a batch of 4 videos of 3D frames, >>> # with 7 frames per video. >>> input_shape = (4, 7, 28, 28, 28, 1) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv3D( ... 2, 3, activation='relu', input_shape=input_shape[2:])(x) >>> print(y.shape) (4, 7, 26, 26, 26, 2) 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 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along each spatial dimension. Can be a single integer to specify the same value for all spatial 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. 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_shape + (spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `batch_shape + (channels, spatial_dim1, spatial_dim2, spatial_dim3)`. 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: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. groups: A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with `filters / groups` filters. The output is the concatenation of all the `groups` results along the channel axis. Input channels and `filters` must both be divisible by `groups`. 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 5+D tensor with shape: `batch_shape + (channels, conv_dim1, conv_dim2, conv_dim3)` if data_format='channels_first' or 5+D tensor with shape: `batch_shape + (conv_dim1, conv_dim2, conv_dim3, channels)` if data_format='channels_last'. Output shape: 5+D tensor with shape: `batch_shape + (filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if data_format='channels_first' or 5+D tensor with shape: `batch_shape + (new_conv_dim1, new_conv_dim2, new_conv_dim3, filters)` if data_format='channels_last'. `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding. Returns: A tensor of rank 5+ representing `activation(conv3d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides > 1` and `dilation_rate > 1`. """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), groups=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(Conv3D, self).__init__( rank=3, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, groups=groups, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv1DTranspose', 'keras.layers.Convolution1DTranspose') class Conv1DTranspose(Conv1D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises 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. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers or `None`, does not include the sample axis), e.g. `input_shape=(128, 3)` for data with 128 time steps and 3 channels. Args: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer length of the 1D convolution window. strides: An integer specifying the stride of the convolution along the time dimension. Specifying a stride value != 1 is incompatible with specifying a `dilation_rate` value != 1. Defaults to 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. output_padding: An integer specifying the amount of padding along the time dimension of the output tensor. The amount of output padding must be lower than the stride. If set to `None` (default), the output shape is inferred. 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, length, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, length)`. dilation_rate: an integer, specifying the dilation rate to use for dilated convolution. Currently, specifying a `dilation_rate` value != 1 is incompatible with specifying a stride value != 1. Also dilation rate larger than 1 is not currently supported. 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 3D tensor with shape: `(batch_size, steps, channels)` Output shape: 3D tensor with shape: `(batch_size, new_steps, filters)` If `output_padding` is specified: ``` new_timesteps = ((timesteps - 1) * strides + kernel_size - 2 * padding + output_padding) ``` Returns: A tensor of rank 3 representing `activation(conv1dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". 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) """ def __init__(self, filters, kernel_size, strides=1, padding='valid', output_padding=None, 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(Conv1DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 1, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Strides must be greater than output padding. ' f'Received strides={self.strides}, ' f'output_padding={self.output_padding}.') def build(self, input_shape): input_shape = tf.TensorShape(input_shape) if len(input_shape) != 3: raise ValueError('Inputs should have rank 3. ' f'Received input_shape={input_shape}.') channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'to `Conv1DTranspose` should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = tf.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': t_axis = 2 else: t_axis = 1 length = inputs_shape[t_axis] if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] # Infer the dynamic output shape: out_length = conv_utils.deconv_output_length( length, self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_length) else: output_shape = (batch_size, out_length, self.filters) data_format = conv_utils.convert_data_format(self.data_format, ndim=3) output_shape_tensor = tf.stack(output_shape) outputs = tf.nn.conv1d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding.upper(), data_format=data_format, dilations=self.dilation_rate) if not tf.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, t_axis = 1, 2 else: c_axis, t_axis = 2, 1 if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] output_shape[c_axis] = self.filters output_shape[t_axis] = conv_utils.deconv_output_length( output_shape[t_axis], self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) return tf.TensorShape(output_shape) def get_config(self): config = super(Conv1DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv2DTranspose', 'keras.layers.Convolution2DTranspose') class Conv2DTranspose(Conv2D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises 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. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers or `None`, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. 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 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. 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. output_padding: An integer or tuple/list of 2 integers, specifying the amount of padding along the height and width of the output tensor. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. 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)`. 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: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the 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, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. If `output_padding` is specified: ``` new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) ``` Returns: A tensor of rank 4 representing `activation(conv2dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". 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) """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 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(Conv2DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 2, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Strides must be greater than output padding. ' f'Received strides={self.strides}, ' f'output_padding={self.output_padding}.') def build(self, input_shape): input_shape = tf.TensorShape(input_shape) if len(input_shape) != 4: raise ValueError('Inputs should have rank 4. ' f'Received input_shape={input_shape}.') channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'to `Conv2DTranspose` should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = tf.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 # Use the constant height and weight when possible. # TODO(scottzhu): Extract this into a utility function that can be applied # to all convolutional layers, which currently lost the static shape # information due to tf.shape(). height, width = None, None if inputs.shape.rank is not None: dims = inputs.shape.as_list() height = dims[h_axis] width = dims[w_axis] height = height if height is not None else inputs_shape[h_axis] width = width if width is not None else inputs_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding # Infer the dynamic output shape: out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) output_shape_tensor = tf.stack(output_shape) outputs = backend.conv2d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if not tf.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, h_axis, w_axis = 1, 2, 3 else: c_axis, h_axis, w_axis = 3, 1, 2 kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) return tf.TensorShape(output_shape) def get_config(self): config = super(Conv2DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv3DTranspose', 'keras.layers.Convolution3DTranspose') class Conv3DTranspose(Conv3D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises 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. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers or `None`, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels if `data_format="channels_last"`. 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 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along the depth, height and width. Can be a single integer to specify the same value for all spatial 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. output_padding: An integer or tuple/list of 3 integers, specifying the amount of padding along the depth, height, and width. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. 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, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, depth, height, width)`. 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: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride 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. kernel_initializer: Initializer for the `kernel` weights matrix (see `keras.initializers`). Defaults to 'glorot_uniform'. bias_initializer: Initializer for the bias vector (see `keras.initializers`). Defaults to 'zeros'. kernel_regularizer: Regularizer function applied to the `kernel` weights 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`). kernel_constraint: Constraint function applied to the kernel matrix (see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector (see `keras.constraints`). Input shape: 5D tensor with shape: `(batch_size, channels, depth, rows, cols)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, depth, rows, cols, channels)` if data_format='channels_last'. Output shape: 5D tensor with shape: `(batch_size, filters, new_depth, new_rows, new_cols)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, new_depth, new_rows, new_cols, filters)` if data_format='channels_last'. `depth` and `rows` and `cols` values might have changed due to padding. If `output_padding` is specified:: ``` new_depth = ((depth - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_rows = ((rows - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) new_cols = ((cols - 1) * strides[2] + kernel_size[2] - 2 * padding[2] + output_padding[2]) ``` Returns: A tensor of rank 5 representing `activation(conv3dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". 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) """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1, 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(Conv3DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 3, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Strides must be greater than output padding. ' f'Received strides={self.strides}, ' f'output_padding={self.output_padding}.') def build(self, input_shape): input_shape = tf.TensorShape(input_shape) if len(input_shape) != 5: raise ValueError('Inputs should have rank 5. ' f'Received input_shape={input_shape}.') channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'to `Conv3DTranspose` should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') input_dim = int(input_shape[channel_axis]) kernel_shape = self.kernel_size + (self.filters, input_dim) self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) self.kernel = self.add_weight( 'kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( 'bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = tf.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': d_axis, h_axis, w_axis = 2, 3, 4 else: d_axis, h_axis, w_axis = 1, 2, 3 depth = inputs_shape[d_axis] height = inputs_shape[h_axis] width = inputs_shape[w_axis] kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding # Infer the dynamic output shape: out_depth = conv_utils.deconv_output_length(depth, kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_depth, out_height, out_width) strides = (1, 1, stride_d, stride_h, stride_w) else: output_shape = (batch_size, out_depth, out_height, out_width, self.filters) strides = (1, stride_d, stride_h, stride_w, 1) output_shape_tensor = tf.stack(output_shape) outputs = tf.nn.conv3d_transpose( inputs, self.kernel, output_shape_tensor, strides, data_format=conv_utils.convert_data_format(self.data_format, ndim=5), padding=self.padding.upper()) if not tf.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4 else: c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3 kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[d_axis] = conv_utils.deconv_output_length( output_shape[d_axis], kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) return tf.TensorShape(output_shape) def get_config(self): config = super(Conv3DTranspose, self).get_config() config.pop('dilation_rate') config['output_padding'] = self.output_padding return config class SeparableConv(Conv): """Abstract base layer for separable nD convolution. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output. Args: rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: A tuple or list of integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. strides: A tuple or list of integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial 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. 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, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, ...)`. dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. 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 `num_filters_in * depth_multiplier`. 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. depthwise_initializer: An initializer for the depthwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. pointwise_initializer: An initializer for the pointwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. bias_initializer: An initializer for the bias vector. If None, the default initializer ('zeros') will be used (see `keras.initializers`). depthwise_regularizer: Optional regularizer for the depthwise convolution kernel. pointwise_regularizer: Optional regularizer for the pointwise convolution kernel. bias_regularizer: Optional regularizer for the bias vector. activity_regularizer: Optional regularizer function for the output. depthwise_constraint: Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for 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. pointwise_constraint: Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer`. trainable: Boolean, if `True` the weights of this layer will be marked as trainable (and listed in `layer.trainable_weights`). """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): super(SeparableConv, self).__init__( rank=rank, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, bias_initializer=initializers.get(bias_initializer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), bias_constraint=bias_constraint, trainable=trainable, name=name, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.pointwise_initializer = initializers.get(pointwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.pointwise_regularizer = regularizers.get(pointwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.pointwise_constraint = constraints.get(pointwise_constraint) def build(self, input_shape): input_shape = tf.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) depthwise_kernel_shape = self.kernel_size + (input_dim, self.depth_multiplier) pointwise_kernel_shape = ( 1,) * self.rank + (self.depth_multiplier * input_dim, self.filters) self.depthwise_kernel = self.add_weight( name='depthwise_kernel', shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint, trainable=True, dtype=self.dtype) self.pointwise_kernel = self.add_weight( name='pointwise_kernel', shape=pointwise_kernel_shape, initializer=self.pointwise_initializer, regularizer=self.pointwise_regularizer, constraint=self.pointwise_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): raise NotImplementedError def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'depth_multiplier': self.depth_multiplier, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'depthwise_initializer': initializers.serialize(self.depthwise_initializer), 'pointwise_initializer': initializers.serialize(self.pointwise_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'depthwise_regularizer': regularizers.serialize(self.depthwise_regularizer), 'pointwise_regularizer': regularizers.serialize(self.pointwise_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'depthwise_constraint': constraints.serialize(self.depthwise_constraint), 'pointwise_constraint': constraints.serialize(self.pointwise_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(SeparableConv, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.SeparableConv1D', 'keras.layers.SeparableConvolution1D') class SeparableConv1D(SeparableConv): """Depthwise separable 1D convolution. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output. Args: filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: A single integer specifying the spatial dimensions of the filters. strides: A single integer specifying the strides of the convolution. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"same"`, or `"causal"` (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. `"causal"` results in causal (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. 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, length, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, length)`. dilation_rate: A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. 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 `num_filters_in * depth_multiplier`. 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. depthwise_initializer: An initializer for the depthwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. pointwise_initializer: An initializer for the pointwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. bias_initializer: An initializer for the bias vector. If None, the default initializer ('zeros') will be used (see `keras.initializers`). depthwise_regularizer: Optional regularizer for the depthwise convolution kernel (see `keras.regularizers`). pointwise_regularizer: Optional regularizer for the pointwise convolution kernel (see `keras.regularizers`). bias_regularizer: Optional regularizer for the bias vector (see `keras.regularizers`). activity_regularizer: Optional regularizer function for the output (see `keras.regularizers`). depthwise_constraint: Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for 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 (see `keras.constraints`). pointwise_constraint: Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer` (see `keras.constraints`). bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer` (see `keras.constraints`). trainable: Boolean, if `True` the weights of this layer will be marked as trainable (and listed in `layer.trainable_weights`). Input shape: 3D tensor with shape: `(batch_size, channels, steps)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, steps, channels)` if data_format='channels_last'. Output shape: 3D tensor with shape: `(batch_size, filters, new_steps)` if data_format='channels_first' or 3D tensor with shape: `(batch_size, new_steps, filters)` if data_format='channels_last'. `new_steps` value might have changed due to padding or strides. Returns: A tensor of rank 3 representing `activation(separableconv1d(inputs, kernel) + bias)`. Raises: ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): if self.padding == 'causal': inputs = tf.pad(inputs, self._compute_causal_padding(inputs)) if self.data_format == 'channels_last': strides = (1,) + self.strides * 2 + (1,) spatial_start_dim = 1 else: strides = (1, 1) + self.strides * 2 spatial_start_dim = 2 # Explicitly broadcast inputs and kernels to 4D. # TODO(fchollet): refactor when a native separable_conv1d op is available. inputs = tf.expand_dims(inputs, spatial_start_dim) depthwise_kernel = tf.expand_dims(self.depthwise_kernel, 0) pointwise_kernel = tf.expand_dims(self.pointwise_kernel, 0) dilation_rate = (1,) + self.dilation_rate if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding outputs = tf.compat.v1.nn.separable_conv2d( inputs, depthwise_kernel, pointwise_kernel, strides=strides, padding=op_padding.upper(), rate=dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) outputs = tf.squeeze(outputs, [spatial_start_dim]) if self.activation is not None: return self.activation(outputs) return outputs @keras_export('keras.layers.SeparableConv2D', 'keras.layers.SeparableConvolution2D') class SeparableConv2D(SeparableConv): """Depthwise separable 2D convolution. Separable convolutions consist of first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. 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 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 the 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. 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)`. 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: 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. 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`. 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: An initializer for the depthwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. pointwise_initializer: An initializer for the pointwise convolution kernel (see `keras.initializers`). If None, then the default initializer ('glorot_uniform') will be used. bias_initializer: An initializer for the bias vector. If None, the default initializer ('zeros') will be used (see `keras.initializers`). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see `keras.regularizers`). pointwise_regularizer: Regularizer function applied to the pointwise 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`). pointwise_constraint: Constraint function applied to the pointwise 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, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4 representing `activation(separableconv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): # Apply the actual ops. if self.data_format == 'channels_last': strides = (1,) + self.strides + (1,) else: strides = (1, 1) + self.strides outputs = tf.compat.v1.nn.separable_conv2d( inputs, self.depthwise_kernel, self.pointwise_kernel, strides=strides, padding=self.padding.upper(), rate=self.dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs class DepthwiseConv(Conv): """Depthwise 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 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: A tuple or list of integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. strides: A tuple or list of integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial 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)`. 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: 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, rank, kernel_size, strides=1, padding='valid', depth_multiplier=1, data_format=None, dilation_rate=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(DepthwiseConv, self).__init__( rank, filters=None, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, bias_constraint=bias_constraint, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.bias_initializer = initializers.get(bias_initializer) def build(self, input_shape): if len(input_shape) != self.rank + 2: raise ValueError('Inputs to `DepthwiseConv` should have ' f'rank {self.rank + 2}. ' f'Received input_shape={input_shape}.') input_shape = tf.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs to `DepthwiseConv` ' 'should be defined. ' f'The input_shape received is {input_shape}, ' f'where axis {channel_axis} (0-based) ' 'is the channel dimension, which found to be `None`.') input_dim = int(input_shape[channel_axis]) depthwise_kernel_shape = self.kernel_size + (input_dim, self.depth_multiplier) self.depthwise_kernel = self.add_weight( shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, name='depthwise_kernel', regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint) if self.use_bias: self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec( min_ndim=self.rank + 2, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): raise NotImplementedError def get_config(self): config = super(DepthwiseConv, self).get_config() config.pop('filters') config.pop('kernel_initializer') config.pop('kernel_regularizer') config.pop('kernel_constraint') config['depth_multiplier'] = self.depth_multiplier config['depthwise_initializer'] = initializers.serialize( self.depthwise_initializer) config['depthwise_regularizer'] = regularizers.serialize( self.depthwise_regularizer) config['depthwise_constraint'] = constraints.serialize( self.depthwise_constraint) return config @keras_export('keras.layers.DepthwiseConv1D') class DepthwiseConv1D(DepthwiseConv): """Depthwise 1D 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 1D 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, specifying the height and width of the 1D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer, 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. 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)`. 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: A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride 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, padding='valid', depth_multiplier=1, data_format=None, dilation_rate=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(DepthwiseConv1D, self).__init__( 1, 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): if self.data_format == 'channels_last': strides = (1,) + self.strides * 2 + (1,) spatial_start_dim = 1 else: strides = (1, 1) + self.strides * 2 spatial_start_dim = 2 inputs = tf.expand_dims(inputs, spatial_start_dim) depthwise_kernel = tf.expand_dims(self.depthwise_kernel, axis=0) dilation_rate = (1,) + self.dilation_rate outputs = tf.nn.depthwise_conv2d( inputs, depthwise_kernel, strides=strides, padding=self.padding.upper(), dilations=dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = tf.nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) outputs = tf.squeeze(outputs, [spatial_start_dim]) 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] out_filters = input_shape[1] * self.depth_multiplier elif self.data_format == 'channels_last': rows = input_shape[1] out_filters = input_shape[2] * self.depth_multiplier rows = conv_utils.conv_output_length(rows, self.kernel_size[0], self.padding, self.strides[0], self.dilation_rate[0]) if self.data_format == 'channels_first': return (input_shape[0], out_filters, rows) elif self.data_format == 'channels_last': return (input_shape[0], rows, out_filters) @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. 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)`. 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: 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(DepthwiseConv2D, self).__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) @keras_export('keras.layers.UpSampling1D') class UpSampling1D(Layer): """Upsampling layer for 1D inputs. Repeats each temporal step `size` times along the time axis. Examples: >>> input_shape = (2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] >>> y = tf.keras.layers.UpSampling1D(size=2)(x) >>> print(y) tf.Tensor( [[[ 0 1 2] [ 0 1 2] [ 3 4 5] [ 3 4 5]] [[ 6 7 8] [ 6 7 8] [ 9 10 11] [ 9 10 11]]], shape=(2, 4, 3), dtype=int64) Args: size: Integer. Upsampling factor. Input shape: 3D tensor with shape: `(batch_size, steps, features)`. Output shape: 3D tensor with shape: `(batch_size, upsampled_steps, features)`. """ def __init__(self, size=2, **kwargs): super(UpSampling1D, self).__init__(**kwargs) self.size = int(size) self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() size = self.size * input_shape[1] if input_shape[1] is not None else None return tf.TensorShape([input_shape[0], size, input_shape[2]]) def call(self, inputs): output = backend.repeat_elements(inputs, self.size, axis=1) return output def get_config(self): config = {'size': self.size} base_config = super(UpSampling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.UpSampling2D') class UpSampling2D(Layer): """Upsampling layer for 2D inputs. Repeats the rows and columns of the data by `size[0]` and `size[1]` respectively. Examples: >>> input_shape = (2, 2, 1, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[[ 0 1 2]] [[ 3 4 5]]] [[[ 6 7 8]] [[ 9 10 11]]]] >>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x) >>> print(y) tf.Tensor( [[[[ 0 1 2] [ 0 1 2]] [[ 3 4 5] [ 3 4 5]]] [[[ 6 7 8] [ 6 7 8]] [[ 9 10 11] [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64) Args: size: Int, or tuple of 2 integers. The upsampling factors for rows and columns. 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)`. 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". interpolation: A string, one of `nearest` or `bilinear`. Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, upsampled_rows, upsampled_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, upsampled_rows, upsampled_cols)` """ def __init__(self, size=(2, 2), data_format=None, interpolation='nearest', **kwargs): super(UpSampling2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 2, 'size') if interpolation not in {'nearest', 'bilinear'}: raise ValueError('`interpolation` argument should be one of `"nearest"` ' f'or `"bilinear"`. Received: "{interpolation}".') self.interpolation = interpolation self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': height = self.size[0] * input_shape[ 2] if input_shape[2] is not None else None width = self.size[1] * input_shape[ 3] if input_shape[3] is not None else None return tf.TensorShape( [input_shape[0], input_shape[1], height, width]) else: height = self.size[0] * input_shape[ 1] if input_shape[1] is not None else None width = self.size[1] * input_shape[ 2] if input_shape[2] is not None else None return tf.TensorShape( [input_shape[0], height, width, input_shape[3]]) def call(self, inputs): return backend.resize_images( inputs, self.size[0], self.size[1], self.data_format, interpolation=self.interpolation) def get_config(self): config = { 'size': self.size, 'data_format': self.data_format, 'interpolation': self.interpolation } base_config = super(UpSampling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @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)`. 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". 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(UpSampling3D, self).__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(UpSampling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding1D') class ZeroPadding1D(Layer): """Zero-padding layer for 1D input (e.g. temporal sequence). Examples: >>> input_shape = (2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] >>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x) >>> print(y) tf.Tensor( [[[ 0 0 0] [ 0 0 0] [ 0 1 2] [ 3 4 5] [ 0 0 0] [ 0 0 0]] [[ 0 0 0] [ 0 0 0] [ 6 7 8] [ 9 10 11] [ 0 0 0] [ 0 0 0]]], shape=(2, 6, 3), dtype=int64) Args: padding: Int, or tuple of int (length 2), or dictionary. - If int: How many zeros to add at the beginning and end of the padding dimension (axis 1). - If tuple of int (length 2): How many zeros to add at the beginning and the end of the padding dimension (`(left_pad, right_pad)`). Input shape: 3D tensor with shape `(batch_size, axis_to_pad, features)` Output shape: 3D tensor with shape `(batch_size, padded_axis, features)` """ def __init__(self, padding=1, **kwargs): super(ZeroPadding1D, self).__init__(**kwargs) self.padding = conv_utils.normalize_tuple(padding, 2, 'padding') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): if input_shape[1] is not None: length = input_shape[1] + self.padding[0] + self.padding[1] else: length = None return tf.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): return backend.temporal_padding(inputs, padding=self.padding) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding2D') class ZeroPadding2D(Layer): """Zero-padding layer for 2D input (e.g. picture). This layer can add rows and columns of zeros at the top, bottom, left and right side of an image tensor. Examples: >>> input_shape = (1, 1, 2, 2) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[[0 1] [2 3]]]] >>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x) >>> print(y) tf.Tensor( [[[[0 0] [0 0] [0 0] [0 0]] [[0 0] [0 1] [2 3] [0 0]] [[0 0] [0 0] [0 0] [0 0]]]], shape=(1, 3, 4, 2), dtype=int64) Args: padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_height_pad, symmetric_width_pad)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_pad, bottom_pad), (left_pad, right_pad))` 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)`. 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". Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, padded_rows, padded_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, padded_rows, padded_cols)` """ def __init__(self, padding=(1, 1), data_format=None, **kwargs): super(ZeroPadding2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 2: raise ValueError('`padding` should have two elements. ' f'Received: {padding}.') height_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') width_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') self.padding = (height_padding, width_padding) else: raise ValueError('`padding` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_pad, symmetric_width_pad), ' 'or a tuple of 2 tuples of 2 ints ' '((top_pad, bottom_pad), (left_pad, right_pad)). ' f'Received: {padding}.') self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: rows = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[3] is not None: cols = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: cols = None return tf.TensorShape( [input_shape[0], input_shape[1], rows, cols]) elif self.data_format == 'channels_last': if input_shape[1] is not None: rows = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[2] is not None: cols = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: cols = None return tf.TensorShape( [input_shape[0], rows, cols, input_shape[3]]) def call(self, inputs): return backend.spatial_2d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding3D') class ZeroPadding3D(Layer): """Zero-padding layer for 3D data (spatial or spatio-temporal). Examples: >>> input_shape = (1, 1, 2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x) >>> print(y.shape) (1, 5, 6, 6, 3) Args: padding: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 3 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_pad, right_dim1_pad), (left_dim2_pad, right_dim2_pad), (left_dim3_pad, right_dim3_pad))` 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)`. 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". Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_padded_axis, second_padded_axis, third_axis_to_pad)` """ def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): super(ZeroPadding3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 3: raise ValueError('`padding` should have 3 elements. ' f'Received: {padding}.') dim1_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') dim2_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') dim3_padding = conv_utils.normalize_tuple(padding[2], 2, '3rd entry of padding') self.padding = (dim1_padding, dim2_padding, dim3_padding) else: raise ValueError( '`padding` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_pad, right_dim1_pad),' ' (left_dim2_pad, right_dim2_pad),' ' (left_dim3_pad, right_dim2_pad)). ' f'Received: {padding}.') self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] + self.padding[2][0] + self.padding[2][1] else: dim3 = None return tf.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] + self.padding[2][0] + self.padding[2][1] else: dim3 = None return tf.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): return backend.spatial_3d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping1D') class Cropping1D(Layer): """Cropping layer for 1D input (e.g. temporal sequence). It crops along the time dimension (axis 1). Examples: >>> input_shape = (2, 3, 2) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1] [ 2 3] [ 4 5]] [[ 6 7] [ 8 9] [10 11]]] >>> y = tf.keras.layers.Cropping1D(cropping=1)(x) >>> print(y) tf.Tensor( [[[2 3]] [[8 9]]], shape=(2, 1, 2), dtype=int64) Args: cropping: Int or tuple of int (length 2) How many units should be trimmed off at the beginning and end of the cropping dimension (axis 1). If a single int is provided, the same value will be used for both. Input shape: 3D tensor with shape `(batch_size, axis_to_crop, features)` Output shape: 3D tensor with shape `(batch_size, cropped_axis, features)` """ def __init__(self, cropping=(1, 1), **kwargs): super(Cropping1D, self).__init__(**kwargs) self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() if input_shape[1] is not None: length = input_shape[1] - self.cropping[0] - self.cropping[1] else: length = None return tf.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): if self.cropping[1] == 0: return inputs[:, self.cropping[0]:, :] else: return inputs[:, self.cropping[0]:-self.cropping[1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping2D') class Cropping2D(Layer): """Cropping layer for 2D input (e.g. picture). It crops along spatial dimensions, i.e. height and width. Examples: >>> input_shape = (2, 28, 28, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x) >>> print(y.shape) (2, 24, 20, 3) Args: cropping: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric cropping is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric cropping values for height and width: `(symmetric_height_crop, symmetric_width_crop)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_crop, bottom_crop), (left_crop, right_crop))` 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)`. 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". Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, cropped_rows, cropped_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, cropped_rows, cropped_cols)` """ def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): super(Cropping2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 2: raise ValueError('`cropping` should have two elements. ' f'Received: {cropping}.') height_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') width_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') self.cropping = (height_cropping, width_cropping) else: raise ValueError('`cropping` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_crop, symmetric_width_crop), ' 'or a tuple of 2 tuples of 2 ints ' '((top_crop, bottom_crop), (left_crop, right_crop)). ' f'Received: {cropping}.') self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': return tf.TensorShape([ input_shape[0], input_shape[1], input_shape[2] - self.cropping[0][0] - self.cropping[0][1] if input_shape[2] else None, input_shape[3] - self.cropping[1][0] - self.cropping[1][1] if input_shape[3] else None ]) else: return tf.TensorShape([ input_shape[0], input_shape[1] - self.cropping[0][0] - self.cropping[0][1] if input_shape[1] else None, input_shape[2] - self.cropping[1][0] - self.cropping[1][1] if input_shape[2] else None, input_shape[3] ]) # pylint: enable=invalid-unary-operand-type def call(self, inputs): # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1]] else: if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], :] # pylint: disable=invalid-unary-operand-type # pylint: enable=invalid-unary-operand-type def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping3D') class Cropping3D(Layer): """Cropping layer for 3D data (e.g. spatial or spatio-temporal). Examples: >>> input_shape = (2, 28, 28, 10, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x) >>> print(y.shape) (2, 24, 20, 6, 3) Args: cropping: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric cropping is applied to depth, height, and width. - If tuple of 3 ints: interpreted as two different symmetric cropping values for depth, height, and width: `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_crop, right_dim1_crop), (left_dim2_crop, right_dim2_crop), (left_dim3_crop, right_dim3_crop))` 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)`. 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". Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_cropped_axis, second_cropped_axis, third_cropped_axis)` """ def __init__(self, cropping=((1, 1), (1, 1), (1, 1)), data_format=None, **kwargs): super(Cropping3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 3: raise ValueError('`cropping` should have 3 elements. ' f'Received: {cropping}.') dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2, '3rd entry of cropping') self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping) else: raise ValueError( '`cropping` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_crop, right_dim1_crop),' ' (left_dim2_crop, right_dim2_crop),' ' (left_dim3_crop, right_dim2_crop)). ' f'Received: {cropping}.') self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tf.TensorShape(input_shape).as_list() # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tf.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tf.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) # pylint: enable=invalid-unary-operand-type def call(self, inputs): # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][ 0]:-self.cropping[2][1]] else: if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1], :] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][ 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[ 2][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], self.cropping[2][0]: # pylint: disable=invalid-unary-operand-type -self.cropping[2][1], :] # pylint: disable=invalid-unary-operand-type # pylint: enable=invalid-unary-operand-type def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Aliases Convolution1D = Conv1D Convolution2D = Conv2D Convolution3D = Conv3D SeparableConvolution1D = SeparableConv1D SeparableConvolution2D = SeparableConv2D Convolution2DTranspose = Conv2DTranspose Convolution3DTranspose = Conv3DTranspose Deconvolution2D = Deconv2D = Conv2DTranspose Deconvolution3D = Deconv3D = Conv3DTranspose
155,211
40.467272
104
py
keras
keras-master/keras/layers/tensorflow_op_layer_test.py
# 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. # ============================================================================== """Test for allowing TF ops to work with Keras Functional API.""" import tensorflow.compat.v2 as tf import time from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import testing_utils from keras.engine import keras_tensor from keras.optimizer_v2 import adam from keras.saving import model_config def _single_op_at_end(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) outputs = tf.nn.relu(x) return keras.Model(inputs, outputs) def _single_identity_op_at_end(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) outputs = tf.identity(x) return keras.Model(inputs, outputs) def _multiple_ops_at_end(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) x = tf.nn.relu(x) outputs = tf.nn.relu(x) return keras.Model(inputs, outputs) def _single_op_in_middle(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) x = tf.nn.relu(x) outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _multiple_ops_in_middle(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) x = tf.nn.relu(x) x = tf.nn.relu(x) outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _shape_op_inference(): inputs = keras.Input(shape=(10,)) x = tf.shape(inputs) x = tf.ones(x) assert x.shape.as_list() == [None, 10] outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _shape_op_known_batch_size(): inputs = keras.Input(batch_size=2, shape=(10,)) x = tf.shape(inputs) x = tf.ones(x) assert x.shape.as_list() == [2, 10] outputs = keras.layers.Dense(10)(x) if tf.executing_eagerly(): return keras.Model(inputs, outputs) else: # In V1 the op layer fails for some reason, # but we don't have access to the test case to call # self.skip_test in this util method return keras.Model(inputs, inputs) def _shape_op_slice_and_range(): inputs = keras.Input(shape=(10,)) batch_size = tf.shape(inputs)[0] x = tf.range(batch_size * 2) assert x.shape.as_list() == [None] x = tf.reshape(x, (batch_size, 2)) x = tf.cast(x, dtype='float32') outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _shape_op_slice_and_range_known_dim(): inputs = keras.Input(batch_size=2, shape=(10,)) batch_size = tf.shape(inputs)[0] x = tf.range(batch_size * 3) assert x.shape.as_list() == [6] x = tf.reshape(x, (batch_size, 3)) x = tf.cast(x, dtype='float32') outputs = keras.layers.Dense(10)(x) if tf.executing_eagerly(): return keras.Model(inputs, outputs) else: # In V1 the op layer fails for some reason, # but we don't have access to the test case to call # self.skip_test in this util method return keras.Model(inputs, inputs) def _int32_manipulation_too_big_for_shape(): # This test verifies that the Keras Functional API # won't crash when manipulating int32 tensors that are too large # to represent shapes. inputs = keras.Input(batch_size=2, shape=(10,)) batch_size = tf.shape(inputs)[0] num_features = 3 * 1024 * 16 x = tf.range(batch_size * num_features, dtype='int32') assert x.shape.as_list() == [inputs.shape[0] * num_features] x = tf.reshape(x, (batch_size, num_features)) x = tf.cast(x, dtype='float32') outputs = keras.layers.Dense(10)(x) if tf.executing_eagerly(): return keras.Model(inputs, outputs) else: # In V1 the op layer fails for some reason, # but we don't have access to the test case to call # self.skip_test in this util method return keras.Model(inputs, inputs) def _int32_manipulation_at_max_shape_dims_limit(): # This test verifies that the Keras Functional API # won't crash when manipulating int32 tensors that are at the limit # of the max tensor size Keras can try inferring values for. inputs = keras.Input(batch_size=2, shape=(10,)) batch_size = tf.shape(inputs)[0] num_features = int(keras_tensor._MAX_TENSOR_RANK / int(inputs.shape[0])) x = tf.range(batch_size * num_features, dtype='int32') assert x.shape.as_list() == [keras_tensor._MAX_TENSOR_RANK] # Verify that a value was actually inferred for a tensor that *might* # represent the shape, bying checking that a value in # the range appears in the printed inferred value if tf.compat.v1.executing_eagerly_outside_functions(): assert str(keras_tensor._MAX_TENSOR_RANK - 1) in str(x) x = tf.reshape(x, (batch_size, num_features)) x = tf.cast(x, dtype='float32') outputs = keras.layers.Dense(10)(x) if tf.executing_eagerly(): return keras.Model(inputs, outputs) else: # In V1 the op layer fails for some reason, # but we don't have access to the test case to call # self.skip_test in this util method return keras.Model(inputs, inputs) def _single_standalone_branch(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10)(inputs) outputs = x * 2 return keras.Model(inputs, outputs) def _single_op_with_attrs(): inputs = keras.Input(shape=(10,)) x = tf.reduce_mean(inputs, axis=1, keepdims=True) outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _multiple_uses(): inputs = keras.Input(shape=(10,)) x = tf.reduce_mean(inputs, axis=1, keepdims=True) x1 = keras.layers.Dense(10)(x) x2 = keras.layers.Dense(10)(x) outputs = x1 + x2 return keras.Model(inputs, outputs) def _op_with_tensor_list(): inputs = keras.Input(shape=(10,)) x = tf.concat([inputs, inputs], axis=1) outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) def _add_n(): inputs = keras.Input(shape=(10,)) outputs = tf.add_n([inputs, inputs, inputs]) return keras.Model(inputs, outputs) def _reuse_op(): inputs = keras.Input(shape=(10,)) # This op needs to be checked multiple times. x = tf.nn.relu(inputs) y = keras.layers.Dense(10)(x) x2 = x * 2 y2 = keras.layers.Dense(10)(x2) outputs = y + y2 return keras.Model(inputs, outputs) def _float64_op(): inputs = keras.Input(shape=(10,)) x = keras.layers.Dense(10, dtype='float64')(inputs) x = tf.nn.relu(x) assert x.dtype == 'float64', 'x has dtype: %s' % x.dtype outputs = keras.layers.Dense(10)(x) return keras.Model(inputs, outputs) class MyAdd(keras.layers.Layer): def call(self, x, y): return x + y def _layer_with_tensor_arg(): inputs = keras.Input(shape=(10,)) x = inputs * 2 outputs = MyAdd()(inputs, x) return keras.Model(inputs, outputs) class LayerWithLayer(keras.layers.Layer): def build(self, input_shape): self.bias = self.add_weight(name='bias', dtype='float32') self.layer = keras.layers.Dense(10) def call(self, inputs): inputs = inputs * self.bias # Would throw an error if Keras History was created here. return self.layer(inputs) def _inner_layer(): inputs = keras.Input(shape=(10,)) outputs = LayerWithLayer()(inputs) return keras.Model(inputs, outputs) def _reuse_ancillary_layer(): inputs = (keras.Input(shape=(5,)), keras.Input(shape=(5,))) base_model = keras.Sequential([ keras.layers.Dense(3, input_shape=(5,)), ]) outputs = base_model(inputs[0]) model = keras.Model(inputs, outputs) # The second input is only involved in ancillary layers. outputs_delta = outputs - base_model(0.5 * inputs[1]) l2_loss = tf.reduce_mean( tf.reduce_sum(tf.square(outputs_delta), -1)) model.add_loss(l2_loss) model.add_metric(l2_loss, aggregation='mean', name='l2_loss') l1_loss = 0.01 * tf.reduce_mean( tf.reduce_sum(tf.abs(outputs_delta), -1)) model.add_loss(l1_loss) model.add_metric(l1_loss, aggregation='mean', name='l1_loss') return model @keras_parameterized.run_all_keras_modes() class AutoLambdaTest(keras_parameterized.TestCase): @parameterized.named_parameters( ('single_op_at_end', _single_op_at_end), ('single_identity_op_at_end', _single_identity_op_at_end), ('multiple_ops_at_end', _multiple_ops_at_end), ('single_op_in_middle', _single_op_in_middle), ('multiple_ops_in_middle', _multiple_ops_in_middle), ('shape_op_inference', _shape_op_inference), ('shape_op_known_batch_size', _shape_op_known_batch_size), ('shape_op_slice_and_range', _shape_op_slice_and_range), ('shape_op_slice_and_range_known_dim', _shape_op_slice_and_range_known_dim), ('int32_manipulation_too_big_for_shape', _int32_manipulation_too_big_for_shape), ('int32_manipulation_at_max_shape_dims_limit', _int32_manipulation_at_max_shape_dims_limit), ('single_standalone_branch', _single_standalone_branch), ('single_op_with_attrs', _single_op_with_attrs), ('multiple_uses', _multiple_uses), ('op_with_tensor_list', _op_with_tensor_list), ('add_n', _add_n), ('_reuse_op', _reuse_op), ('_float64_op', _float64_op), ('_inner_layer', _inner_layer), ('_reuse_ancillary_layer', _reuse_ancillary_layer), ('_layer_with_tensor_arg', _layer_with_tensor_arg), ) def test_autolambda(self, model_fn): model = model_fn() model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) np_inputs = tf.nest.map_structure( lambda x: np.ones((2,) + tuple(x.shape[1:]), 'float32'), model.inputs) np_outputs = tf.nest.map_structure( lambda x: np.ones((2,) + tuple(x.shape[1:]), 'float32'), model.outputs) model.fit(np_inputs, np_outputs, batch_size=2) model(np_inputs) # Test calling the model directly on inputs. new_model = keras.Model.from_config( model.get_config(), custom_objects={ 'LayerWithLayer': LayerWithLayer, 'MyAdd': MyAdd }) new_model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) new_model.fit(np_inputs, np_outputs, batch_size=2) new_model(np_inputs) # Test calling the new model directly on inputs. # Assert that metrics are preserved and in the right order. self.assertAllEqual(model.metrics_names, new_model.metrics_names) # Assert that layer names don't change. self.assertAllEqual([layer.name for layer in model.layers], [layer.name for layer in new_model.layers]) def test_stack_preserves_correct_shape(self): ## Test stack([x]) inp = keras.Input(shape=(), dtype='float32') out = tf.stack([inp]) model = keras.Model( inputs=inp, outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) x = tf.ones(shape=(4, 4)) expected = tf.stack([x]) self.assertAllEqual(expected.shape, (1, 4, 4)) self.assertAllEqual(model(x).shape, (1, 4, 4)) self.assertAllEqual(model(x), expected) config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(x).shape, (1, 4, 4)) self.assertAllEqual(model(x), expected) ## Test stack(x) inp = keras.Input(shape=(), dtype='float32') out = tf.stack(inp) model = keras.Model( inputs=inp, outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) x = tf.ones(shape=(4, 4)) expected = tf.stack(x) self.assertAllEqual(expected.shape, (4, 4)) self.assertAllEqual(model(x).shape, (4, 4)) self.assertAllEqual(model(x), expected) config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(x).shape, (4, 4)) self.assertAllEqual(model(x), expected) def test_getitem_slice_with_step_only(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') inp = keras.Input(shape=(8,)) slice_step = keras.Input(shape=(), dtype='int32') out = inp[..., ::slice_step[0]] model = keras.Model( inputs=[inp, slice_step], outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 step = 3 x = tf.stack([ tf.range(8) for _ in range(batch_size)]) args = [x, tf.constant(step, shape=(batch_size,))] expected = tf.stack([ tf.range(8)[::step] for _ in range(batch_size)]) if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) self.assertNotIn('tf.strided_slice', ( x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_getitem_slice_real_tensor(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') x = tf.range(10.0) slice_stop = keras.Input(shape=(), dtype='int32') out = x[:slice_stop[0]] model = keras.Model( inputs=slice_stop, outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 stop = 6 args = tf.constant(stop, shape=(batch_size,)) expected = x[:stop] if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) # TODO(b/161925288): Fix the dispatch triggering then uncomment: # self.assertNotIn('tf.strided_slice', ( # x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_getitem_index_real_tensor(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') x = tf.range(10.0) slice_stop = keras.Input(shape=(), dtype='int32') out = x[slice_stop[0]] model = keras.Model( inputs=slice_stop, outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 index = 6 args = tf.constant(index, shape=(batch_size,)) expected = x[index] if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) # TODO(b/161925288): Fix the bug then uncomment: # self.assertNotIn('tf.strided_slice', ( # x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_getitem_slice_with_stop_only(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') inp = keras.Input(shape=(8,)) slice_stop = keras.Input(shape=(), dtype='int32') out = inp[:slice_stop[0]] model = keras.Model( inputs=[inp, slice_stop], outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 stop = 6 x = tf.stack([ tf.range(8) for _ in range(batch_size)]) args = [x, tf.constant(stop, shape=(batch_size,))] expected = x[:stop] if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) self.assertNotIn('tf.strided_slice', ( x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_getitem_slice_with_stop_and_ellipsis_only(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') inp = keras.Input(shape=(8,)) slice_stop = keras.Input(shape=(), dtype='int32') out = inp[..., :slice_stop[0]] model = keras.Model( inputs=[inp, slice_stop], outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 stop = 6 x = tf.stack([ tf.range(8) for _ in range(batch_size)]) args = [x, tf.constant(stop, shape=(batch_size,))] expected = tf.stack([ tf.range(8)[:stop] for _ in range(batch_size)]) if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) self.assertNotIn('tf.strided_slice', ( x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_getitem_complex_slicing(self): if not tf.executing_eagerly(): self.skipTest('Complex slicing like this fails in v1') inp = keras.Input(shape=(4, 3, 8)) first_dim = keras.Input(shape=(), dtype='int32') slice_start = keras.Input(shape=(), dtype='int32') slice_stop = keras.Input(shape=(), dtype='int32') slice_stride = keras.Input(shape=(), dtype='int32') out = inp[..., first_dim[0], slice_start[0]:slice_stop[0]:slice_stride[0]] model = keras.Model( inputs=[inp, first_dim, slice_start, slice_stop, slice_stride], outputs=out) model.compile( adam.Adam(0.001), 'mse', run_eagerly=testing_utils.should_run_eagerly()) batch_size = 7 start = 1 stop = 6 step = 2 x = tf.stack([tf.stack([tf.stack([ tf.range(8) for _ in range(3)]) for _ in range(4)]) for _ in range(batch_size)]) args = [x, tf.constant(0, shape=(batch_size,)), tf.constant(start, shape=(batch_size,)), tf.constant(stop, shape=(batch_size,)), tf.constant(step, shape=(batch_size,))] # Slice the innermost dim. only grab one index from the second-to-innermost # dim, removing that dim from the shape. expected = tf.stack([tf.stack([ tf.range(8)[start:stop:step] for _ in range(4)]) for _ in range(batch_size)]) if tf.compat.v1.executing_eagerly_outside_functions(): self.assertIn('tf.__operators__.getitem', ( x.name for x in model.layers)) self.assertNotIn('tf.strided_slice', ( x.name for x in model.layers)) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) # Make sure it can be successfully saved and loaded config = model.get_config() model = keras.Model.from_config(config) self.assertAllEqual(model(args), expected) self.assertAllEqual(model.predict(args, batch_size=batch_size), expected) def test_left_hand_numpy_multiplication(self): x = np.asarray([3.0]) inputs = keras.Input(shape=(4,)) outputs = x * inputs model = keras.Model(inputs, outputs) ones = tf.ones((5, 4), dtype='float32') self.assertAllEqual(model(ones), 3.0 * ones) def test_numerical_correctness_simple(self): x = tf.convert_to_tensor([[-1., 0., -2., 1.]]) inputs = keras.Input(shape=(4,)) outputs = tf.nn.relu(inputs) model = keras.Model(inputs, outputs) y = self.evaluate(model(x)) self.assertAllClose(y, [[0., 0., 0., 1.]]) def test_numerical_correctness_with_attrs(self): x = tf.convert_to_tensor([[1.5, 1.5], [2.5, 3.5]]) inputs = keras.Input(shape=(2,)) outputs = tf.reduce_mean(inputs, axis=1) model = keras.Model(inputs, outputs) y = self.evaluate(model(x)) self.assertAllClose(y, [1.5, 3.]) def test_numerical_correctness_serialization(self): x = tf.convert_to_tensor([[-1., 0., -2., 1.]]) inputs = keras.Input(shape=(4,)) outputs = tf.nn.relu(inputs) model1 = keras.Model(inputs, outputs) y1 = self.evaluate(model1(x)) model2 = keras.Model.from_config(model1.get_config()) y2 = self.evaluate(model2(x)) self.assertAllClose(y1, y2) def test_gradient_tape_in_function(self): z = keras.Input((1,)) x = tf.matmul(z, tf.constant(2.0, shape=(1, 1))) x = tf.reduce_mean(x, axis=0, keepdims=True) h = tf.nn.relu(x) m = keras.Model(z, h) @tf.function() def f(x): with tf.GradientTape() as t: t.watch(x) z = m(x ** 2) grads = t.gradient(z, x) return grads self.assertAllEqual(f(tf.constant(10.0, shape=(1, 1))), tf.constant(40.0, shape=(1, 1))) f = tf.function(f) self.assertAllEqual(f(tf.constant(10.0, shape=(1, 1))), tf.constant(40.0, shape=(1, 1))) def test_no_tracking(self): if not tf.executing_eagerly(): x = tf.constant(1.0, shape=(10, 10)) keras.layers.Dense(1)(x) self.assertTrue(x._keras_history_checked) def test_timing_scales_linearly(self): def _construct_graph_of_size(size): start = time.time() x = keras.backend.placeholder(shape=(10, 4)) for _ in range(size): x = keras.layers.Dense(4)(x) x = tf.nn.relu(x) end = time.time() return end - start size_50 = _construct_graph_of_size(50) size_500 = _construct_graph_of_size(500) # Check construction time grows approx. linearly with size. e = 3 # Fudge factor to prevent flakiness. self.assertLess(size_500, (10 * e) * size_50) def test_built(self): inputs = keras.Input(shape=(10,)) outputs = tf.nn.relu(inputs) model = keras.Model(inputs, outputs) model.compile('sgd', 'mse') for layer in model.layers: self.assertTrue(layer.built) # Test something that requires Layers to be built. model.summary() def test_json_serialization(self): inputs = keras.Input(shape=(4,), dtype='uint8') outputs = tf.cast(inputs, 'float32') / 4. model = model_config.model_from_json(keras.Model(inputs, outputs).to_json()) self.assertAllEqual( self.evaluate(model(np.array([0, 64, 128, 192], np.uint8))), [0., 16., 32., 48.]) model.summary() @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class InputInEagerTest(keras_parameterized.TestCase): """Tests ops on keras inputs in Eager runtime. Input returns graph/symbolic tensors in the Eager runtime (this happens, for example, with tensors returned from Keras layers). These should be routed to the graph-style branch of these ops (b/134715641) """ def test_identity(self): x = keras.Input(shape=(1,)) ident = tf.identity(x) # This is now a graph tensor, and should be able to continue in graphland self.assertIn('Identity', ident.name) def test_size(self): x = keras.Input(shape=(3,)) self.assertAllEqual(x.get_shape().as_list(), [None, 3]) sz = tf.size(x) # This is now a graph tensor, and should be able to continue in graphland self.assertIn('Size', sz.name) if __name__ == '__main__': tf.test.main()
24,923
32.232
80
py
keras
keras-master/keras/layers/rnn_cell_wrapper_v2.py
# 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. # ============================================================================== """Module implementing for RNN wrappers for TF v2.""" # Note that all the APIs under this module are exported as tf.nn.*. This is due # to the fact that those APIs were from tf.nn.rnn_cell_impl. They are ported # here to avoid the cyclic dependency issue for serialization. These APIs will # probably be deprecated and removed in future since similar API is available in # existing Keras RNN API. from keras.layers import recurrent from keras.layers.legacy_rnn import rnn_cell_wrapper_impl from keras.utils import tf_inspect from tensorflow.python.util.tf_export import tf_export class _RNNCellWrapperV2(recurrent.AbstractRNNCell): """Base class for cells wrappers V2 compatibility. This class along with `rnn_cell_impl._RNNCellWrapperV1` allows to define wrappers that are compatible with V1 and V2, and defines helper methods for this purpose. """ def __init__(self, cell, *args, **kwargs): super(_RNNCellWrapperV2, self).__init__(*args, **kwargs) self.cell = cell cell_call_spec = tf_inspect.getfullargspec(cell.call) self._expects_training_arg = ("training" in cell_call_spec.args) or ( cell_call_spec.varkw is not None ) def call(self, inputs, state, **kwargs): """Runs the RNN cell step computation. When `call` is being used, we assume that the wrapper object has been built, and therefore the wrapped cells has been built via its `build` method and its `call` method can be used directly. This allows to use the wrapped cell and the non-wrapped cell equivalently when using `call` and `build`. Args: inputs: A tensor with wrapped cell's input. state: A tensor or tuple of tensors with wrapped cell's state. **kwargs: Additional arguments passed to the wrapped cell's `call`. Returns: A pair containing: - Output: A tensor with cell's output. - New state: A tensor or tuple of tensors with new wrapped cell's state. """ return self._call_wrapped_cell( inputs, state, cell_call_fn=self.cell.call, **kwargs) def build(self, inputs_shape): """Builds the wrapped cell.""" self.cell.build(inputs_shape) self.built = True def get_config(self): config = { "cell": { "class_name": self.cell.__class__.__name__, "config": self.cell.get_config() }, } base_config = super(_RNNCellWrapperV2, self).get_config() return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config, custom_objects=None): config = config.copy() from keras.layers.serialization import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top cell = deserialize_layer(config.pop("cell"), custom_objects=custom_objects) return cls(cell, **config) @tf_export("nn.RNNCellDropoutWrapper", v1=[]) class DropoutWrapper(rnn_cell_wrapper_impl.DropoutWrapperBase, _RNNCellWrapperV2): """Operator adding dropout to inputs and outputs of the given cell.""" def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(DropoutWrapper, self).__init__(*args, **kwargs) if isinstance(self.cell, recurrent.LSTMCell): raise ValueError("keras LSTM cell does not work with DropoutWrapper. " "Please use LSTMCell(dropout=x, recurrent_dropout=y) " "instead.") __init__.__doc__ = rnn_cell_wrapper_impl.DropoutWrapperBase.__init__.__doc__ @tf_export("nn.RNNCellResidualWrapper", v1=[]) class ResidualWrapper(rnn_cell_wrapper_impl.ResidualWrapperBase, _RNNCellWrapperV2): """RNNCell wrapper that ensures cell inputs are added to the outputs.""" def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(ResidualWrapper, self).__init__(*args, **kwargs) __init__.__doc__ = rnn_cell_wrapper_impl.ResidualWrapperBase.__init__.__doc__ @tf_export("nn.RNNCellDeviceWrapper", v1=[]) class DeviceWrapper(rnn_cell_wrapper_impl.DeviceWrapperBase, _RNNCellWrapperV2): """Operator that ensures an RNNCell runs on a particular device.""" def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(DeviceWrapper, self).__init__(*args, **kwargs) __init__.__doc__ = rnn_cell_wrapper_impl.DeviceWrapperBase.__init__.__doc__
5,072
38.632813
114
py
keras
keras-master/keras/layers/multi_head_attention_test.py
# 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 the attention layer.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras.layers import multi_head_attention # This decorator runs the test in V1, V2-Eager, and V2-Functional mode. It # guarantees forward compatibility of this code for the V2 switchover. @keras_parameterized.run_all_keras_modes class MultiHeadAttentionTest(keras_parameterized.TestCase): @parameterized.named_parameters( ("key_value_same_proj", None, None, [40, 80]), ("key_value_different_proj", 32, 60, [40, 60]), ) def test_non_masked_attention(self, value_dim, output_shape, output_dims): """Test that the attention layer can be created without a mask tensor.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=12, key_dim=64, value_dim=value_dim, output_shape=output_shape) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) value = keras.Input(shape=(20, 80)) output = test_layer(query=query, value=value) self.assertEqual(output.shape.as_list(), [None] + output_dims) def test_non_masked_self_attention(self): """Test with one input (self-attenntion) and no mask tensor.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=12, key_dim=64) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) output = test_layer(query, query) self.assertEqual(output.shape.as_list(), [None, 40, 80]) def test_attention_scores(self): """Test attention outputs with coefficients.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=12, key_dim=64) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) output, coef = test_layer(query, query, return_attention_scores=True) self.assertEqual(output.shape.as_list(), [None, 40, 80]) self.assertEqual(coef.shape.as_list(), [None, 12, 40, 40]) def test_attention_scores_with_values(self): """Test attention outputs with coefficients.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=12, key_dim=64) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) value = keras.Input(shape=(60, 80)) output, coef = test_layer(query, value, return_attention_scores=True) self.assertEqual(output.shape.as_list(), [None, 40, 80]) self.assertEqual(coef.shape.as_list(), [None, 12, 40, 60]) @parameterized.named_parameters(("with_bias", True), ("no_bias", False)) def test_masked_attention(self, use_bias): """Test with a mask tensor.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=2, key_dim=2, use_bias=use_bias) # Create a 3-dimensional input (the first dimension is implicit). batch_size = 3 query = keras.Input(shape=(4, 8)) value = keras.Input(shape=(2, 8)) mask_tensor = keras.Input(shape=(4, 2)) output = test_layer(query=query, value=value, attention_mask=mask_tensor) # Create a model containing the test layer. model = keras.Model([query, value, mask_tensor], output) # Generate data for the input (non-mask) tensors. from_data = 10 * np.random.random_sample((batch_size, 4, 8)) to_data = 10 * np.random.random_sample((batch_size, 2, 8)) # Invoke the data with a random set of mask data. This should mask at least # one element. mask_data = np.random.randint(2, size=(batch_size, 4, 2)) masked_output_data = model.predict([from_data, to_data, mask_data]) # Invoke the same data, but with a null mask (where no elements are masked). null_mask_data = np.ones((batch_size, 4, 2)) unmasked_output_data = model.predict([from_data, to_data, null_mask_data]) # Because one data is masked and one is not, the outputs should not be the # same. self.assertNotAllClose(masked_output_data, unmasked_output_data) # Tests the layer with three inputs: Q, K, V. key = keras.Input(shape=(2, 8)) output = test_layer(query, value=value, key=key, attention_mask=mask_tensor) model = keras.Model([query, value, key, mask_tensor], output) masked_output_data = model.predict([from_data, to_data, to_data, mask_data]) unmasked_output_data = model.predict( [from_data, to_data, to_data, null_mask_data]) # Because one data is masked and one is not, the outputs should not be the # same. self.assertNotAllClose(masked_output_data, unmasked_output_data) if use_bias: self.assertLen(test_layer._query_dense.trainable_variables, 2) self.assertLen(test_layer._output_dense.trainable_variables, 2) else: self.assertLen(test_layer._query_dense.trainable_variables, 1) self.assertLen(test_layer._output_dense.trainable_variables, 1) def test_initializer(self): """Test with a specified initializer.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=12, key_dim=64, kernel_initializer=keras.initializers.TruncatedNormal(stddev=0.02)) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) output = test_layer(query, query) self.assertEqual(output.shape.as_list(), [None, 40, 80]) def test_masked_attention_with_scores(self): """Test with a mask tensor.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=2, key_dim=2) # Create a 3-dimensional input (the first dimension is implicit). batch_size = 3 query = keras.Input(shape=(4, 8)) value = keras.Input(shape=(2, 8)) mask_tensor = keras.Input(shape=(4, 2)) output = test_layer(query=query, value=value, attention_mask=mask_tensor) # Create a model containing the test layer. model = keras.Model([query, value, mask_tensor], output) # Generate data for the input (non-mask) tensors. from_data = 10 * np.random.random_sample((batch_size, 4, 8)) to_data = 10 * np.random.random_sample((batch_size, 2, 8)) # Invoke the data with a random set of mask data. This should mask at least # one element. mask_data = np.random.randint(2, size=(batch_size, 4, 2)) masked_output_data = model.predict([from_data, to_data, mask_data]) # Invoke the same data, but with a null mask (where no elements are masked). null_mask_data = np.ones((batch_size, 4, 2)) unmasked_output_data = model.predict([from_data, to_data, null_mask_data]) # Because one data is masked and one is not, the outputs should not be the # same. self.assertNotAllClose(masked_output_data, unmasked_output_data) # Create a model containing attention scores. output, scores = test_layer( query=query, value=value, attention_mask=mask_tensor, return_attention_scores=True) model = keras.Model([query, value, mask_tensor], [output, scores]) masked_output_data_score, masked_score = model.predict( [from_data, to_data, mask_data]) unmasked_output_data_score, unmasked_score = model.predict( [from_data, to_data, null_mask_data]) self.assertNotAllClose(masked_output_data_score, unmasked_output_data_score) self.assertAllClose(masked_output_data, masked_output_data_score) self.assertAllClose(unmasked_output_data, unmasked_output_data_score) self.assertNotAllClose(masked_score, unmasked_score) @parameterized.named_parameters( ("4d_inputs_1freebatch_mask2", [3, 4], [3, 2], [4, 2], (2,)), ("4d_inputs_1freebatch_mask3", [3, 4], [3, 2], [3, 4, 2], (2,)), ("4d_inputs_1freebatch_mask4", [3, 4], [3, 2], [3, 2, 4, 2], (2,)), ("4D_inputs_2D_attention", [3, 4], [3, 2], [3, 4, 3, 2], (1, 2)), ("5D_inputs_2D_attention", [5, 3, 4], [5, 3, 2], [3, 4, 3, 2], (2, 3)), ("5D_inputs_2D_attention_fullmask", [5, 3, 4], [5, 3, 2], [5, 3, 4, 3, 2], (2, 3))) def test_high_dim_attention(self, q_dims, v_dims, mask_dims, attention_axes): """Test with a mask tensor.""" test_layer = multi_head_attention.MultiHeadAttention( num_heads=2, key_dim=2, attention_axes=attention_axes) batch_size, hidden_size = 3, 8 # Generate data for the input (non-mask) tensors. query_shape = [batch_size] + q_dims + [hidden_size] value_shape = [batch_size] + v_dims + [hidden_size] mask_shape = [batch_size] + mask_dims query = 10 * np.random.random_sample(query_shape) value = 10 * np.random.random_sample(value_shape) # Invoke the data with a random set of mask data. This should mask at least # one element. mask_data = np.random.randint(2, size=mask_shape).astype("bool") # Invoke the same data, but with a null mask (where no elements are masked). null_mask_data = np.ones(mask_shape) # Because one data is masked and one is not, the outputs should not be the # same. query_tensor = keras.Input(query_shape[1:], name="query") value_tensor = keras.Input(value_shape[1:], name="value") mask_tensor = keras.Input(mask_shape[1:], name="mask") output = test_layer(query=query_tensor, value=value_tensor, attention_mask=mask_tensor) model = keras.Model([query_tensor, value_tensor, mask_tensor], output) self.assertNotAllClose( model.predict([query, value, mask_data]), model.predict([query, value, null_mask_data])) def test_dropout(self): test_layer = multi_head_attention.MultiHeadAttention( num_heads=2, key_dim=2, dropout=0.5) # Generate data for the input (non-mask) tensors. from_data = keras.backend.ones(shape=(32, 4, 8)) to_data = keras.backend.ones(shape=(32, 2, 8)) train_out = test_layer(from_data, to_data, None, None, None, True) test_out = test_layer(from_data, to_data, None, None, None, False) # Output should be close when not in training mode, # and should not be close when enabling dropout in training mode. self.assertNotAllClose( keras.backend.eval(train_out), keras.backend.eval(test_out)) class SubclassAttention(multi_head_attention.MultiHeadAttention): def _build_attention(self, qkv_rank): pass def _compute_attention(self, query_tensor, key_tensor, value_tensor, attention_mask=None, training=None): return value_tensor, None @keras_parameterized.run_all_keras_modes class AttentionSubclassTest(keras_parameterized.TestCase): def test_initializer(self): """Test with a specified initializer.""" test_layer = SubclassAttention(num_heads=12, key_dim=64) # Create a 3-dimensional input (the first dimension is implicit). query = keras.Input(shape=(40, 80)) output = test_layer(query, query) self.assertEqual(output.shape.as_list(), [None, 40, 80]) class TestModel(keras.Model): def __init__(self): super(TestModel, self).__init__() self.attention = multi_head_attention.MultiHeadAttention( num_heads=3, key_dim=4, value_dim=4, use_bias=True, dropout=0.0, output_shape=[12]) @classmethod def from_config(cls, config): return cls(**config) def get_config(self): return {} def call(self, x, training=False): return self.attention(x, x, training=training) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class KerasModelSavingTest(keras_parameterized.TestCase): def test_keras_saving_subclass(self): model = TestModel() query = keras.Input(shape=(40, 80)) _ = model(query) model_path = self.get_temp_dir() + "/tmp_model" keras.models.save_model(model, model_path, save_format="tf") reloaded_model = keras.models.load_model(model_path) self.assertEqual( len(model.trainable_variables), len(reloaded_model.trainable_variables)) for src_v, loaded_v in zip(model.trainable_variables, reloaded_model.trainable_variables): self.assertAllEqual(src_v, loaded_v) @parameterized.parameters("h5", "tf") def test_keras_saving_functional(self, save_format): model = TestModel() query = keras.Input(shape=(40, 80)) output = multi_head_attention.MultiHeadAttention( num_heads=3, key_dim=4, value_dim=4, use_bias=True, dropout=0.0)(query, query) model = keras.Model(inputs=query, outputs=output) model_path = self.get_temp_dir() + "/tmp_model" keras.models.save_model(model, model_path, save_format=save_format) reloaded_model = keras.models.load_model(model_path) self.assertEqual( len(model.trainable_variables), len(reloaded_model.trainable_variables)) for src_v, loaded_v in zip(model.trainable_variables, reloaded_model.trainable_variables): self.assertAllEqual(src_v, loaded_v) def test_create_without_build(self): not_intialized_layer = multi_head_attention.MultiHeadAttention( num_heads=3, key_dim=4, value_dim=4) multi_head_attention.MultiHeadAttention.from_config( not_intialized_layer.get_config()) if __name__ == "__main__": tf.test.main()
14,028
40.752976
80
py
keras
keras-master/keras/layers/lstm_test.py
# 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 LSTM layer.""" import tensorflow.compat.v2 as tf import copy from absl.testing import parameterized import numpy as np import keras from keras import keras_parameterized from keras import testing_utils @keras_parameterized.run_all_keras_modes class LSTMLayerTest(keras_parameterized.TestCase): def test_return_sequences_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'return_sequences': True}, input_shape=(num_samples, timesteps, embedding_dim)) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Double type is yet not supported in ROCm') @testing_utils.run_v2_only def test_float64_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'return_sequences': True, 'dtype': 'float64'}, input_shape=(num_samples, timesteps, embedding_dim), input_dtype='float64') def test_static_shape_inference_LSTM(self): # Github issue: 15165 timesteps = 3 embedding_dim = 4 units = 2 model = keras.models.Sequential() inputs = keras.layers.Dense(embedding_dim, input_shape=(timesteps, embedding_dim)) model.add(inputs) layer = keras.layers.LSTM(units, return_sequences=True) model.add(layer) outputs = model.layers[-1].output self.assertEqual(outputs.shape.as_list(), [None, timesteps, units]) def test_dynamic_behavior_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer = keras.layers.LSTM(units, input_shape=(None, embedding_dim)) model = keras.models.Sequential() model.add(layer) model.compile( 'rmsprop', 'mse', run_eagerly=testing_utils.should_run_eagerly()) x = np.random.random((num_samples, timesteps, embedding_dim)) y = np.random.random((num_samples, units)) model.train_on_batch(x, y) def test_dropout_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) def test_recurrent_dropout_with_implementation_restriction(self): layer = keras.layers.LSTM(2, recurrent_dropout=0.1, implementation=2) # The implementation is force to 1 due to the limit of recurrent_dropout. self.assertEqual(layer.implementation, 1) @parameterized.parameters([0, 1, 2]) def test_implementation_mode_LSTM(self, implementation_mode): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.LSTM, kwargs={'units': units, 'implementation': implementation_mode}, input_shape=(num_samples, timesteps, embedding_dim)) def test_constraints_LSTM(self): embedding_dim = 4 layer_class = keras.layers.LSTM k_constraint = keras.constraints.max_norm(0.01) r_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_constraint=k_constraint, recurrent_constraint=r_constraint, bias_constraint=b_constraint) layer.build((None, None, embedding_dim)) self.assertEqual(layer.cell.kernel.constraint, k_constraint) self.assertEqual(layer.cell.recurrent_kernel.constraint, r_constraint) self.assertEqual(layer.cell.bias.constraint, b_constraint) @parameterized.parameters([True, False]) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input.') def test_with_masking_layer_LSTM(self, unroll): layer_class = keras.layers.LSTM inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) model.add(layer_class(units=5, return_sequences=True, unroll=unroll)) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) @parameterized.parameters([True, False]) def test_masking_with_stacking_LSTM(self, unroll): inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) lstm_cells = [keras.layers.LSTMCell(10), keras.layers.LSTMCell(5)] model.add(keras.layers.RNN( lstm_cells, return_sequences=True, unroll=unroll)) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) def test_from_config_LSTM(self): layer_class = keras.layers.LSTM for stateful in (False, True): l1 = layer_class(units=1, stateful=stateful) l2 = layer_class.from_config(l1.get_config()) assert l1.get_config() == l2.get_config() def test_deep_copy_LSTM(self): cell = keras.layers.LSTMCell(5) copied_cell = copy.deepcopy(cell) self.assertEqual(copied_cell.units, 5) self.assertEqual(cell.get_config(), copied_cell.get_config()) def test_specify_initial_state_keras_tensor(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 # Test with Keras tensor inputs = keras.Input((timesteps, embedding_dim)) initial_state = [keras.Input((units,)) for _ in range(num_states)] layer = keras.layers.LSTM(units) if len(initial_state) == 1: output = layer(inputs, initial_state=initial_state[0]) else: output = layer(inputs, initial_state=initial_state) self.assertTrue( any(initial_state[0] is t for t in layer._inbound_nodes[0].input_tensors)) model = keras.models.Model([inputs] + initial_state, output) model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.AdamOptimizer(), run_eagerly=testing_utils.should_run_eagerly()) inputs = np.random.random((num_samples, timesteps, embedding_dim)) initial_state = [np.random.random((num_samples, units)) for _ in range(num_states)] targets = np.random.random((num_samples, units)) model.train_on_batch([inputs] + initial_state, targets) def test_specify_initial_state_non_keras_tensor(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 # Test with non-Keras tensor inputs = keras.Input((timesteps, embedding_dim)) initial_state = [keras.backend.random_normal_variable( (num_samples, units), 0, 1) for _ in range(num_states)] layer = keras.layers.LSTM(units) output = layer(inputs, initial_state=initial_state) model = keras.models.Model(inputs, output) model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.AdamOptimizer(), run_eagerly=testing_utils.should_run_eagerly()) inputs = np.random.random((num_samples, timesteps, embedding_dim)) targets = np.random.random((num_samples, units)) model.train_on_batch(inputs, targets) def test_reset_states_with_values(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 layer = keras.layers.LSTM(units, stateful=True) layer.build((num_samples, timesteps, embedding_dim)) layer.reset_states() assert len(layer.states) == num_states assert layer.states[0] is not None self.assertAllClose( keras.backend.eval(layer.states[0]), np.zeros(keras.backend.int_shape(layer.states[0])), atol=1e-4) state_shapes = [keras.backend.int_shape(state) for state in layer.states] values = [np.ones(shape) for shape in state_shapes] if len(values) == 1: values = values[0] layer.reset_states(values) self.assertAllClose( keras.backend.eval(layer.states[0]), np.ones(keras.backend.int_shape(layer.states[0])), atol=1e-4) # Test with invalid data with self.assertRaises(ValueError): layer.reset_states([1] * (len(layer.states) + 1)) def test_specify_state_with_masking(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 inputs = keras.Input((timesteps, embedding_dim)) _ = keras.layers.Masking()(inputs) initial_state = [keras.Input((units,)) for _ in range(num_states)] output = keras.layers.LSTM(units)(inputs, initial_state=initial_state) model = keras.models.Model([inputs] + initial_state, output) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', run_eagerly=testing_utils.should_run_eagerly()) inputs = np.random.random((num_samples, timesteps, embedding_dim)) initial_state = [np.random.random((num_samples, units)) for _ in range(num_states)] targets = np.random.random((num_samples, units)) model.train_on_batch([inputs] + initial_state, targets) def test_return_state(self): num_states = 2 timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) layer = keras.layers.LSTM(units, return_state=True, stateful=True) outputs = layer(inputs) state = outputs[1:] assert len(state) == num_states model = keras.models.Model(inputs, state[0]) inputs = np.random.random((num_samples, timesteps, embedding_dim)) state = model.predict(inputs) self.assertAllClose(keras.backend.eval(layer.states[0]), state, atol=1e-4) def test_state_reuse(self): timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim)) layer = keras.layers.LSTM(units, return_state=True, return_sequences=True) outputs = layer(inputs) output, state = outputs[0], outputs[1:] output = keras.layers.LSTM(units)(output, initial_state=state) model = keras.models.Model(inputs, output) inputs = np.random.random((num_samples, timesteps, embedding_dim)) outputs = model.predict(inputs) def test_initial_states_as_other_inputs(self): timesteps = 3 embedding_dim = 4 units = 3 num_samples = 2 num_states = 2 layer_class = keras.layers.LSTM # Test with Keras tensor main_inputs = keras.Input((timesteps, embedding_dim)) initial_state = [keras.Input((units,)) for _ in range(num_states)] inputs = [main_inputs] + initial_state layer = layer_class(units) output = layer(inputs) self.assertTrue( any(initial_state[0] is t for t in layer._inbound_nodes[0].input_tensors)) model = keras.models.Model(inputs, output) model.compile( loss='categorical_crossentropy', optimizer=tf.compat.v1.train.AdamOptimizer(), run_eagerly=testing_utils.should_run_eagerly()) main_inputs = np.random.random((num_samples, timesteps, embedding_dim)) initial_state = [np.random.random((num_samples, units)) for _ in range(num_states)] targets = np.random.random((num_samples, units)) model.train_on_batch([main_inputs] + initial_state, targets) def test_regularizers_LSTM(self): embedding_dim = 4 layer_class = keras.layers.LSTM layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_regularizer=keras.regularizers.l1(0.01), recurrent_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l2', activity_regularizer='l1') layer.build((None, None, 2)) self.assertEqual(len(layer.losses), 3) x = keras.backend.variable(np.ones((2, 3, 2))) layer(x) if tf.executing_eagerly(): self.assertEqual(len(layer.losses), 4) else: self.assertEqual(len(layer.get_losses_for(x)), 1) @tf.test.disable_with_predicate( pred=tf.test.is_built_with_rocm, skip_message='Skipping as ROCm MIOpen does not support padded input.') def test_statefulness_LSTM(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer_class = keras.layers.LSTM model = keras.models.Sequential() model.add( keras.layers.Embedding( 4, embedding_dim, mask_zero=True, input_length=timesteps, batch_input_shape=(num_samples, timesteps))) layer = layer_class( units, return_sequences=False, stateful=True, weights=None) model.add(layer) model.compile( optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01), loss='mse', run_eagerly=testing_utils.should_run_eagerly()) out1 = model.predict(np.ones((num_samples, timesteps))) self.assertEqual(out1.shape, (num_samples, units)) # train once so that the states change model.train_on_batch( np.ones((num_samples, timesteps)), np.ones((num_samples, units))) out2 = model.predict(np.ones((num_samples, timesteps))) # if the state is not reset, output should be different self.assertNotEqual(out1.max(), out2.max()) # check that output changes after states are reset # (even though the model itself didn't change) layer.reset_states() out3 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out2.max(), out3.max()) # check that container-level reset_states() works model.reset_states() out4 = model.predict(np.ones((num_samples, timesteps))) self.assertAllClose(out3, out4, atol=1e-5) # check that the call to `predict` updated the states out5 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out4.max(), out5.max()) # Check masking layer.reset_states() left_padded_input = np.ones((num_samples, timesteps)) left_padded_input[0, :1] = 0 left_padded_input[1, :2] = 0 out6 = model.predict(left_padded_input) layer.reset_states() right_padded_input = np.ones((num_samples, timesteps)) right_padded_input[0, -1:] = 0 right_padded_input[1, -2:] = 0 out7 = model.predict(right_padded_input) self.assertAllClose(out7, out6, atol=1e-5) if __name__ == '__main__': tf.test.main()
15,716
33.695364
80
py
keras
keras-master/keras/layers/rnn_cell_wrapper_v2_test.py
# 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 RNN cell wrapper v2 implementation.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np from keras import combinations from keras import layers from keras.layers import rnn_cell_wrapper_v2 from keras.layers.legacy_rnn import rnn_cell_impl from keras.legacy_tf_layers import base as legacy_base_layer from keras.utils import generic_utils @combinations.generate(combinations.combine(mode=["graph", "eager"])) class RNNCellWrapperTest(tf.test.TestCase, parameterized.TestCase): def testResidualWrapper(self): wrapper_type = rnn_cell_wrapper_v2.ResidualWrapper x = tf.convert_to_tensor( np.array([[1., 1., 1.]]), dtype="float32") m = tf.convert_to_tensor( np.array([[0.1, 0.1, 0.1]]), dtype="float32") base_cell = rnn_cell_impl.GRUCell( 3, kernel_initializer=tf.compat.v1.constant_initializer(0.5), bias_initializer=tf.compat.v1.constant_initializer(0.5)) g, m_new = base_cell(x, m) wrapper_object = wrapper_type(base_cell) (name, dep), = wrapper_object._checkpoint_dependencies wrapper_object.get_config() # Should not throw an error self.assertIs(dep, base_cell) self.assertEqual("cell", name) g_res, m_new_res = wrapper_object(x, m) self.evaluate([tf.compat.v1.global_variables_initializer()]) res = self.evaluate([g, g_res, m_new, m_new_res]) # Residual connections self.assertAllClose(res[1], res[0] + [1., 1., 1.]) # States are left untouched self.assertAllClose(res[2], res[3]) def testResidualWrapperWithSlice(self): wrapper_type = rnn_cell_wrapper_v2.ResidualWrapper x = tf.convert_to_tensor( np.array([[1., 1., 1., 1., 1.]]), dtype="float32") m = tf.convert_to_tensor( np.array([[0.1, 0.1, 0.1]]), dtype="float32") base_cell = rnn_cell_impl.GRUCell( 3, kernel_initializer=tf.compat.v1.constant_initializer(0.5), bias_initializer=tf.compat.v1.constant_initializer(0.5)) g, m_new = base_cell(x, m) def residual_with_slice_fn(inp, out): inp_sliced = tf.slice(inp, [0, 0], [-1, 3]) return inp_sliced + out g_res, m_new_res = wrapper_type( base_cell, residual_with_slice_fn)(x, m) self.evaluate([tf.compat.v1.global_variables_initializer()]) res_g, res_g_res, res_m_new, res_m_new_res = self.evaluate( [g, g_res, m_new, m_new_res]) # Residual connections self.assertAllClose(res_g_res, res_g + [1., 1., 1.]) # States are left untouched self.assertAllClose(res_m_new, res_m_new_res) def testDeviceWrapper(self): wrapper_type = rnn_cell_wrapper_v2.DeviceWrapper x = tf.zeros([1, 3]) m = tf.zeros([1, 3]) cell = rnn_cell_impl.GRUCell(3) wrapped_cell = wrapper_type(cell, "/cpu:0") (name, dep), = wrapped_cell._checkpoint_dependencies wrapped_cell.get_config() # Should not throw an error self.assertIs(dep, cell) self.assertEqual("cell", name) outputs, _ = wrapped_cell(x, m) self.assertIn("cpu:0", outputs.device.lower()) @parameterized.parameters( [[rnn_cell_impl.DropoutWrapper, rnn_cell_wrapper_v2.DropoutWrapper], [rnn_cell_impl.ResidualWrapper, rnn_cell_wrapper_v2.ResidualWrapper]]) def testWrapperKerasStyle(self, wrapper, wrapper_v2): """Tests if wrapper cell is instantiated in keras style scope.""" wrapped_cell_v2 = wrapper_v2(rnn_cell_impl.BasicRNNCell(1)) self.assertIsNone(getattr(wrapped_cell_v2, "_keras_style", None)) wrapped_cell = wrapper(rnn_cell_impl.BasicRNNCell(1)) self.assertFalse(wrapped_cell._keras_style) @parameterized.parameters( [rnn_cell_wrapper_v2.DropoutWrapper, rnn_cell_wrapper_v2.ResidualWrapper]) def testWrapperWeights(self, wrapper): """Tests that wrapper weights contain wrapped cells weights.""" base_cell = layers.SimpleRNNCell(1, name="basic_rnn_cell") rnn_cell = wrapper(base_cell) rnn_layer = layers.RNN(rnn_cell) inputs = tf.convert_to_tensor([[[1]]], dtype=tf.float32) rnn_layer(inputs) wrapper_name = generic_utils.to_snake_case(wrapper.__name__) expected_weights = ["rnn/" + wrapper_name + "/" + var for var in ("kernel:0", "recurrent_kernel:0", "bias:0")] self.assertLen(rnn_cell.weights, 3) self.assertCountEqual([v.name for v in rnn_cell.weights], expected_weights) self.assertCountEqual([v.name for v in rnn_cell.trainable_variables], expected_weights) self.assertCountEqual([v.name for v in rnn_cell.non_trainable_variables], []) self.assertCountEqual([v.name for v in rnn_cell.cell.weights], expected_weights) @parameterized.parameters( [rnn_cell_wrapper_v2.DropoutWrapper, rnn_cell_wrapper_v2.ResidualWrapper]) def testWrapperV2Caller(self, wrapper): """Tests that wrapper V2 is using the LayerRNNCell's caller.""" with legacy_base_layer.keras_style_scope(): base_cell = rnn_cell_impl.MultiRNNCell( [rnn_cell_impl.BasicRNNCell(1) for _ in range(2)]) rnn_cell = wrapper(base_cell) inputs = tf.convert_to_tensor([[1]], dtype=tf.float32) state = tf.convert_to_tensor([[1]], dtype=tf.float32) _ = rnn_cell(inputs, [state, state]) weights = base_cell._cells[0].weights self.assertLen(weights, expected_len=2) self.assertTrue(all("_wrapper" in v.name for v in weights)) @parameterized.parameters( [rnn_cell_wrapper_v2.DropoutWrapper, rnn_cell_wrapper_v2.ResidualWrapper]) def testWrapperV2Build(self, wrapper): cell = rnn_cell_impl.LSTMCell(10) wrapper = wrapper(cell) wrapper.build((1,)) self.assertTrue(cell.built) def testDeviceWrapperSerialization(self): wrapper_cls = rnn_cell_wrapper_v2.DeviceWrapper cell = layers.LSTMCell(10) wrapper = wrapper_cls(cell, "/cpu:0") config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) self.assertDictEqual(config, reconstructed_wrapper.get_config()) self.assertIsInstance(reconstructed_wrapper, wrapper_cls) def testResidualWrapperSerialization(self): wrapper_cls = rnn_cell_wrapper_v2.ResidualWrapper cell = layers.LSTMCell(10) wrapper = wrapper_cls(cell) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) self.assertDictEqual(config, reconstructed_wrapper.get_config()) self.assertIsInstance(reconstructed_wrapper, wrapper_cls) wrapper = wrapper_cls(cell, residual_fn=lambda i, o: i + i + o) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) # Assert the reconstructed function will perform the math correctly. self.assertEqual(reconstructed_wrapper._residual_fn(1, 2), 4) def residual_fn(inputs, outputs): return inputs * 3 + outputs wrapper = wrapper_cls(cell, residual_fn=residual_fn) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) # Assert the reconstructed function will perform the math correctly. self.assertEqual(reconstructed_wrapper._residual_fn(1, 2), 5) def testDropoutWrapperSerialization(self): wrapper_cls = rnn_cell_wrapper_v2.DropoutWrapper cell = layers.GRUCell(10) wrapper = wrapper_cls(cell) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) self.assertDictEqual(config, reconstructed_wrapper.get_config()) self.assertIsInstance(reconstructed_wrapper, wrapper_cls) wrapper = wrapper_cls(cell, dropout_state_filter_visitor=lambda s: True) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) self.assertTrue(reconstructed_wrapper._dropout_state_filter(None)) def dropout_state_filter_visitor(unused_state): return False wrapper = wrapper_cls( cell, dropout_state_filter_visitor=dropout_state_filter_visitor) config = wrapper.get_config() reconstructed_wrapper = wrapper_cls.from_config(config) self.assertFalse(reconstructed_wrapper._dropout_state_filter(None)) def testDropoutWrapperWithKerasLSTMCell(self): wrapper_cls = rnn_cell_wrapper_v2.DropoutWrapper cell = layers.LSTMCell(10) with self.assertRaisesRegex(ValueError, "does not work with "): wrapper_cls(cell) cell = layers.LSTMCellV2(10) with self.assertRaisesRegex(ValueError, "does not work with "): wrapper_cls(cell) if __name__ == "__main__": tf.test.main()
9,260
39.265217
80
py
keras
keras-master/keras/layers/local.py
# 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. # ============================================================================== # pylint: disable=g-classes-have-attributes """Locally-connected layers.""" import tensorflow.compat.v2 as tf import numpy as np from keras import activations from keras import backend from keras import constraints from keras import initializers from keras import regularizers from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils from keras.utils import tf_utils from tensorflow.python.util.tf_export import keras_export @keras_export('keras.layers.LocallyConnected1D') class LocallyConnected1D(Layer): """Locally-connected layer for 1D inputs. The `LocallyConnected1D` layer works similarly to the `Conv1D` 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). Example: ```python # apply a unshared weight convolution 1d of length 3 to a sequence with # 10 timesteps, with 64 output filters model = Sequential() model.add(LocallyConnected1D(64, 3, input_shape=(10, 32))) # now model.output_shape == (None, 8, 64) # add a new conv1d on top model.add(LocallyConnected1D(32, 3)) # now model.output_shape == (None, 6, 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 a single integer, specifying the length of the 1D convolution window. strides: An integer or tuple/list of a single integer, specifying the stride length of the convolution. padding: Currently only supports `"valid"` (case-insensitive). `"same"` may be supported in the 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, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. 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". 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 `input_size`, `output_size`), and "sparse" stands for few connections between inputs and outputs, i.e. small ratio `filters * input_filters * kernel_size / (input_size * 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: 3D tensor with shape: `(batch_size, steps, input_dim)` Output shape: 3D tensor with shape: `(batch_size, new_steps, filters)` `steps` value might have changed due to padding or strides. """ def __init__(self, filters, kernel_size, strides=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(LocallyConnected1D, self).__init__(**kwargs) self.filters = filters self.kernel_size = conv_utils.normalize_tuple(kernel_size, 1, 'kernel_size') self.strides = conv_utils.normalize_tuple(strides, 1, 'strides') self.padding = conv_utils.normalize_padding(padding) if self.padding != 'valid' and implementation == 1: raise ValueError('Invalid border mode for LocallyConnected1D ' '(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=3) @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_first': input_dim, input_length = input_shape[1], input_shape[2] else: input_dim, input_length = input_shape[2], input_shape[1] if input_dim is None: raise ValueError( 'Axis 2 of input should be fully-defined. ' 'Found shape:', input_shape) self.output_length = conv_utils.conv_output_length(input_length, self.kernel_size[0], self.padding, self.strides[0]) if self.implementation == 1: self.kernel_shape = (self.output_length, self.kernel_size[0] * input_dim, 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_dim, input_length, self.filters, self.output_length) else: self.kernel_shape = (input_length, input_dim, self.output_length, 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 = get_locallyconnected_mask( input_shape=(input_length,), 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_length * self.filters, input_length * input_dim) self.kernel_idxs = sorted( conv_utils.conv_kernel_idxs( input_shape=(input_length,), kernel_shape=self.kernel_size, strides=self.strides, padding=self.padding, filters_in=input_dim, 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=(self.output_length, 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=3, axes={1: input_dim}) else: self.input_spec = InputSpec(ndim=3, axes={-1: input_dim}) self.built = True @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': input_length = input_shape[2] else: input_length = input_shape[1] length = conv_utils.conv_output_length(input_length, self.kernel_size[0], self.padding, self.strides[0]) if self.data_format == 'channels_first': return (input_shape[0], self.filters, length) elif self.data_format == 'channels_last': return (input_shape[0], length, self.filters) def call(self, inputs): if self.implementation == 1: output = backend.local_conv( inputs, self.kernel, self.kernel_size, self.strides, (self.output_length,), self.data_format) elif self.implementation == 2: output = local_conv_matmul(inputs, self.kernel, self.kernel_mask, self.compute_output_shape(inputs.shape)) elif self.implementation == 3: output = 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(LocallyConnected1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @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)`. 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". 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(LocallyConnected2D, self).__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') 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.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 = 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 = local_conv_matmul(inputs, self.kernel, self.kernel_mask, self.compute_output_shape(inputs.shape)) elif self.implementation == 3: output = 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(LocallyConnected2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) def get_locallyconnected_mask(input_shape, kernel_shape, strides, padding, data_format): """Return a mask representing connectivity of a locally-connected operation. This method returns a masking numpy array of 0s and 1s (of type `np.float32`) that, when element-wise multiplied with a fully-connected weight tensor, masks out the weights between disconnected input-output pairs and thus implements local connectivity through a sparse fully-connected weight tensor. Assume an unshared convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined by layer parameters such as `strides`). This method returns a mask which can be broadcast-multiplied (element-wise) with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer between (N+1)-D activations (N spatial + 1 channel dimensions for input and output) to make it perform an unshared convolution with given `kernel_shape`, `strides`, `padding` and `data_format`. Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)` spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. data_format: a string, `"channels_first"` or `"channels_last"`. Returns: a `np.float32`-type `np.ndarray` of shape `(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)` if `data_format == `"channels_first"`, or `(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)` if `data_format == "channels_last"`. Raises: ValueError: if `data_format` is neither `"channels_first"` nor `"channels_last"`. """ mask = conv_utils.conv_kernel_mask( input_shape=input_shape, kernel_shape=kernel_shape, strides=strides, padding=padding) ndims = int(mask.ndim / 2) if data_format == 'channels_first': mask = np.expand_dims(mask, 0) mask = np.expand_dims(mask, -ndims - 1) elif data_format == 'channels_last': mask = np.expand_dims(mask, ndims) mask = np.expand_dims(mask, -1) else: raise ValueError('Unrecognized data_format: ' + str(data_format)) return mask def local_conv_matmul(inputs, kernel, kernel_mask, output_shape): """Apply N-D convolution with un-shared weights using a single matmul call. This method outputs `inputs . (kernel * kernel_mask)` (with `.` standing for matrix-multiply and `*` for element-wise multiply) and requires a precomputed `kernel_mask` to zero-out weights in `kernel` and hence perform the same operation as a convolution with un-shared (the remaining entries in `kernel`) weights. It also does the necessary reshapes to make `inputs` and `kernel` 2-D and `output` (N+2)-D. Args: inputs: (N+2)-D tensor with shape `(batch_size, channels_in, d_in1, ..., d_inN)` or `(batch_size, d_in1, ..., d_inN, channels_in)`. kernel: the unshared weights for N-D convolution, an (N+2)-D tensor of shape: `(d_in1, ..., d_inN, channels_in, d_out2, ..., d_outN, channels_out)` or `(channels_in, d_in1, ..., d_inN, channels_out, d_out2, ..., d_outN)`, with the ordering of channels and spatial dimensions matching that of the input. Each entry is the weight between a particular input and output location, similarly to a fully-connected weight matrix. kernel_mask: a float 0/1 mask tensor of shape: `(d_in1, ..., d_inN, 1, d_out2, ..., d_outN, 1)` or `(1, d_in1, ..., d_inN, 1, d_out2, ..., d_outN)`, with the ordering of singleton and spatial dimensions matching that of the input. Mask represents the connectivity pattern of the layer and is precomputed elsewhere based on layer parameters: stride, padding, and the receptive field shape. output_shape: a tuple of (N+2) elements representing the output shape: `(batch_size, channels_out, d_out1, ..., d_outN)` or `(batch_size, d_out1, ..., d_outN, channels_out)`, with the ordering of channels and spatial dimensions matching that of the input. Returns: Output (N+2)-D tensor with shape `output_shape`. """ inputs_flat = backend.reshape(inputs, (backend.shape(inputs)[0], -1)) kernel = kernel_mask * kernel kernel = make_2d(kernel, split_dim=backend.ndim(kernel) // 2) output_flat = tf.matmul(inputs_flat, kernel, b_is_sparse=True) output = backend.reshape(output_flat, [ backend.shape(output_flat)[0], ] + output_shape.as_list()[1:]) return output def local_conv_sparse_matmul(inputs, kernel, kernel_idxs, kernel_shape, output_shape): """Apply N-D convolution with un-shared weights using a single sparse matmul. This method outputs `inputs . tf.sparse.SparseTensor(indices=kernel_idxs, values=kernel, dense_shape=kernel_shape)`, with `.` standing for matrix-multiply. It also reshapes `inputs` to 2-D and `output` to (N+2)-D. Args: inputs: (N+2)-D tensor with shape `(batch_size, channels_in, d_in1, ..., d_inN)` or `(batch_size, d_in1, ..., d_inN, channels_in)`. kernel: a 1-D tensor with shape `(len(kernel_idxs),)` containing all the weights of the layer. kernel_idxs: a list of integer tuples representing indices in a sparse matrix performing the un-shared convolution as a matrix-multiply. kernel_shape: a tuple `(input_size, output_size)`, where `input_size = channels_in * d_in1 * ... * d_inN` and `output_size = channels_out * d_out1 * ... * d_outN`. output_shape: a tuple of (N+2) elements representing the output shape: `(batch_size, channels_out, d_out1, ..., d_outN)` or `(batch_size, d_out1, ..., d_outN, channels_out)`, with the ordering of channels and spatial dimensions matching that of the input. Returns: Output (N+2)-D dense tensor with shape `output_shape`. """ inputs_flat = backend.reshape(inputs, (backend.shape(inputs)[0], -1)) output_flat = tf.raw_ops.SparseTensorDenseMatMul( a_indices=kernel_idxs, a_values=kernel, a_shape=kernel_shape, b=inputs_flat, adjoint_b=True) output_flat_transpose = backend.transpose(output_flat) output_reshaped = backend.reshape(output_flat_transpose, [ backend.shape(output_flat_transpose)[0], ] + output_shape.as_list()[1:]) return output_reshaped def make_2d(tensor, split_dim): """Reshapes an N-dimensional tensor into a 2D tensor. Dimensions before (excluding) and after (including) `split_dim` are grouped together. Args: tensor: a tensor of shape `(d0, ..., d(N-1))`. split_dim: an integer from 1 to N-1, index of the dimension to group dimensions before (excluding) and after (including). Returns: Tensor of shape `(d0 * ... * d(split_dim-1), d(split_dim) * ... * d(N-1))`. """ shape = tf.shape(tensor) in_dims = shape[:split_dim] out_dims = shape[split_dim:] in_size = tf.reduce_prod(in_dims) out_size = tf.reduce_prod(out_dims) return tf.reshape(tensor, (in_size, out_size))
34,424
41.239264
80
py
keras
keras-master/keras/layers/simplernn_test.py
# 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 SimpleRNN layer.""" import tensorflow.compat.v2 as tf import copy from absl.testing import parameterized import numpy as np import keras from keras import combinations from keras import testing_utils @combinations.generate(combinations.keras_mode_combinations()) class SimpleRNNLayerTest(tf.test.TestCase, parameterized.TestCase): def test_return_sequences_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.SimpleRNN, kwargs={'units': units, 'return_sequences': True}, input_shape=(num_samples, timesteps, embedding_dim)) @testing_utils.run_v2_only def test_float64_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.SimpleRNN, kwargs={'units': units, 'return_sequences': True, 'dtype': 'float64'}, input_shape=(num_samples, timesteps, embedding_dim), input_dtype='float64') def test_dynamic_behavior_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer = keras.layers.SimpleRNN(units, input_shape=(None, embedding_dim)) model = keras.models.Sequential() model.add(layer) model.compile('rmsprop', 'mse') x = np.random.random((num_samples, timesteps, embedding_dim)) y = np.random.random((num_samples, units)) model.train_on_batch(x, y) def test_dropout_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 testing_utils.layer_test( keras.layers.SimpleRNN, kwargs={'units': units, 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) def test_implementation_mode_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 for mode in [0, 1, 2]: testing_utils.layer_test( keras.layers.SimpleRNN, kwargs={'units': units, 'implementation': mode}, input_shape=(num_samples, timesteps, embedding_dim)) def test_constraints_SimpleRNN(self): embedding_dim = 4 layer_class = keras.layers.SimpleRNN k_constraint = keras.constraints.max_norm(0.01) r_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_constraint=k_constraint, recurrent_constraint=r_constraint, bias_constraint=b_constraint) layer.build((None, None, embedding_dim)) self.assertEqual(layer.cell.kernel.constraint, k_constraint) self.assertEqual(layer.cell.recurrent_kernel.constraint, r_constraint) self.assertEqual(layer.cell.bias.constraint, b_constraint) def test_with_masking_layer_SimpleRNN(self): layer_class = keras.layers.SimpleRNN inputs = np.random.random((2, 3, 4)) targets = np.abs(np.random.random((2, 3, 5))) targets /= targets.sum(axis=-1, keepdims=True) model = keras.models.Sequential() model.add(keras.layers.Masking(input_shape=(3, 4))) model.add(layer_class(units=5, return_sequences=True, unroll=False)) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1) def test_from_config_SimpleRNN(self): layer_class = keras.layers.SimpleRNN for stateful in (False, True): l1 = layer_class(units=1, stateful=stateful) l2 = layer_class.from_config(l1.get_config()) assert l1.get_config() == l2.get_config() def test_deep_copy_SimpleRNN(self): cell = keras.layers.SimpleRNNCell(5) copied_cell = copy.deepcopy(cell) self.assertEqual(copied_cell.units, 5) self.assertEqual(cell.get_config(), copied_cell.get_config()) def test_regularizers_SimpleRNN(self): embedding_dim = 4 layer_class = keras.layers.SimpleRNN layer = layer_class( 5, return_sequences=False, weights=None, input_shape=(None, embedding_dim), kernel_regularizer=keras.regularizers.l1(0.01), recurrent_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l2', activity_regularizer='l1') layer.build((None, None, 2)) self.assertLen(layer.losses, 3) x = keras.backend.variable(np.ones((2, 3, 2))) layer(x) if tf.executing_eagerly(): self.assertLen(layer.losses, 4) else: self.assertLen(layer.get_losses_for(x), 1) def test_statefulness_SimpleRNN(self): num_samples = 2 timesteps = 3 embedding_dim = 4 units = 2 layer_class = keras.layers.SimpleRNN model = keras.models.Sequential() model.add( keras.layers.Embedding( 4, embedding_dim, mask_zero=True, input_length=timesteps, batch_input_shape=(num_samples, timesteps))) layer = layer_class( units, return_sequences=False, stateful=True, weights=None) model.add(layer) model.compile( optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.01), loss='mse', run_eagerly=testing_utils.should_run_eagerly()) out1 = model.predict(np.ones((num_samples, timesteps))) self.assertEqual(out1.shape, (num_samples, units)) # train once so that the states change model.train_on_batch( np.ones((num_samples, timesteps)), np.ones((num_samples, units))) out2 = model.predict(np.ones((num_samples, timesteps))) # if the state is not reset, output should be different self.assertNotEqual(out1.max(), out2.max()) # check that output changes after states are reset # (even though the model itself didn't change) layer.reset_states() out3 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out2.max(), out3.max()) # check that container-level reset_states() works model.reset_states() out4 = model.predict(np.ones((num_samples, timesteps))) np.testing.assert_allclose(out3, out4, atol=1e-5) # check that the call to `predict` updated the states out5 = model.predict(np.ones((num_samples, timesteps))) self.assertNotEqual(out4.max(), out5.max()) # Check masking layer.reset_states() left_padded_input = np.ones((num_samples, timesteps)) left_padded_input[0, :1] = 0 left_padded_input[1, :2] = 0 out6 = model.predict(left_padded_input) layer.reset_states() right_padded_input = np.ones((num_samples, timesteps)) right_padded_input[0, -1:] = 0 right_padded_input[1, -2:] = 0 out7 = model.predict(right_padded_input) np.testing.assert_allclose(out7, out6, atol=1e-5) def test_get_initial_states(self): batch_size = 4 cell = keras.layers.SimpleRNNCell(20) initial_state = cell.get_initial_state( batch_size=batch_size, dtype=tf.float32) _, state = cell(np.ones((batch_size, 20), dtype=np.float32), initial_state) self.assertEqual(state.shape, initial_state.shape) if __name__ == '__main__': tf.test.main()
7,925
32.871795
80
py
keras
keras-master/keras/layers/convolutional_recurrent.py
# 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. # ============================================================================== # pylint: disable=protected-access # pylint: disable=g-classes-have-attributes """Convolutional-recurrent layers.""" import tensorflow.compat.v2 as tf import numpy as np from keras import activations from keras import backend from keras import constraints from keras import initializers from keras import regularizers from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.layers.recurrent import DropoutRNNCellMixin from keras.layers.recurrent import RNN from keras.utils import conv_utils from keras.utils import generic_utils from keras.utils import tf_utils from tensorflow.python.util.tf_export import keras_export class ConvRNN(RNN): """N-Dimensional Base class for convolutional-recurrent layers. Args: rank: Integer, rank of the convolution, e.g. "2" for 2D convolutions. cell: A RNN cell instance. A RNN cell is a class that has: - a `call(input_at_t, states_at_t)` method, returning `(output_at_t, states_at_t_plus_1)`. The call method of the cell can also take the optional argument `constants`, see section "Note on passing external constants" below. - a `state_size` attribute. This can be a single integer (single state) in which case it is the number of channels of the recurrent state (which should be the same as the number of channels of the cell output). This can also be a list/tuple of integers (one size per state). In this case, the first entry (`state_size[0]`) should be the same as the size of the cell output. return_sequences: Boolean. Whether to return the last output. in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state in addition to the output. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. input_shape: Use this argument to specify the shape of the input when this layer is the first one in a model. Call arguments: inputs: A (2 + `rank`)D tensor. mask: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is for use with cells that use dropout. initial_state: List of initial state tensors to be passed to the first call of the cell. constants: List of constant tensors to be passed to the cell at each timestep. Input shape: (3 + `rank`)D tensor with shape: `(samples, timesteps, channels, img_dimensions...)` if data_format='channels_first' or shape: `(samples, timesteps, img_dimensions..., channels)` if data_format='channels_last'. Output shape: - If `return_state`: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each (2 + `rank`)D tensor with shape: `(samples, filters, new_img_dimensions...)` if data_format='channels_first' or shape: `(samples, new_img_dimensions..., filters)` if data_format='channels_last'. img_dimension values might have changed due to padding. - If `return_sequences`: (3 + `rank`)D tensor with shape: `(samples, timesteps, filters, new_img_dimensions...)` if data_format='channels_first' or shape: `(samples, timesteps, new_img_dimensions..., filters)` if data_format='channels_last'. - Else, (2 + `rank`)D tensor with shape: `(samples, filters, new_img_dimensions...)` if data_format='channels_first' or shape: `(samples, new_img_dimensions..., filters)` if data_format='channels_last'. Masking: This layer supports masking for input data with a variable number of timesteps. Note on using statefulness in RNNs: You can set RNN layers to be 'stateful', which means that the states computed for the samples in one batch will be reused as initial states for the samples in the next batch. This assumes a one-to-one mapping between samples in different successive batches. To enable statefulness: - Specify `stateful=True` in the layer constructor. - Specify a fixed batch size for your model, by passing - If sequential model: `batch_input_shape=(...)` to the first layer in your model. - If functional model with 1 or more Input layers: `batch_shape=(...)` to all the first layers in your model. This is the expected shape of your inputs *including the batch size*. It should be a tuple of integers, e.g. `(32, 10, 100, 100, 32)`. for rank 2 convolution Note that the image dimensions should be specified too. - Specify `shuffle=False` when calling fit(). To reset the states of your model, call `.reset_states()` on either a specific layer, or on your entire model. Note on specifying the initial state of RNNs: You can specify the initial state of RNN layers symbolically by calling them with the keyword argument `initial_state`. The value of `initial_state` should be a tensor or list of tensors representing the initial state of the RNN layer. You can specify the initial state of RNN layers numerically by calling `reset_states` with the keyword argument `states`. The value of `states` should be a numpy array or list of numpy arrays representing the initial state of the RNN layer. Note on passing external constants to RNNs: You can pass "external" constants to the cell using the `constants` keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This requires that the `cell.call` method accepts the same keyword argument `constants`. Such constants can be used to condition the cell transformation on additional static inputs (not changing over time), a.k.a. an attention mechanism. """ def __init__(self, rank, cell, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, **kwargs): if unroll: raise TypeError( 'Unrolling is not possible with convolutional RNNs. ' f'Received: unroll={unroll}') if isinstance(cell, (list, tuple)): # The StackedConvRNN3DCells isn't implemented yet. raise TypeError('It is not possible at the moment to' 'stack convolutional cells. Only pass a single cell ' 'instance as the `cell` argument. Received: ' f'cell={cell}') super(ConvRNN, self).__init__(cell, return_sequences, return_state, go_backwards, stateful, unroll, **kwargs) self.rank = rank self.input_spec = [InputSpec(ndim=rank + 3)] self.states = None self._num_constants = None @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if isinstance(input_shape, list): input_shape = input_shape[0] cell = self.cell if cell.data_format == 'channels_first': img_dims = input_shape[3:] elif cell.data_format == 'channels_last': img_dims = input_shape[2:-1] norm_img_dims = tuple([ conv_utils.conv_output_length( img_dims[idx], cell.kernel_size[idx], padding=cell.padding, stride=cell.strides[idx], dilation=cell.dilation_rate[idx]) for idx in range(len(img_dims)) ]) if cell.data_format == 'channels_first': output_shape = input_shape[:2] + (cell.filters,) + norm_img_dims elif cell.data_format == 'channels_last': output_shape = input_shape[:2] + norm_img_dims + (cell.filters,) if not self.return_sequences: output_shape = output_shape[:1] + output_shape[2:] if self.return_state: output_shape = [output_shape] if cell.data_format == 'channels_first': output_shape += [ (input_shape[0], cell.filters) + norm_img_dims for _ in range(2) ] elif cell.data_format == 'channels_last': output_shape += [(input_shape[0],) + norm_img_dims + (cell.filters,) for _ in range(2)] return output_shape @tf_utils.shape_type_conversion def build(self, input_shape): # Note input_shape will be list of shapes of initial states and # constants if these are passed in __call__. if self._num_constants is not None: constants_shape = input_shape[-self._num_constants:] # pylint: disable=E1130 else: constants_shape = None if isinstance(input_shape, list): input_shape = input_shape[0] batch_size = input_shape[0] if self.stateful else None self.input_spec[0] = InputSpec( shape=(batch_size, None) + input_shape[2:self.rank + 3]) # allow cell (if layer) to build before we set or validate state_spec if isinstance(self.cell, Layer): step_input_shape = (input_shape[0],) + input_shape[2:] if constants_shape is not None: self.cell.build([step_input_shape] + constants_shape) else: self.cell.build(step_input_shape) # set or validate state_spec if hasattr(self.cell.state_size, '__len__'): state_size = list(self.cell.state_size) else: state_size = [self.cell.state_size] if self.state_spec is not None: # initial_state was passed in call, check compatibility if self.cell.data_format == 'channels_first': ch_dim = 1 elif self.cell.data_format == 'channels_last': ch_dim = self.rank + 1 if [spec.shape[ch_dim] for spec in self.state_spec] != state_size: raise ValueError( 'An `initial_state` was passed that is not compatible with ' '`cell.state_size`. Received state shapes ' f'{[spec.shape for spec in self.state_spec]}. ' f'However `cell.state_size` is {self.cell.state_size}') else: img_dims = tuple((None for _ in range(self.rank))) if self.cell.data_format == 'channels_first': self.state_spec = [ InputSpec(shape=(None, dim) + img_dims) for dim in state_size ] elif self.cell.data_format == 'channels_last': self.state_spec = [ InputSpec(shape=(None,) + img_dims + (dim,)) for dim in state_size ] if self.stateful: self.reset_states() self.built = True def get_initial_state(self, inputs): # (samples, timesteps, img_dims..., filters) initial_state = backend.zeros_like(inputs) # (samples, img_dims..., filters) initial_state = backend.sum(initial_state, axis=1) shape = list(self.cell.kernel_shape) shape[-1] = self.cell.filters initial_state = self.cell.input_conv(initial_state, tf.zeros(tuple(shape), initial_state.dtype), padding=self.cell.padding) if hasattr(self.cell.state_size, '__len__'): return [initial_state for _ in self.cell.state_size] else: return [initial_state] def call(self, inputs, mask=None, training=None, initial_state=None, constants=None): # note that the .build() method of subclasses MUST define # self.input_spec and self.state_spec with complete input shapes. inputs, initial_state, constants = self._process_inputs( inputs, initial_state, constants) if isinstance(mask, list): mask = mask[0] timesteps = backend.int_shape(inputs)[1] kwargs = {} if generic_utils.has_arg(self.cell.call, 'training'): kwargs['training'] = training if constants: if not generic_utils.has_arg(self.cell.call, 'constants'): raise ValueError( f'RNN cell {self.cell} does not support constants. ' f'Received: constants={constants}') def step(inputs, states): constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type states = states[:-self._num_constants] # pylint: disable=invalid-unary-operand-type return self.cell.call(inputs, states, constants=constants, **kwargs) else: def step(inputs, states): return self.cell.call(inputs, states, **kwargs) last_output, outputs, states = backend.rnn(step, inputs, initial_state, constants=constants, go_backwards=self.go_backwards, mask=mask, input_length=timesteps) if self.stateful: updates = [ backend.update(self_state, state) for self_state, state in zip(self.states, states) ] self.add_update(updates) if self.return_sequences: output = outputs else: output = last_output if self.return_state: if not isinstance(states, (list, tuple)): states = [states] else: states = list(states) return [output] + states return output def reset_states(self, states=None): if not self.stateful: raise AttributeError('Layer must be stateful.') input_shape = self.input_spec[0].shape state_shape = self.compute_output_shape(input_shape) if self.return_state: state_shape = state_shape[0] if self.return_sequences: state_shape = state_shape[:1].concatenate(state_shape[2:]) if None in state_shape: raise ValueError('If a RNN is stateful, it needs to know ' 'its batch size. Specify the batch size ' 'of your input tensors: \n' '- If using a Sequential model, ' 'specify the batch size by passing ' 'a `batch_input_shape` ' 'argument to your first layer.\n' '- If using the functional API, specify ' 'the time dimension by passing a ' '`batch_shape` argument to your Input layer.\n' 'The same thing goes for the number of rows and ' 'columns.') # helper function def get_tuple_shape(nb_channels): result = list(state_shape) if self.cell.data_format == 'channels_first': result[1] = nb_channels elif self.cell.data_format == 'channels_last': result[self.rank + 1] = nb_channels else: raise KeyError( 'Cell data format must be one of ' '{"channels_first", "channels_last"}. Received: ' f'cell.data_format={self.cell.data_format}') return tuple(result) # initialize state if None if self.states[0] is None: if hasattr(self.cell.state_size, '__len__'): self.states = [backend.zeros(get_tuple_shape(dim)) for dim in self.cell.state_size] else: self.states = [backend.zeros(get_tuple_shape(self.cell.state_size))] elif states is None: if hasattr(self.cell.state_size, '__len__'): for state, dim in zip(self.states, self.cell.state_size): backend.set_value(state, np.zeros(get_tuple_shape(dim))) else: backend.set_value(self.states[0], np.zeros(get_tuple_shape(self.cell.state_size))) else: if not isinstance(states, (list, tuple)): states = [states] if len(states) != len(self.states): raise ValueError( f'Layer {self.name} expects {len(self.states)} states, ' f'but it received {len(states)} state values. ' f'States received: {states}') for index, (value, state) in enumerate(zip(states, self.states)): if hasattr(self.cell.state_size, '__len__'): dim = self.cell.state_size[index] else: dim = self.cell.state_size if value.shape != get_tuple_shape(dim): raise ValueError( f'State {index} is incompatible with layer {self.name}: ' f'expected shape={get_tuple_shape(dim)}, ' f'found shape={value.shape}') backend.set_value(state, value) class ConvLSTMCell(DropoutRNNCellMixin, Layer): """Cell class for the ConvLSTM layer. Args: rank: Integer, rank of the convolution, e.g. "2" for 2D convolutions. 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 n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. 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 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`. 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: An integer or tuple/list of n 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 (ie. "linear" activation: `a(x) = x`). recurrent_activation: Activation function to use for the recurrent step. use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015]( http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. kernel_constraint: Constraint function applied to the `kernel` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Call arguments: inputs: A (2+ `rank`)D tensor. states: List of state tensors corresponding to the previous timestep. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when `dropout` or `recurrent_dropout` is used. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0, **kwargs): super(ConvLSTMCell, self).__init__(**kwargs) self.rank = rank if self.rank > 3: raise ValueError(f'Rank {rank} convolutions are not currently ' f'implemented. Received: rank={rank}') self.filters = filters self.kernel_size = conv_utils.normalize_tuple(kernel_size, self.rank, 'kernel_size') self.strides = conv_utils.normalize_tuple(strides, self.rank, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.dilation_rate = conv_utils.normalize_tuple(dilation_rate, self.rank, 'dilation_rate') self.activation = activations.get(activation) self.recurrent_activation = activations.get(recurrent_activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.recurrent_initializer = initializers.get(recurrent_initializer) self.bias_initializer = initializers.get(bias_initializer) self.unit_forget_bias = unit_forget_bias self.kernel_regularizer = regularizers.get(kernel_regularizer) self.recurrent_regularizer = regularizers.get(recurrent_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.recurrent_constraint = constraints.get(recurrent_constraint) self.bias_constraint = constraints.get(bias_constraint) self.dropout = min(1.0, max(0.0, dropout)) self.recurrent_dropout = min(1.0, max(0.0, recurrent_dropout)) self.state_size = (self.filters, self.filters) def build(self, input_shape): if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 if input_shape[channel_axis] is None: raise ValueError( 'The channel dimension of the inputs (last axis) should be defined. ' f'Found None. Full input shape received: input_shape={input_shape}') input_dim = input_shape[channel_axis] self.kernel_shape = self.kernel_size + (input_dim, self.filters * 4) recurrent_kernel_shape = self.kernel_size + (self.filters, self.filters * 4) self.kernel = self.add_weight( shape=self.kernel_shape, initializer=self.kernel_initializer, name='kernel', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.recurrent_kernel = self.add_weight( shape=recurrent_kernel_shape, initializer=self.recurrent_initializer, name='recurrent_kernel', regularizer=self.recurrent_regularizer, constraint=self.recurrent_constraint) if self.use_bias: if self.unit_forget_bias: def bias_initializer(_, *args, **kwargs): return backend.concatenate([ self.bias_initializer((self.filters,), *args, **kwargs), initializers.get('ones')((self.filters,), *args, **kwargs), self.bias_initializer((self.filters * 2,), *args, **kwargs), ]) else: bias_initializer = self.bias_initializer self.bias = self.add_weight( shape=(self.filters * 4,), name='bias', initializer=bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None self.built = True def call(self, inputs, states, training=None): h_tm1 = states[0] # previous memory state c_tm1 = states[1] # previous carry state # dropout matrices for input units dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=4) # dropout matrices for recurrent units rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( h_tm1, training, count=4) if 0 < self.dropout < 1.: inputs_i = inputs * dp_mask[0] inputs_f = inputs * dp_mask[1] inputs_c = inputs * dp_mask[2] inputs_o = inputs * dp_mask[3] else: inputs_i = inputs inputs_f = inputs inputs_c = inputs inputs_o = inputs if 0 < self.recurrent_dropout < 1.: h_tm1_i = h_tm1 * rec_dp_mask[0] h_tm1_f = h_tm1 * rec_dp_mask[1] h_tm1_c = h_tm1 * rec_dp_mask[2] h_tm1_o = h_tm1 * rec_dp_mask[3] else: h_tm1_i = h_tm1 h_tm1_f = h_tm1 h_tm1_c = h_tm1 h_tm1_o = h_tm1 (kernel_i, kernel_f, kernel_c, kernel_o) = tf.split( self.kernel, 4, axis=self.rank + 1) (recurrent_kernel_i, recurrent_kernel_f, recurrent_kernel_c, recurrent_kernel_o) = tf.split( self.recurrent_kernel, 4, axis=self.rank + 1) if self.use_bias: bias_i, bias_f, bias_c, bias_o = tf.split(self.bias, 4) else: bias_i, bias_f, bias_c, bias_o = None, None, None, None x_i = self.input_conv(inputs_i, kernel_i, bias_i, padding=self.padding) x_f = self.input_conv(inputs_f, kernel_f, bias_f, padding=self.padding) x_c = self.input_conv(inputs_c, kernel_c, bias_c, padding=self.padding) x_o = self.input_conv(inputs_o, kernel_o, bias_o, padding=self.padding) h_i = self.recurrent_conv(h_tm1_i, recurrent_kernel_i) h_f = self.recurrent_conv(h_tm1_f, recurrent_kernel_f) h_c = self.recurrent_conv(h_tm1_c, recurrent_kernel_c) h_o = self.recurrent_conv(h_tm1_o, recurrent_kernel_o) i = self.recurrent_activation(x_i + h_i) f = self.recurrent_activation(x_f + h_f) c = f * c_tm1 + i * self.activation(x_c + h_c) o = self.recurrent_activation(x_o + h_o) h = o * self.activation(c) return h, [h, c] @property def _conv_func(self): if self.rank == 1: return backend.conv1d if self.rank == 2: return backend.conv2d if self.rank == 3: return backend.conv3d def input_conv(self, x, w, b=None, padding='valid'): conv_out = self._conv_func( x, w, strides=self.strides, padding=padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if b is not None: conv_out = backend.bias_add(conv_out, b, data_format=self.data_format) return conv_out def recurrent_conv(self, x, w): strides = conv_utils.normalize_tuple(1, self.rank, 'strides') conv_out = self._conv_func( x, w, strides=strides, padding='same', data_format=self.data_format) return conv_out def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'recurrent_activation': activations.serialize(self.recurrent_activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'unit_forget_bias': self.unit_forget_bias, 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'dropout': self.dropout, 'recurrent_dropout': self.recurrent_dropout, } base_config = super(ConvLSTMCell, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ConvLSTM(ConvRNN): """Abstract N-D Convolutional LSTM layer. (Used as implementation base) Similar to an LSTM layer, but the input transformations and recurrent transformations are both convolutional. Args: rank: Integer, rank of the convolution, e.g. "2" for 2D convolutions. 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 n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. 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 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, time, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, time, channels, ...)`. 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: An integer or tuple/list of n 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. By default hyperbolic tangent activation function is applied (`tanh(x)`). recurrent_activation: Activation function to use for the recurrent step. use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015]( http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to. kernel_constraint: Constraint function applied to the `kernel` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. (default False) return_state: Boolean Whether to return the last state in addition to the output. (default False) go_backwards: Boolean (default False). If True, process the input sequence backwards. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, dropout=0.0, recurrent_dropout=0.0, **kwargs): cell = ConvLSTMCell( rank=rank, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, dropout=dropout, recurrent_dropout=recurrent_dropout, dtype=kwargs.get('dtype')) super(ConvLSTM, self).__init__( rank, cell, return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, **kwargs) self.activity_regularizer = regularizers.get(activity_regularizer) def call(self, inputs, mask=None, training=None, initial_state=None): return super(ConvLSTM, self).call( inputs, mask=mask, training=training, initial_state=initial_state) @property def filters(self): return self.cell.filters @property def kernel_size(self): return self.cell.kernel_size @property def strides(self): return self.cell.strides @property def padding(self): return self.cell.padding @property def data_format(self): return self.cell.data_format @property def dilation_rate(self): return self.cell.dilation_rate @property def activation(self): return self.cell.activation @property def recurrent_activation(self): return self.cell.recurrent_activation @property def use_bias(self): return self.cell.use_bias @property def kernel_initializer(self): return self.cell.kernel_initializer @property def recurrent_initializer(self): return self.cell.recurrent_initializer @property def bias_initializer(self): return self.cell.bias_initializer @property def unit_forget_bias(self): return self.cell.unit_forget_bias @property def kernel_regularizer(self): return self.cell.kernel_regularizer @property def recurrent_regularizer(self): return self.cell.recurrent_regularizer @property def bias_regularizer(self): return self.cell.bias_regularizer @property def kernel_constraint(self): return self.cell.kernel_constraint @property def recurrent_constraint(self): return self.cell.recurrent_constraint @property def bias_constraint(self): return self.cell.bias_constraint @property def dropout(self): return self.cell.dropout @property def recurrent_dropout(self): return self.cell.recurrent_dropout def get_config(self): config = {'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'recurrent_activation': activations.serialize( self.recurrent_activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize( self.kernel_initializer), 'recurrent_initializer': initializers.serialize( self.recurrent_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'unit_forget_bias': self.unit_forget_bias, 'kernel_regularizer': regularizers.serialize( self.kernel_regularizer), 'recurrent_regularizer': regularizers.serialize( self.recurrent_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize( self.activity_regularizer), 'kernel_constraint': constraints.serialize( self.kernel_constraint), 'recurrent_constraint': constraints.serialize( self.recurrent_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'dropout': self.dropout, 'recurrent_dropout': self.recurrent_dropout} base_config = super(ConvLSTM, self).get_config() del base_config['cell'] return dict(list(base_config.items()) + list(config.items())) @classmethod def from_config(cls, config): return cls(**config) @keras_export('keras.layers.ConvLSTM1D') class ConvLSTM1D(ConvLSTM): """1D Convolutional LSTM. Similar to an LSTM layer, but the input transformations and recurrent transformations are both convolutional. 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 n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. 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 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, time, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, time, channels, ...)`. 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: An integer or tuple/list of n 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. By default hyperbolic tangent activation function is applied (`tanh(x)`). recurrent_activation: Activation function to use for the recurrent step. use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015]( http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to. kernel_constraint: Constraint function applied to the `kernel` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. (default False) return_state: Boolean Whether to return the last state in addition to the output. (default False) go_backwards: Boolean (default False). If True, process the input sequence backwards. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Call arguments: inputs: A 4D tensor. mask: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` are set. initial_state: List of initial state tensors to be passed to the first call of the cell. Input shape: - If data_format='channels_first' 4D tensor with shape: `(samples, time, channels, rows)` - If data_format='channels_last' 4D tensor with shape: `(samples, time, rows, channels)` Output shape: - If `return_state`: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each 3D tensor with shape: `(samples, filters, new_rows)` if data_format='channels_first' or shape: `(samples, new_rows, filters)` if data_format='channels_last'. `rows` values might have changed due to padding. - If `return_sequences`: 4D tensor with shape: `(samples, timesteps, filters, new_rows)` if data_format='channels_first' or shape: `(samples, timesteps, new_rows, filters)` if data_format='channels_last'. - Else, 3D tensor with shape: `(samples, filters, new_rows)` if data_format='channels_first' or shape: `(samples, new_rows, filters)` if data_format='channels_last'. Raises: ValueError: in case of invalid constructor arguments. References: - [Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) (the current implementation does not include the feedback loop on the cells output). """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, dropout=0.0, recurrent_dropout=0.0, **kwargs): super(ConvLSTM1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, dropout=dropout, recurrent_dropout=recurrent_dropout, **kwargs) @keras_export('keras.layers.ConvLSTM2D') class ConvLSTM2D(ConvLSTM): """2D Convolutional LSTM. Similar to an LSTM layer, but the input transformations and recurrent transformations are both convolutional. 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 n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. 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 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, time, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, time, channels, ...)`. 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: An integer or tuple/list of n 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. By default hyperbolic tangent activation function is applied (`tanh(x)`). recurrent_activation: Activation function to use for the recurrent step. use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015]( http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to. kernel_constraint: Constraint function applied to the `kernel` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. (default False) return_state: Boolean Whether to return the last state in addition to the output. (default False) go_backwards: Boolean (default False). If True, process the input sequence backwards. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Call arguments: inputs: A 5D tensor. mask: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` are set. initial_state: List of initial state tensors to be passed to the first call of the cell. Input shape: - If data_format='channels_first' 5D tensor with shape: `(samples, time, channels, rows, cols)` - If data_format='channels_last' 5D tensor with shape: `(samples, time, rows, cols, channels)` Output shape: - If `return_state`: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if data_format='channels_first' or shape: `(samples, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. - If `return_sequences`: 5D tensor with shape: `(samples, timesteps, filters, new_rows, new_cols)` if data_format='channels_first' or shape: `(samples, timesteps, new_rows, new_cols, filters)` if data_format='channels_last'. - Else, 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if data_format='channels_first' or shape: `(samples, new_rows, new_cols, filters)` if data_format='channels_last'. Raises: ValueError: in case of invalid constructor arguments. References: - [Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) (the current implementation does not include the feedback loop on the cells output). """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, dropout=0.0, recurrent_dropout=0.0, **kwargs): super(ConvLSTM2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, dropout=dropout, recurrent_dropout=recurrent_dropout, **kwargs) @keras_export('keras.layers.ConvLSTM3D') class ConvLSTM3D(ConvLSTM): """3D Convolutional LSTM. Similar to an LSTM layer, but the input transformations and recurrent transformations are both convolutional. 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 n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. 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 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, time, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, time, channels, ...)`. 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: An integer or tuple/list of n 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. By default hyperbolic tangent activation function is applied (`tanh(x)`). recurrent_activation: Activation function to use for the recurrent step. use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. bias_initializer: Initializer for the bias vector. unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at initialization. Use in combination with `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015]( http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to. kernel_constraint: Constraint function applied to the `kernel` weights matrix. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. (default False) return_state: Boolean Whether to return the last state in addition to the output. (default False) go_backwards: Boolean (default False). If True, process the input sequence backwards. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Call arguments: inputs: A 6D tensor. mask: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` are set. initial_state: List of initial state tensors to be passed to the first call of the cell. Input shape: - If data_format='channels_first' 6D tensor with shape: `(samples, time, channels, rows, cols, depth)` - If data_format='channels_last' 5D tensor with shape: `(samples, time, rows, cols, depth, channels)` Output shape: - If `return_state`: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each 5D tensor with shape: `(samples, filters, new_rows, new_cols, new_depth)` if data_format='channels_first' or shape: `(samples, new_rows, new_cols, new_depth, filters)` if data_format='channels_last'. `rows`, `cols`, and `depth` values might have changed due to padding. - If `return_sequences`: 6D tensor with shape: `(samples, timesteps, filters, new_rows, new_cols, new_depth)` if data_format='channels_first' or shape: `(samples, timesteps, new_rows, new_cols, new_depth, filters)` if data_format='channels_last'. - Else, 5D tensor with shape: `(samples, filters, new_rows, new_cols, new_depth)` if data_format='channels_first' or shape: `(samples, new_rows, new_cols, new_depth, filters)` if data_format='channels_last'. Raises: ValueError: in case of invalid constructor arguments. References: - [Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) (the current implementation does not include the feedback loop on the cells output). """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, return_sequences=False, return_state=False, go_backwards=False, stateful=False, dropout=0.0, recurrent_dropout=0.0, **kwargs): super(ConvLSTM3D, self).__init__( rank=3, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, dropout=dropout, recurrent_dropout=recurrent_dropout, **kwargs)
63,142
42.101024
95
py
keras
keras-master/keras/layers/subclassed_layers_test.py
# 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 Keras subclassed layers utilizing desired user syntax.""" import tensorflow.compat.v2 as tf import keras from keras import keras_parameterized from keras import testing_utils from keras.utils import tf_utils @keras_parameterized.run_all_keras_modes @keras_parameterized.run_with_all_model_types class SubclassedLayersTest(keras_parameterized.TestCase): def test_simple_build_with_constant(self): class BuildConstantLayer(keras.layers.Layer): def build(self, input_shape): self.b = tf.convert_to_tensor(2.0) def call(self, inputs): return self.b * inputs layer = BuildConstantLayer() model = testing_utils.get_model_from_layers( [layer, keras.layers.Dense(1)], input_shape=(1,)) x = tf.convert_to_tensor([[3.0]]) self.assertEqual( tf_utils.is_symbolic_tensor(model(x)), not tf.executing_eagerly()) self.assertEqual( tf_utils.is_symbolic_tensor(layer(x)), not tf.executing_eagerly()) self.assertAllClose(keras.backend.get_value(layer(x)), [[6.0]]) def test_build_with_derived_constant(self): class BuildDerivedConstantLayer(keras.layers.Layer): def build(self, input_shape): a = tf.convert_to_tensor(1.0) b = 2.0 * a self.variable = tf.Variable(b) self.constant = tf.convert_to_tensor(self.variable) def call(self, inputs): return self.variable * self.constant * inputs layer = BuildDerivedConstantLayer() model = testing_utils.get_model_from_layers( [layer, keras.layers.Dense(1)], input_shape=(1,)) x = tf.convert_to_tensor([[3.0]]) self.assertEqual( tf_utils.is_symbolic_tensor(model(x)), not tf.executing_eagerly()) self.assertEqual( tf_utils.is_symbolic_tensor(layer(x)), not tf.executing_eagerly()) self.assertAllClose(keras.backend.get_value(layer(x)), [[12.0]]) if __name__ == '__main__': tf.test.main()
2,620
33.038961
80
py
keras
keras-master/keras/layers/recurrent_v2.py
# 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. # ============================================================================== # pylint: disable=g-classes-have-attributes """Recurrent layers for TF 2.""" import tensorflow.compat.v2 as tf import uuid from tensorflow.python.eager.context import get_device_name from keras import activations from keras import backend from keras.engine.input_spec import InputSpec from keras.layers import recurrent from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import keras_export # The following string constants are used by Defun approach for unified backend # of LSTM and GRU. _FUNCTION_API_NAME_ATTRIBUTE = 'api_implements' _FUNCTION_DEVICE_ATTRIBUTE = 'api_preferred_device' _CPU_DEVICE_NAME = 'CPU' _GPU_DEVICE_NAME = 'GPU' # The following number constants are used to represent the runtime of the defun # backend function. Since the CPU/GPU implementation are mathematically same, we # need some signal for the function to indicate which function is executed. This # is for testing purpose to verify the correctness of swapping backend function. _RUNTIME_UNKNOWN = 0 _RUNTIME_CPU = 1 _RUNTIME_GPU = 2 _CUDNN_AVAILABLE_MSG = 'Layer %s will use cuDNN kernels when running on GPU.' _CUDNN_NOT_AVAILABLE_MSG = ('Layer %s will not use cuDNN kernels since it ' 'doesn\'t meet the criteria. It will ' 'use a generic GPU kernel as fallback when running ' 'on GPU.') def _use_new_code(): return False # TODO(b/169707691): The wrapper can be removed if TFLite doesn't need to rely # on supportive attributes from LSTM/GRU. class _DefunWrapper: """A wrapper with no deep copy of the Defun in LSTM/GRU layer.""" def __init__(self, time_major, go_backwards, layer_name): self.time_major = time_major self.go_backwards = go_backwards self.layer_name = layer_name if self.layer_name not in ['lstm', 'gru']: raise ValueError('Defun wrapper only applies to LSTM and GRU layer, ' 'but given {}'.format(self.layer_name)) # The first two attributes are added to support TFLite use case. supportive_attributes = { 'time_major': self.time_major, 'go_backwards': self.go_backwards, _FUNCTION_API_NAME_ATTRIBUTE: self.layer_name + '_' + str(uuid.uuid4()) } if self.layer_name == 'lstm': layer_func = lstm_with_backend_selection else: layer_func = gru_with_backend_selection self.defun_layer = tf.__internal__.function.defun_with_attributes( layer_func, attributes=supportive_attributes, autograph=False) def __deepcopy__(self, memo): new_wrapper = type(self)( self.time_major, self.go_backwards, self.layer_name) memo[id(self)] = new_wrapper return new_wrapper @keras_export('keras.layers.GRUCell', v1=[]) class GRUCell(recurrent.GRUCell): """Cell class for the GRU layer. See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) for details about the usage of RNN API. This class processes one step within the whole time sequence input, whereas `tf.keras.layer.GRU` processes the whole sequence. For example: >>> inputs = tf.random.normal([32, 10, 8]) >>> rnn = tf.keras.layers.RNN(tf.keras.layers.GRUCell(4)) >>> output = rnn(inputs) >>> print(output.shape) (32, 4) >>> rnn = tf.keras.layers.RNN( ... tf.keras.layers.GRUCell(4), ... return_sequences=True, ... return_state=True) >>> whole_sequence_output, final_state = rnn(inputs) >>> print(whole_sequence_output.shape) (32, 10, 4) >>> print(final_state.shape) (32, 4) Args: units: Positive integer, dimensionality of the output space. activation: Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass None, no activation is applied (ie. "linear" activation: `a(x) = x`). recurrent_activation: Activation function to use for the recurrent step. Default: sigmoid (`sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, (default `True`), whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. Default: `glorot_uniform`. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. Default: `orthogonal`. bias_initializer: Initializer for the bias vector. Default: `zeros`. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. Default: `None`. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_regularizer: Regularizer function applied to the bias vector. Default: `None`. kernel_constraint: Constraint function applied to the `kernel` weights matrix. Default: `None`. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_constraint: Constraint function applied to the bias vector. Default: `None`. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. reset_after: GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before", True = "after" (default and cuDNN compatible). Call arguments: inputs: A 2D tensor, with shape of `[batch, feature]`. states: A 2D tensor with shape of `[batch, units]`, which is the state from the previous time step. For timestep 0, the initial state provided by user will be feed to cell. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when `dropout` or `recurrent_dropout` is used. """ def __init__(self, units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0., recurrent_dropout=0., reset_after=True, **kwargs): super(GRUCell, self).__init__( units, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, dropout=dropout, recurrent_dropout=recurrent_dropout, implementation=kwargs.pop('implementation', 2), reset_after=reset_after, **kwargs) @keras_export('keras.layers.GRU', v1=[]) class GRU(recurrent.DropoutRNNCellMixin, recurrent.GRU): """Gated Recurrent Unit - Cho et al. 2014. See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) for details about the usage of RNN API. Based on available runtime hardware and constraints, this layer will choose different implementations (cuDNN-based or pure-TensorFlow) to maximize the performance. If a GPU is available and all the arguments to the layer meet the requirement of the cuDNN kernel (see below for details), the layer will use a fast cuDNN implementation. The requirements to use the cuDNN implementation are: 1. `activation` == `tanh` 2. `recurrent_activation` == `sigmoid` 3. `recurrent_dropout` == 0 4. `unroll` is `False` 5. `use_bias` is `True` 6. `reset_after` is `True` 7. Inputs, if use masking, are strictly right-padded. 8. Eager execution is enabled in the outermost context. There are two variants of the GRU implementation. The default one is based on [v3](https://arxiv.org/abs/1406.1078v3) and has reset gate applied to hidden state before matrix multiplication. The other one is based on [original](https://arxiv.org/abs/1406.1078v1) and has the order reversed. The second variant is compatible with CuDNNGRU (GPU-only) and allows inference on CPU. Thus it has separate biases for `kernel` and `recurrent_kernel`. To use this variant, set `reset_after=True` and `recurrent_activation='sigmoid'`. For example: >>> inputs = tf.random.normal([32, 10, 8]) >>> gru = tf.keras.layers.GRU(4) >>> output = gru(inputs) >>> print(output.shape) (32, 4) >>> gru = tf.keras.layers.GRU(4, return_sequences=True, return_state=True) >>> whole_sequence_output, final_state = gru(inputs) >>> print(whole_sequence_output.shape) (32, 10, 4) >>> print(final_state.shape) (32, 4) Args: units: Positive integer, dimensionality of the output space. activation: Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). recurrent_activation: Activation function to use for the recurrent step. Default: sigmoid (`sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, (default `True`), whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. Default: `glorot_uniform`. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. Default: `orthogonal`. bias_initializer: Initializer for the bias vector. Default: `zeros`. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. Default: `None`. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_regularizer: Regularizer function applied to the bias vector. Default: `None`. activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). Default: `None`. kernel_constraint: Constraint function applied to the `kernel` weights matrix. Default: `None`. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_constraint: Constraint function applied to the bias vector. Default: `None`. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. Default: `False`. return_state: Boolean. Whether to return the last state in addition to the output. Default: `False`. go_backwards: Boolean (default `False`). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. unroll: Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. time_major: The shape format of the `inputs` and `outputs` tensors. If True, the inputs and outputs will be in shape `[timesteps, batch, feature]`, whereas in the False case, it will be `[batch, timesteps, feature]`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. reset_after: GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before", True = "after" (default and cuDNN compatible). Call arguments: inputs: A 3D tensor, with shape `[batch, timesteps, feature]`. mask: Binary tensor of shape `[samples, timesteps]` indicating whether a given timestep should be masked (optional, defaults to `None`). An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` is used (optional, defaults to `None`). initial_state: List of initial state tensors to be passed to the first call of the cell (optional, defaults to `None` which causes creation of zero-filled initial state tensors). """ def __init__(self, units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0., recurrent_dropout=0., return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, time_major=False, reset_after=True, **kwargs): # return_runtime is a flag for testing, which shows the real backend # implementation chosen by grappler in graph mode. self._return_runtime = kwargs.pop('return_runtime', False) super(GRU, self).__init__( units, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, dropout=dropout, recurrent_dropout=recurrent_dropout, implementation=kwargs.pop('implementation', 2), return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, unroll=unroll, time_major=time_major, reset_after=reset_after, **kwargs) # GPU kernel uses following setting by default and not configurable. self._could_use_gpu_kernel = ( self.activation in (activations.tanh, tf.tanh) and self.recurrent_activation in (activations.sigmoid, tf.sigmoid) and recurrent_dropout == 0 and not unroll and use_bias and reset_after and tf.compat.v1.executing_eagerly_outside_functions()) if tf.config.list_logical_devices('GPU'): # Only show the message when there is GPU available, user will not care # about the cuDNN if there isn't any GPU. if self._could_use_gpu_kernel: logging.debug(_CUDNN_AVAILABLE_MSG % self.name) else: logging.warning(_CUDNN_NOT_AVAILABLE_MSG % self.name) if _use_new_code(): self._defun_wrapper = _DefunWrapper(time_major, go_backwards, 'gru') def call(self, inputs, mask=None, training=None, initial_state=None): # The input should be dense, padded with zeros. If a ragged input is fed # into the layer, it is padded and the row lengths are used for masking. inputs, row_lengths = backend.convert_inputs_if_ragged(inputs) is_ragged_input = (row_lengths is not None) self._validate_args_if_ragged(is_ragged_input, mask) # GRU does not support constants. Ignore it during process. inputs, initial_state, _ = self._process_inputs(inputs, initial_state, None) if isinstance(mask, list): mask = mask[0] input_shape = backend.int_shape(inputs) timesteps = input_shape[0] if self.time_major else input_shape[1] # TODO(b/156447398) Investigate why the cuDNN kernel fails with ragged # inputs. if is_ragged_input or not self._could_use_gpu_kernel: kwargs = {'training': training} self._maybe_reset_cell_dropout_mask(self.cell) def step(cell_inputs, cell_states): return self.cell(cell_inputs, cell_states, **kwargs) last_output, outputs, states = backend.rnn( step, inputs, initial_state, constants=None, go_backwards=self.go_backwards, mask=mask, unroll=self.unroll, input_length=row_lengths if row_lengths is not None else timesteps, time_major=self.time_major, zero_output_for_mask=self.zero_output_for_mask) # This is a dummy tensor for testing purpose. runtime = _runtime(_RUNTIME_UNKNOWN) else: last_output, outputs, runtime, states = self._defun_gru_call( inputs, initial_state, training, mask, row_lengths) if self.stateful: updates = [tf.compat.v1.assign(self.states[0], states[0])] self.add_update(updates) if self.return_sequences: output = backend.maybe_convert_to_ragged( is_ragged_input, outputs, row_lengths, go_backwards=self.go_backwards) else: output = last_output if self.return_state: return [output] + list(states) elif self._return_runtime: return output, runtime else: return output def _defun_gru_call(self, inputs, initial_state, training, mask, sequence_lengths): # Use the new defun approach for backend implementation swap. # Note that different implementations need to have same function # signature, eg, the tensor parameters need to have same shape and dtypes. self.reset_dropout_mask() dropout_mask = self.get_dropout_mask_for_cell(inputs, training, count=3) if dropout_mask is not None: inputs = inputs * dropout_mask[0] if _use_new_code(): gru_kwargs = { 'inputs': inputs, 'init_h': _read_variable_value(initial_state[0]), 'kernel': _read_variable_value(self.cell.kernel), 'recurrent_kernel': _read_variable_value(self.cell.recurrent_kernel), 'bias': _read_variable_value(self.cell.bias), 'mask': mask, 'time_major': self.time_major, 'go_backwards': self.go_backwards, 'sequence_lengths': sequence_lengths, 'zero_output_for_mask': self.zero_output_for_mask } (last_output, outputs, new_h, runtime) = self._defun_wrapper.defun_layer(**gru_kwargs) else: gpu_gru_kwargs = { 'inputs': inputs, 'init_h': _read_variable_value(initial_state[0]), 'kernel': _read_variable_value(self.cell.kernel), 'recurrent_kernel': _read_variable_value(self.cell.recurrent_kernel), 'bias': _read_variable_value(self.cell.bias), 'mask': mask, 'time_major': self.time_major, 'go_backwards': self.go_backwards, 'sequence_lengths': sequence_lengths } normal_gru_kwargs = gpu_gru_kwargs.copy() normal_gru_kwargs.update({ 'zero_output_for_mask': self.zero_output_for_mask, }) if tf.executing_eagerly(): device_type = _get_context_device_type() can_use_gpu = ( # Either user specified GPU or unspecified but GPU is available. (device_type == _GPU_DEVICE_NAME or (device_type is None and tf.config.list_logical_devices('GPU'))) and (mask is None or is_cudnn_supported_inputs(mask, self.time_major))) # Under eager context, check the device placement and prefer the if can_use_gpu: last_output, outputs, new_h, runtime = gpu_gru(**gpu_gru_kwargs) else: last_output, outputs, new_h, runtime = standard_gru( **normal_gru_kwargs) else: last_output, outputs, new_h, runtime = gru_with_backend_selection( **normal_gru_kwargs) states = [new_h] return last_output, outputs, runtime, states def standard_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """GRU with standard kernel implementation. This implementation can be run on all types of hardware. This implementation lifts out all the layer weights and make them function parameters. It has same number of tensor input params as the cuDNN counterpart. The RNN step logic has been simplified, eg dropout and mask is removed since cuDNN implementation does not support that. Args: inputs: Input tensor of GRU layer. init_h: Initial state tensor for the cell output. kernel: Weights for cell kernel. recurrent_kernel: Weights for cell recurrent kernel. bias: Weights for cell kernel bias and recurrent bias. The bias contains the combined input_bias and recurrent_bias. mask: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. time_major: Boolean, whether the inputs are in the format of [time, batch, feature] or [batch, time, feature]. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. sequence_lengths: The lengths of all sequences coming from a variable length input, such as ragged tensors. If the input has a fixed timestep size, this should be None. zero_output_for_mask: Boolean, whether to output zero for masked timestep. Returns: last_output: output tensor for the last timestep, which has shape [batch, units]. outputs: output tensor for all timesteps, which has shape [batch, time, units]. state_0: the cell output, which has same shape as init_h. runtime: constant string tensor which indicate real runtime hardware. This value is for testing purpose and should be used by user. """ input_shape = backend.int_shape(inputs) timesteps = input_shape[0] if time_major else input_shape[1] input_bias, recurrent_bias = tf.unstack(bias) def step(cell_inputs, cell_states): """Step function that will be used by Keras RNN backend.""" h_tm1 = cell_states[0] # inputs projected by all gate matrices at once matrix_x = backend.dot(cell_inputs, kernel) matrix_x = backend.bias_add(matrix_x, input_bias) x_z, x_r, x_h = tf.split(matrix_x, 3, axis=1) # hidden state projected by all gate matrices at once matrix_inner = backend.dot(h_tm1, recurrent_kernel) matrix_inner = backend.bias_add(matrix_inner, recurrent_bias) recurrent_z, recurrent_r, recurrent_h = tf.split(matrix_inner, 3, axis=1) z = tf.sigmoid(x_z + recurrent_z) r = tf.sigmoid(x_r + recurrent_r) hh = tf.tanh(x_h + r * recurrent_h) # previous and candidate state mixed by update gate h = z * h_tm1 + (1 - z) * hh return h, [h] last_output, outputs, new_states = backend.rnn( step, inputs, [init_h], constants=None, unroll=False, time_major=time_major, mask=mask, go_backwards=go_backwards, input_length=sequence_lengths if sequence_lengths is not None else timesteps, zero_output_for_mask=zero_output_for_mask) return last_output, outputs, new_states[0], _runtime(_RUNTIME_CPU) def gpu_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths): """GRU with cuDNN implementation which is only available for GPU.""" if not time_major and mask is None: inputs = tf.transpose(inputs, perm=(1, 0, 2)) seq_axis, batch_axis = (0, 1) else: seq_axis, batch_axis = (0, 1) if time_major else (1, 0) # For init_h, cuDNN expects one more dim of num_layers before or after batch # dim for time major or batch major inputs respectively init_h = tf.expand_dims(init_h, axis=seq_axis) weights = tf.split(kernel, 3, axis=1) weights += tf.split(recurrent_kernel, 3, axis=1) # Note that the bias was initialized as shape (2, 3 * units), flat it into # (6 * units) bias = tf.split(backend.flatten(bias), 6) if tf.sysconfig.get_build_info()['is_cuda_build']: # Note that the gate order for cuDNN is different from the canonical format. # canonical format is [z, r, h], whereas cuDNN is [r, z, h]. The swap need # to be done for kernel, recurrent_kernel, input_bias, recurrent_bias. # z is update gate weights. # r is reset gate weights. # h is output gate weights. weights[0], weights[1] = weights[1], weights[0] weights[3], weights[4] = weights[4], weights[3] bias[0], bias[1] = bias[1], bias[0] bias[3], bias[4] = bias[4], bias[3] params = _canonical_to_params( weights=weights, biases=bias, shape=tf.constant([-1]), transpose_weights=True) if mask is not None: sequence_lengths = calculate_sequence_by_mask(mask, time_major) if sequence_lengths is not None: if go_backwards: # Three reversals are required. E.g., # normal input = [1, 2, 3, 0, 0] # where 0 need to be masked # reversed_input_to_cudnn = [3, 2, 1, 0, 0] # output_from_cudnn = [6, 5, 4, 0, 0] # expected_output = [0, 0, 6, 5 ,4] inputs = tf.reverse_sequence( inputs, sequence_lengths, seq_axis=seq_axis, batch_axis=batch_axis) outputs, h, _, _, _ = tf.raw_ops.CudnnRNNV3( input=inputs, input_h=init_h, input_c=0, params=params, is_training=True, rnn_mode='gru', sequence_lengths=sequence_lengths, time_major=time_major) if go_backwards: outputs = tf.reverse_sequence( outputs, sequence_lengths, seq_axis=seq_axis, batch_axis=batch_axis) outputs = tf.reverse(outputs, axis=[seq_axis]) else: if go_backwards: # Reverse axis 0 since the input is already convert to time major. inputs = tf.reverse(inputs, axis=[0]) outputs, h, _, _ = tf.raw_ops.CudnnRNN( input=inputs, input_h=init_h, input_c=0, params=params, is_training=True, rnn_mode='gru') last_output = outputs[-1] if not time_major and mask is None: outputs = tf.transpose(outputs, perm=[1, 0, 2]) h = tf.squeeze(h, axis=seq_axis) # In the case of variable length input, the cudnn kernel will fill zeros for # the output, whereas the default keras behavior is to bring over the previous # output for t-1, so that in the return_sequence=False case, user can quickly # get the final effect output instead just 0s at the last timestep. # In order to mimic the default keras behavior, we copy the final h state as # the last_output, since it is numerically same as the output. if mask is not None: last_output = h return last_output, outputs, h, _runtime(_RUNTIME_GPU) def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """Call the GRU with optimized backend kernel selection. Under the hood, this function will create two TF function, one with the most generic kernel and can run on all device condition, and the second one with cuDNN specific kernel, which can only run on GPU. The first function will be called with normal_lstm_params, while the second function is not called, but only registered in the graph. The Grappler will do the proper graph rewrite and swap the optimized TF function based on the device placement. Args: inputs: Input tensor of GRU layer. init_h: Initial state tensor for the cell output. kernel: Weights for cell kernel. recurrent_kernel: Weights for cell recurrent kernel. bias: Weights for cell kernel bias and recurrent bias. Only recurrent bias is used in this case. mask: Boolean tensor for mask out the steps within sequence. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. time_major: Boolean, whether the inputs are in the format of [time, batch, feature] or [batch, time, feature]. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. sequence_lengths: The lengths of all sequences coming from a variable length input, such as ragged tensors. If the input has a fixed timestep size, this should be None. zero_output_for_mask: Boolean, whether to output zero for masked timestep. Returns: List of output tensors, same as standard_gru. """ params = { 'inputs': inputs, 'init_h': init_h, 'kernel': kernel, 'recurrent_kernel': recurrent_kernel, 'bias': bias, 'mask': mask, 'time_major': time_major, 'go_backwards': go_backwards, 'sequence_lengths': sequence_lengths, 'zero_output_for_mask': zero_output_for_mask, } def gpu_gru_with_fallback(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """Use cuDNN kernel when mask is none or strictly right padded.""" if mask is None: return gpu_gru( inputs=inputs, init_h=init_h, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths) def cudnn_gru_fn(): return gpu_gru( inputs=inputs, init_h=init_h, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths) def standard_gru_fn(): return standard_gru( inputs=inputs, init_h=init_h, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths, zero_output_for_mask=zero_output_for_mask) return tf.cond( is_cudnn_supported_inputs(mask, time_major), true_fn=cudnn_gru_fn, false_fn=standard_gru_fn) if _use_new_code(): # Chooses the implementation dynamically based on the running device. (last_output, outputs, new_h, runtime) = tf.__internal__.execute_fn_for_device( { _CPU_DEVICE_NAME: lambda: standard_gru(**params), _GPU_DEVICE_NAME: lambda: gpu_gru_with_fallback(**params) }, lambda: standard_gru(**params)) else: # Each time a `tf.function` is called, we will give it a unique # identifiable API name, so that Grappler won't get confused when it # sees multiple GRU layers added into same graph, and it will be able # to pair up the different implementations across them. api_name = 'gru_' + str(uuid.uuid4()) supportive_attribute = { 'time_major': time_major, 'go_backwards': go_backwards, } defun_standard_gru = _generate_defun_backend(api_name, _CPU_DEVICE_NAME, standard_gru, supportive_attribute) defun_gpu_gru = _generate_defun_backend(api_name, _GPU_DEVICE_NAME, gpu_gru_with_fallback, supportive_attribute) # Call the normal GRU impl and register the cuDNN impl function. The # grappler will kick in during session execution to optimize the graph. last_output, outputs, new_h, runtime = defun_standard_gru(**params) _function_register(defun_gpu_gru, **params) return last_output, outputs, new_h, runtime @keras_export('keras.layers.LSTMCell', v1=[]) class LSTMCell(recurrent.LSTMCell): """Cell class for the LSTM layer. See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) for details about the usage of RNN API. This class processes one step within the whole time sequence input, whereas `tf.keras.layer.LSTM` processes the whole sequence. For example: >>> inputs = tf.random.normal([32, 10, 8]) >>> rnn = tf.keras.layers.RNN(tf.keras.layers.LSTMCell(4)) >>> output = rnn(inputs) >>> print(output.shape) (32, 4) >>> rnn = tf.keras.layers.RNN( ... tf.keras.layers.LSTMCell(4), ... return_sequences=True, ... return_state=True) >>> whole_seq_output, final_memory_state, final_carry_state = rnn(inputs) >>> print(whole_seq_output.shape) (32, 10, 4) >>> print(final_memory_state.shape) (32, 4) >>> print(final_carry_state.shape) (32, 4) Args: units: Positive integer, dimensionality of the output space. activation: Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). recurrent_activation: Activation function to use for the recurrent step. Default: sigmoid (`sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, (default `True`), whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. Default: `glorot_uniform`. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. Default: `orthogonal`. bias_initializer: Initializer for the bias vector. Default: `zeros`. unit_forget_bias: Boolean (default `True`). If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. Default: `None`. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_regularizer: Regularizer function applied to the bias vector. Default: `None`. kernel_constraint: Constraint function applied to the `kernel` weights matrix. Default: `None`. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_constraint: Constraint function applied to the bias vector. Default: `None`. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. Call arguments: inputs: A 2D tensor, with shape of `[batch, feature]`. states: List of 2 tensors that corresponding to the cell's units. Both of them have shape `[batch, units]`, the first tensor is the memory state from previous time step, the second tensor is the carry state from previous time step. For timestep 0, the initial state provided by user will be feed to cell. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when `dropout` or `recurrent_dropout` is used. """ def __init__(self, units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0., recurrent_dropout=0., **kwargs): super(LSTMCell, self).__init__( units, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, dropout=dropout, recurrent_dropout=recurrent_dropout, implementation=kwargs.pop('implementation', 2), **kwargs) @keras_export('keras.layers.LSTM', v1=[]) class LSTM(recurrent.DropoutRNNCellMixin, recurrent.LSTM): """Long Short-Term Memory layer - Hochreiter 1997. See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) for details about the usage of RNN API. Based on available runtime hardware and constraints, this layer will choose different implementations (cuDNN-based or pure-TensorFlow) to maximize the performance. If a GPU is available and all the arguments to the layer meet the requirement of the cuDNN kernel (see below for details), the layer will use a fast cuDNN implementation. The requirements to use the cuDNN implementation are: 1. `activation` == `tanh` 2. `recurrent_activation` == `sigmoid` 3. `recurrent_dropout` == 0 4. `unroll` is `False` 5. `use_bias` is `True` 6. Inputs, if use masking, are strictly right-padded. 7. Eager execution is enabled in the outermost context. For example: >>> inputs = tf.random.normal([32, 10, 8]) >>> lstm = tf.keras.layers.LSTM(4) >>> output = lstm(inputs) >>> print(output.shape) (32, 4) >>> lstm = tf.keras.layers.LSTM(4, return_sequences=True, return_state=True) >>> whole_seq_output, final_memory_state, final_carry_state = lstm(inputs) >>> print(whole_seq_output.shape) (32, 10, 4) >>> print(final_memory_state.shape) (32, 4) >>> print(final_carry_state.shape) (32, 4) Args: units: Positive integer, dimensionality of the output space. activation: Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). recurrent_activation: Activation function to use for the recurrent step. Default: sigmoid (`sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean (default `True`), whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. Default: `glorot_uniform`. recurrent_initializer: Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. Default: `orthogonal`. bias_initializer: Initializer for the bias vector. Default: `zeros`. unit_forget_bias: Boolean (default `True`). If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. Default: `None`. recurrent_regularizer: Regularizer function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_regularizer: Regularizer function applied to the bias vector. Default: `None`. activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). Default: `None`. kernel_constraint: Constraint function applied to the `kernel` weights matrix. Default: `None`. recurrent_constraint: Constraint function applied to the `recurrent_kernel` weights matrix. Default: `None`. bias_constraint: Constraint function applied to the bias vector. Default: `None`. dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. return_sequences: Boolean. Whether to return the last output. in the output sequence, or the full sequence. Default: `False`. return_state: Boolean. Whether to return the last state in addition to the output. Default: `False`. go_backwards: Boolean (default `False`). If True, process the input sequence backwards and return the reversed sequence. stateful: Boolean (default `False`). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. time_major: The shape format of the `inputs` and `outputs` tensors. If True, the inputs and outputs will be in shape `[timesteps, batch, feature]`, whereas in the False case, it will be `[batch, timesteps, feature]`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. unroll: Boolean (default `False`). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. Call arguments: inputs: A 3D tensor with shape `[batch, timesteps, feature]`. mask: Binary tensor of shape `[batch, timesteps]` indicating whether a given timestep should be masked (optional, defaults to `None`). An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` is used (optional, defaults to `None`). initial_state: List of initial state tensors to be passed to the first call of the cell (optional, defaults to `None` which causes creation of zero-filled initial state tensors). """ def __init__(self, units, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0., recurrent_dropout=0., return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False, **kwargs): # return_runtime is a flag for testing, which shows the real backend # implementation chosen by grappler in graph mode. self.return_runtime = kwargs.pop('return_runtime', False) super(LSTM, self).__init__( units, activation=activation, recurrent_activation=recurrent_activation, use_bias=use_bias, kernel_initializer=kernel_initializer, recurrent_initializer=recurrent_initializer, bias_initializer=bias_initializer, unit_forget_bias=unit_forget_bias, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, recurrent_constraint=recurrent_constraint, bias_constraint=bias_constraint, dropout=dropout, recurrent_dropout=recurrent_dropout, implementation=kwargs.pop('implementation', 2), return_sequences=return_sequences, return_state=return_state, go_backwards=go_backwards, stateful=stateful, time_major=time_major, unroll=unroll, **kwargs) self.state_spec = [ InputSpec(shape=(None, dim)) for dim in (self.units, self.units) ] self._could_use_gpu_kernel = ( self.activation in (activations.tanh, tf.tanh) and self.recurrent_activation in (activations.sigmoid, tf.sigmoid) and recurrent_dropout == 0 and not unroll and use_bias and tf.compat.v1.executing_eagerly_outside_functions()) if tf.config.list_logical_devices('GPU'): # Only show the message when there is GPU available, user will not care # about the cuDNN if there isn't any GPU. if self._could_use_gpu_kernel: logging.debug(_CUDNN_AVAILABLE_MSG % self.name) else: logging.warning(_CUDNN_NOT_AVAILABLE_MSG % self.name) if _use_new_code(): self._defun_wrapper = _DefunWrapper(time_major, go_backwards, 'lstm') def call(self, inputs, mask=None, training=None, initial_state=None): # The input should be dense, padded with zeros. If a ragged input is fed # into the layer, it is padded and the row lengths are used for masking. inputs, row_lengths = backend.convert_inputs_if_ragged(inputs) is_ragged_input = (row_lengths is not None) self._validate_args_if_ragged(is_ragged_input, mask) # LSTM does not support constants. Ignore it during process. inputs, initial_state, _ = self._process_inputs(inputs, initial_state, None) if isinstance(mask, list): mask = mask[0] input_shape = backend.int_shape(inputs) timesteps = input_shape[0] if self.time_major else input_shape[1] # TODO(b/156447398) Investigate why the cuDNN kernel fails with ragged # inputs. if is_ragged_input or not self._could_use_gpu_kernel: # Fall back to use the normal LSTM. kwargs = {'training': training} self._maybe_reset_cell_dropout_mask(self.cell) def step(inputs, states): return self.cell(inputs, states, **kwargs) last_output, outputs, states = backend.rnn( step, inputs, initial_state, constants=None, go_backwards=self.go_backwards, mask=mask, unroll=self.unroll, input_length=row_lengths if row_lengths is not None else timesteps, time_major=self.time_major, zero_output_for_mask=self.zero_output_for_mask) runtime = _runtime(_RUNTIME_UNKNOWN) else: # Use the new defun approach for backend implementation swap. # Note that different implementations need to have same function # signature, eg, the tensor parameters need to have same shape and dtypes. # Since the cuDNN has an extra set of bias, those bias will be passed to # both normal and cuDNN implementations. self.reset_dropout_mask() dropout_mask = self.get_dropout_mask_for_cell(inputs, training, count=4) if dropout_mask is not None: inputs = inputs * dropout_mask[0] if _use_new_code(): lstm_kwargs = { 'inputs': inputs, 'init_h': _read_variable_value(initial_state[0]), 'init_c': _read_variable_value(initial_state[1]), 'kernel': _read_variable_value(self.cell.kernel), 'recurrent_kernel': _read_variable_value(self.cell.recurrent_kernel), 'bias': _read_variable_value(self.cell.bias), 'mask': mask, 'time_major': self.time_major, 'go_backwards': self.go_backwards, 'sequence_lengths': row_lengths, 'zero_output_for_mask': self.zero_output_for_mask, } (last_output, outputs, new_h, new_c, runtime) = self._defun_wrapper.defun_layer(**lstm_kwargs) else: gpu_lstm_kwargs = { 'inputs': inputs, 'init_h': _read_variable_value(initial_state[0]), 'init_c': _read_variable_value(initial_state[1]), 'kernel': _read_variable_value(self.cell.kernel), 'recurrent_kernel': _read_variable_value(self.cell.recurrent_kernel), 'bias': _read_variable_value(self.cell.bias), 'mask': mask, 'time_major': self.time_major, 'go_backwards': self.go_backwards, 'sequence_lengths': row_lengths } normal_lstm_kwargs = gpu_lstm_kwargs.copy() normal_lstm_kwargs.update({ 'zero_output_for_mask': self.zero_output_for_mask, }) if tf.executing_eagerly(): device_type = _get_context_device_type() can_use_gpu = ( # Either user specified GPU or unspecified but GPU is available. (device_type == _GPU_DEVICE_NAME or (device_type is None and tf.config.list_logical_devices('GPU'))) and (mask is None or is_cudnn_supported_inputs(mask, self.time_major))) # Under eager context, check the device placement and prefer the # GPU implementation when GPU is available. if can_use_gpu: last_output, outputs, new_h, new_c, runtime = gpu_lstm( **gpu_lstm_kwargs) else: last_output, outputs, new_h, new_c, runtime = standard_lstm( **normal_lstm_kwargs) else: (last_output, outputs, new_h, new_c, runtime) = lstm_with_backend_selection(**normal_lstm_kwargs) states = [new_h, new_c] if self.stateful: updates = [ tf.compat.v1.assign(self_state, state) for self_state, state in zip(self.states, states) ] self.add_update(updates) if self.return_sequences: output = backend.maybe_convert_to_ragged( is_ragged_input, outputs, row_lengths, go_backwards=self.go_backwards) else: output = last_output if self.return_state: return [output] + list(states) elif self.return_runtime: return output, runtime else: return output def _canonical_to_params(weights, biases, shape, transpose_weights=False): """Utility function convert variable to cuDNN compatible parameter. Note that Keras weights for kernels are different from the cuDNN format. Eg.: ``` Keras cuDNN [[0, 1, 2], <---> [[0, 2, 4], [3, 4, 5]] [1, 3, 5]] ``` If the input weights need to be in a unified format, then set `transpose_weights=True` to convert the weights. Args: weights: list of weights for the individual kernels and recurrent kernels. biases: list of biases for individual gate. shape: the shape for the converted variables that will be feed to cuDNN. transpose_weights: boolean, whether to transpose the weights. Returns: The converted weights that can be feed to cuDNN ops as param. """ def convert(w): return tf.transpose(w) if transpose_weights else w weights = [tf.reshape(convert(x), shape) for x in weights] biases = [tf.reshape(x, shape) for x in biases] return tf.concat(weights + biases, axis=0) def standard_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """LSTM with standard kernel implementation. This implementation can be run on all types for hardware. This implementation lifts out all the layer weights and make them function parameters. It has same number of tensor input params as the cuDNN counterpart. The RNN step logic has been simplified, eg dropout and mask is removed since cuDNN implementation does not support that. Note that the first half of the bias tensor should be ignored by this impl. The cuDNN impl need an extra set of input gate bias. In order to make the both function take same shape of parameter, that extra set of bias is also feed here. Args: inputs: input tensor of LSTM layer. init_h: initial state tensor for the cell output. init_c: initial state tensor for the cell hidden state. kernel: weights for cell kernel. recurrent_kernel: weights for cell recurrent kernel. bias: weights for cell kernel bias and recurrent bias. Only recurrent bias is used in this case. mask: Boolean tensor for mask out the steps within sequence. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. time_major: boolean, whether the inputs are in the format of [time, batch, feature] or [batch, time, feature]. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. sequence_lengths: The lengths of all sequences coming from a variable length input, such as ragged tensors. If the input has a fixed timestep size, this should be None. zero_output_for_mask: Boolean, whether to output zero for masked timestep. Returns: last_output: output tensor for the last timestep, which has shape [batch, units]. outputs: output tensor for all timesteps, which has shape [batch, time, units]. state_0: the cell output, which has same shape as init_h. state_1: the cell hidden state, which has same shape as init_c. runtime: constant string tensor which indicate real runtime hardware. This value is for testing purpose and should be used by user. """ input_shape = backend.int_shape(inputs) timesteps = input_shape[0] if time_major else input_shape[1] def step(cell_inputs, cell_states): """Step function that will be used by Keras RNN backend.""" h_tm1 = cell_states[0] # previous memory state c_tm1 = cell_states[1] # previous carry state z = backend.dot(cell_inputs, kernel) z += backend.dot(h_tm1, recurrent_kernel) z = backend.bias_add(z, bias) z0, z1, z2, z3 = tf.split(z, 4, axis=1) i = tf.sigmoid(z0) f = tf.sigmoid(z1) c = f * c_tm1 + i * tf.tanh(z2) o = tf.sigmoid(z3) h = o * tf.tanh(c) return h, [h, c] last_output, outputs, new_states = backend.rnn( step, inputs, [init_h, init_c], constants=None, unroll=False, time_major=time_major, mask=mask, go_backwards=go_backwards, input_length=(sequence_lengths if sequence_lengths is not None else timesteps), zero_output_for_mask=zero_output_for_mask) return (last_output, outputs, new_states[0], new_states[1], _runtime(_RUNTIME_CPU)) def gpu_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths): """LSTM with either cuDNN or ROCm implementation which is only available for GPU. Note that currently only right padded data is supported, or the result will be polluted by the unmasked data which should be filtered. Args: inputs: Input tensor of LSTM layer. init_h: Initial state tensor for the cell output. init_c: Initial state tensor for the cell hidden state. kernel: Weights for cell kernel. recurrent_kernel: Weights for cell recurrent kernel. bias: Weights for cell kernel bias and recurrent bias. Only recurrent bias is used in this case. mask: Boolean tensor for mask out the steps within sequence. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. time_major: Boolean, whether the inputs are in the format of [time, batch, feature] or [batch, time, feature]. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. sequence_lengths: The lengths of all sequences coming from a variable length input, such as ragged tensors. If the input has a fixed timestep size, this should be None. Returns: last_output: Output tensor for the last timestep, which has shape [batch, units]. outputs: Output tensor for all timesteps, which has shape [batch, time, units]. state_0: The cell output, which has same shape as init_h. state_1: The cell hidden state, which has same shape as init_c. runtime: Constant string tensor which indicate real runtime hardware. This value is for testing purpose and should not be used by user. """ if not time_major and mask is None: inputs = tf.transpose(inputs, perm=(1, 0, 2)) seq_axis, batch_axis = (0, 1) else: seq_axis, batch_axis = (0, 1) if time_major else (1, 0) # For init_h and init_c, cuDNN expects one more dim of num_layers before or # after batch dim for time major or batch major inputs respectively init_h = tf.expand_dims(init_h, axis=seq_axis) init_c = tf.expand_dims(init_c, axis=seq_axis) weights = tf.split(kernel, 4, axis=1) weights += tf.split(recurrent_kernel, 4, axis=1) # cuDNN has an extra set of bias for inputs, we disable them (setting to 0), # so that mathematically it is same as the canonical LSTM implementation. full_bias = tf.concat((tf.zeros_like(bias), bias), 0) if tf.sysconfig.get_build_info()['is_rocm_build']: # ROCm MIOpen's weight sequence for LSTM is different from both canonical # and Cudnn format # MIOpen: [i, f, o, c] Cudnn/Canonical: [i, f, c, o] # i is input gate weights. # f is forget gate weights. # o is output gate weights. # c is cell gate weights. weights = [weights[x] for x in (0, 1, 3, 2, 4, 5, 7, 6)] # full_bias is a tensor of shape (8*n,) full_bias = tf.split(full_bias, 8, axis=0) full_bias = [full_bias[x] for x in (0, 1, 3, 2, 4, 5, 7, 6)] params = _canonical_to_params( weights=weights, biases=tf.split(full_bias, 8), shape=tf.constant([-1]), transpose_weights=True) if mask is not None: sequence_lengths = calculate_sequence_by_mask(mask, time_major) if sequence_lengths is not None: if go_backwards: # Three reversals are required. E.g., # normal input = [1, 2, 3, 0, 0] # where 0 need to be masked # reversed_input_to_cudnn = [3, 2, 1, 0, 0] # output_from_cudnn = [6, 5, 4, 0, 0] # expected_output = [0, 0, 6, 5 ,4] inputs = tf.reverse_sequence( inputs, sequence_lengths, seq_axis=seq_axis, batch_axis=batch_axis) outputs, h, c, _, _ = tf.raw_ops.CudnnRNNV3( input=inputs, input_h=init_h, input_c=init_c, params=params, is_training=True, rnn_mode='lstm', sequence_lengths=sequence_lengths, time_major=time_major) if go_backwards: outputs = tf.reverse_sequence( outputs, sequence_lengths, seq_axis=seq_axis, batch_axis=batch_axis) outputs = tf.reverse(outputs, axis=[seq_axis]) else: # # Fill the array with shape [batch] with value of max timesteps. # sequence_length = array_ops.fill([array_ops.shape(inputs)[1]], # array_ops.shape(inputs)[0]) if go_backwards: # Reverse axis 0 since the input is already convert to time major. inputs = tf.reverse(inputs, axis=[0]) outputs, h, c, _ = tf.raw_ops.CudnnRNN( input=inputs, input_h=init_h, input_c=init_c, params=params, is_training=True, rnn_mode='lstm') last_output = outputs[-1] if not time_major and mask is None: outputs = tf.transpose(outputs, perm=[1, 0, 2]) h = tf.squeeze(h, axis=seq_axis) c = tf.squeeze(c, axis=seq_axis) # In the case of variable length input, the cudnn kernel will fill zeros for # the output, whereas the default keras behavior is to bring over the previous # output for t-1, so that in the return_sequence=False case, user can quickly # get the final effect output instead just 0s at the last timestep. # In order to mimic the default keras behavior, we copy the final h state as # the last_output, since it is numerically same as the output. if mask is not None: last_output = h return last_output, outputs, h, c, _runtime(_RUNTIME_GPU) def lstm_with_backend_selection(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """Call the LSTM with optimized backend kernel selection. Under the hood, this function will create two TF function, one with the most generic kernel and can run on all device condition, and the second one with cuDNN specific kernel, which can only run on GPU. The first function will be called with normal_lstm_params, while the second function is not called, but only registered in the graph. The Grappler will do the proper graph rewrite and swap the optimized TF function based on the device placement. Args: inputs: Input tensor of LSTM layer. init_h: Initial state tensor for the cell output. init_c: Initial state tensor for the cell hidden state. kernel: Weights for cell kernel. recurrent_kernel: Weights for cell recurrent kernel. bias: Weights for cell kernel bias and recurrent bias. Only recurrent bias is used in this case. mask: Boolean tensor for mask out the steps within sequence. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored. time_major: Boolean, whether the inputs are in the format of [time, batch, feature] or [batch, time, feature]. go_backwards: Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. sequence_lengths: The lengths of all sequences coming from a variable length input, such as ragged tensors. If the input has a fixed timestep size, this should be None. zero_output_for_mask: Boolean, whether to output zero for masked timestep. Returns: List of output tensors, same as standard_lstm. """ params = { 'inputs': inputs, 'init_h': init_h, 'init_c': init_c, 'kernel': kernel, 'recurrent_kernel': recurrent_kernel, 'bias': bias, 'mask': mask, 'time_major': time_major, 'go_backwards': go_backwards, 'sequence_lengths': sequence_lengths, 'zero_output_for_mask': zero_output_for_mask, } def gpu_lstm_with_fallback(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, time_major, go_backwards, sequence_lengths, zero_output_for_mask): """Use cuDNN kernel when mask is none or strictly right padded.""" if mask is None: return gpu_lstm( inputs=inputs, init_h=init_h, init_c=init_c, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths) def cudnn_lstm_fn(): return gpu_lstm( inputs=inputs, init_h=init_h, init_c=init_c, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths) def stardard_lstm_fn(): return standard_lstm( inputs=inputs, init_h=init_h, init_c=init_c, kernel=kernel, recurrent_kernel=recurrent_kernel, bias=bias, mask=mask, time_major=time_major, go_backwards=go_backwards, sequence_lengths=sequence_lengths, zero_output_for_mask=zero_output_for_mask) return tf.cond( is_cudnn_supported_inputs(mask, time_major), true_fn=cudnn_lstm_fn, false_fn=stardard_lstm_fn) if _use_new_code(): # Chooses the implementation dynamically based on the running device. (last_output, outputs, new_h, new_c, runtime) = tf.__internal__.execute_fn_for_device( { _CPU_DEVICE_NAME: lambda: standard_lstm(**params), _GPU_DEVICE_NAME: lambda: gpu_lstm_with_fallback(**params) }, lambda: standard_lstm(**params)) else: # Each time a `tf.function` is called, we will give it a unique # identifiable API name, so that Grappler won't get confused when it # sees multiple LSTM layers added into same graph, and it will be able # to pair up the different implementations across them. api_name = 'lstm_' + str(uuid.uuid4()) supportive_attribute = { 'time_major': time_major, 'go_backwards': go_backwards, } defun_standard_lstm = _generate_defun_backend(api_name, _CPU_DEVICE_NAME, standard_lstm, supportive_attribute) defun_gpu_lstm = _generate_defun_backend(api_name, _GPU_DEVICE_NAME, gpu_lstm_with_fallback, supportive_attribute) # Call the normal LSTM impl and register the cuDNN impl function. The # grappler will kick in during session execution to optimize the graph. last_output, outputs, new_h, new_c, runtime = defun_standard_lstm(**params) _function_register(defun_gpu_lstm, **params) return last_output, outputs, new_h, new_c, runtime def is_sequence_right_padded(mask): """Check the mask tensor and see if it right padded. For cuDNN kernel, it uses the sequence length param to skip the tailing timestep. If the data is left padded, or not a strict right padding (has masked value in the middle of the sequence), then cuDNN kernel won't be work properly in those cases. Left padded data: [[False, False, True, True, True]]. Right padded data: [[True, True, True, False, False]]. Mixture of mask/unmasked data: [[True, False, True, False, False]]. Note that for the mixed data example above, the actually data RNN should see are those 2 Trues (index 0 and 2), the index 1 False should be ignored and not pollute the internal states. Args: mask: the Boolean tensor with shape [batch, timestep] Returns: boolean scalar tensor, whether the mask is strictly right padded. """ max_seq_length = tf.shape(mask)[1] count_of_true = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) right_padded_mask = tf.sequence_mask( count_of_true, maxlen=max_seq_length) return tf.reduce_all(tf.equal(mask, right_padded_mask)) def has_fully_masked_sequence(mask): # See https://github.com/tensorflow/tensorflow/issues/33148 for more details. # Cudnn kernel will error out if the input sequence contains any fully masked # data. We walk around this issue by rerouting the computation to standard # kernel, until the issue on cudnn side has been fixed. # For a fully masked sequence, it will contain all Falses. To make it easy to # check, we inverse the boolean, check if any of the sequence has all True. return tf.reduce_any( tf.reduce_all( tf.logical_not(mask), axis=1)) def is_cudnn_supported_inputs(mask, time_major): if time_major: mask = tf.transpose(mask) return tf.logical_and( is_sequence_right_padded(mask), tf.logical_not(has_fully_masked_sequence(mask))) def calculate_sequence_by_mask(mask, time_major): """Calculate the sequence length tensor (1-D) based on the masking tensor. The masking tensor is a 2D boolean tensor with shape [batch, timestep]. For any timestep that should be masked, the corresponding field will be False. Consider the following example: a = [[True, True, False, False], [True, True, True, False]] It is a (2, 4) tensor, and the corresponding sequence length result should be 1D tensor with value [2, 3]. Note that the masking tensor must be right padded that could be checked by, e.g., `is_sequence_right_padded()`. Args: mask: Boolean tensor with shape [batch, timestep] or [timestep, batch] if time_major=True. time_major: Boolean, which indicates whether the mask is time major or batch major. Returns: sequence_length: 1D int32 tensor. """ timestep_index = 0 if time_major else 1 return tf.reduce_sum(tf.cast(mask, tf.int32), axis=timestep_index) def _generate_defun_backend(unique_api_name, preferred_device, func, supportive_attributes): function_attributes = { _FUNCTION_API_NAME_ATTRIBUTE: unique_api_name, _FUNCTION_DEVICE_ATTRIBUTE: preferred_device, } function_attributes.update(supportive_attributes) return tf.__internal__.function.defun_with_attributes(func=func, attributes=function_attributes, autograph=False) def _get_context_device_type(): """Parse the current context and return the device type, eg CPU/GPU.""" current_device = get_device_name() if current_device is None: return None return tf.compat.v1.DeviceSpec.from_string(current_device).device_type def _runtime(runtime_name): with tf.device('/cpu:0'): return tf.constant( runtime_name, dtype=tf.float32, name='runtime') def _read_variable_value(v): """Read the value of a variable if it is variable.""" if isinstance(v, tf.Variable): return v.read_value() return v def _function_register(func, *args, **kwargs): """Register a specialization of a `Function` into the graph. This won't actually call the function with the inputs, and only put the function definition into graph. Register function with different input param will result into multiple version of functions registered in graph. Args: func: the `Function` instance that generated by a @defun *args: input arguments for the Python function. **kwargs: input keyword arguments for the Python function. Returns: a `ConcreteFunction` object specialized to inputs and execution context. Raises: ValueError: When the input function is not a defun wrapped python function. """ concrete_func = func.get_concrete_function(*args, **kwargs) concrete_func.add_to_graph() concrete_func.add_gradient_functions_to_graph() return concrete_func
74,378
40.668908
83
py
keras
keras-master/keras/layers/multi_head_attention.py
# Lint as: python3 # 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 attention layer.""" import tensorflow.compat.v2 as tf # pylint: disable=g-classes-have-attributes import collections import math import string import numpy as np from keras import constraints from keras import initializers from keras import regularizers from keras.engine.base_layer import Layer from keras.layers import advanced_activations from keras.layers import core from keras.layers import einsum_dense from keras.utils import tf_utils 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 = "%s,%s->%s" % (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. 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 key feature dim. 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). Defaults to either using the training mode of the parent layer/model, or False (inference) if there is no parent layer. 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 project 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(MultiHeadAttention, self).__init__(**kwargs) 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._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(MultiHeadAttention, self).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 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) # pylint: disable=protected-access 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) common_kwargs = dict( kernel_initializer=self._kernel_initializer, bias_initializer=self._bias_initializer, 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) # 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 = einsum_dense.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", **common_kwargs) einsum_equation, bias_axes, output_rank = _build_proj_equation( self._key_shape.rank - 1, bound_dims=1, output_dims=2) self._key_dense = einsum_dense.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", **common_kwargs) einsum_equation, bias_axes, output_rank = _build_proj_equation( self._value_shape.rank - 1, bound_dims=1, output_dims=2) self._value_dense = einsum_dense.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", **common_kwargs) # Builds the attention computations for multi-head dot product attention. # These computations could be wrapped into the keras attention layer once # it support mult-head einsum computations. self._build_attention(output_rank) self._output_dense = self._make_output_dense( free_dims, common_kwargs, "attention_output") 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 einsum_dense.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 costomize 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 = advanced_activations.Softmax(axis=norm_axes) self._dropout_layer = core.Dropout(rate=self._dropout) 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, 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. 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): if not self._built_from_signature: self._build_from_signature(query=query, value=value, key=key) if key is None: key = value # 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 return_attention_scores: return attention_output, attention_scores return attention_output
20,780
39.747059
106
py
keras
keras-master/keras/layers/dense_attention.py
# 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. # ============================================================================== """Attention layers that can be used in sequence DNN/CNN models. This file follows the terminology of https://arxiv.org/abs/1706.03762 Figure 2. Attention is formed by three tensors: Query, Key and Value. """ import tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer import Layer from keras.utils import control_flow_util from tensorflow.python.util.tf_export import keras_export class BaseDenseAttention(Layer): """Base Attention class for Dense networks. This class is suitable for Dense or CNN networks, and not for RNN networks. Implementations of attention mechanisms should inherit from this class, and reuse the `apply_attention_scores()` method. Args: causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such that position `i` cannot attend to positions `j > i`. This prevents the flow of information from the future towards the past. dropout: Float between 0 and 1. Fraction of the units to drop for the attention scores. Call Args: inputs: List of the following tensors: * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not given, will use `value` for both `key` and `value`, which is the most common case. mask: List of the following tensors: * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. If given, the output will be zero at the positions where `mask==False`. * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. If given, will apply the mask such that values at positions where `mask==False` do not contribute to the result. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). return_attention_scores: bool, it `True`, returns the attention scores (after masking and softmax) as an additional output argument. Output: Attention outputs of shape `[batch_size, Tq, dim]`. [Optional] Attention scores after masking and softmax with shape `[batch_size, Tq, Tv]`. """ def __init__(self, causal=False, dropout=0.0, **kwargs): super(BaseDenseAttention, self).__init__(**kwargs) self.causal = causal self.dropout = dropout self.supports_masking = True def _calculate_scores(self, query, key): """Calculates attention scores. Args: query: Query tensor of shape `[batch_size, Tq, dim]`. key: Key tensor of shape `[batch_size, Tv, dim]`. Returns: Tensor of shape `[batch_size, Tq, Tv]`. """ return NotImplementedError def _apply_scores(self, scores, value, scores_mask=None, training=None): """Applies attention scores to the given value tensor. To use this method in your attention layer, follow the steps: * Use `query` tensor of shape `[batch_size, Tq]` and `key` tensor of shape `[batch_size, Tv]` to calculate the attention `scores`. * Pass `scores` and `value` tensors to this method. The method applies `scores_mask`, calculates `attention_distribution = softmax(scores)`, then returns `matmul(attention_distribution, value). * Apply `query_mask` and return the result. Args: scores: Scores float tensor of shape `[batch_size, Tq, Tv]`. value: Value tensor of shape `[batch_size, Tv, dim]`. scores_mask: A boolean mask `Tensor` of shape `[batch_size, 1, Tv]` or `[batch_size, Tq, Tv]`. If given, scores at positions where `scores_mask==False` do not contribute to the result. It must contain at least one `True` value in each line along the last dimension. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Returns: Tensor of shape `[batch_size, Tq, dim]`. Attention scores after masking and softmax with shape `[batch_size, Tq, Tv]`. """ if scores_mask is not None: padding_mask = tf.logical_not(scores_mask) # Bias so padding positions do not contribute to attention distribution. # Note 65504. is the max float16 value. if scores.dtype is tf.float16: scores -= 65504. * tf.cast(padding_mask, dtype=scores.dtype) else: scores -= 1.e9 * tf.cast(padding_mask, dtype=scores.dtype) if training is None: training = backend.learning_phase() weights = tf.nn.softmax(scores) def dropped_weights(): return tf.nn.dropout(weights, rate=self.dropout) weights = control_flow_util.smart_cond(training, dropped_weights, lambda: tf.identity(weights)) return tf.matmul(weights, value), weights # TODO(b/125916026): Consider exposing a __call__ method with named args. def call(self, inputs, mask=None, training=None, return_attention_scores=False): self._validate_call_args(inputs=inputs, mask=mask) q = inputs[0] v = inputs[1] k = inputs[2] if len(inputs) > 2 else v q_mask = mask[0] if mask else None v_mask = mask[1] if mask else None scores = self._calculate_scores(query=q, key=k) if v_mask is not None: # Mask of shape [batch_size, 1, Tv]. v_mask = tf.expand_dims(v_mask, axis=-2) if self.causal: # Creates a lower triangular mask, so position i cannot attend to # positions j>i. This prevents the flow of information from the future # into the past. scores_shape = tf.shape(scores) # causal_mask_shape = [1, Tq, Tv]. causal_mask_shape = tf.concat( [tf.ones_like(scores_shape[:-2]), scores_shape[-2:]], axis=0) causal_mask = _lower_triangular_mask(causal_mask_shape) else: causal_mask = None scores_mask = _merge_masks(v_mask, causal_mask) result, attention_scores = self._apply_scores( scores=scores, value=v, scores_mask=scores_mask, training=training) if q_mask is not None: # Mask of shape [batch_size, Tq, 1]. q_mask = tf.expand_dims(q_mask, axis=-1) result *= tf.cast(q_mask, dtype=result.dtype) if return_attention_scores: return result, attention_scores return result def compute_mask(self, inputs, mask=None): self._validate_call_args(inputs=inputs, mask=mask) if mask: q_mask = mask[0] if q_mask is None: return None return tf.convert_to_tensor(q_mask) return None def _validate_call_args(self, inputs, mask): """Validates arguments of the call method.""" class_name = self.__class__.__name__ if not isinstance(inputs, list): raise ValueError( f'{class_name} layer must be called on a list of inputs, ' 'namely [query, value] or [query, value, key]. ' f'Received: {inputs}.') if len(inputs) < 2 or len(inputs) > 3: raise ValueError( f'{class_name} layer accepts inputs list of length 2 or 3, ' 'namely [query, value] or [query, value, key]. ' f'Received length: {len(inputs)}.') if mask: if not isinstance(mask, list): raise ValueError( f'{class_name} layer mask must be a list, ' f'namely [query_mask, value_mask]. Received: {mask}.') if len(mask) < 2 or len(mask) > len(inputs): raise ValueError( f'{class_name} layer mask must be a list of length 2, ' f'namely [query_mask, value_mask]. Received length: {len(mask)}.') def get_config(self): config = { 'causal': self.causal, 'dropout': self.dropout, } base_config = super(BaseDenseAttention, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Attention') class Attention(BaseDenseAttention): """Dot-product attention layer, a.k.a. Luong-style attention. Inputs are `query` tensor of shape `[batch_size, Tq, dim]`, `value` tensor of shape `[batch_size, Tv, dim]` and `key` tensor of shape `[batch_size, Tv, dim]`. The calculation follows the steps: 1. Calculate scores with shape `[batch_size, Tq, Tv]` as a `query`-`key` dot product: `scores = tf.matmul(query, key, transpose_b=True)`. 2. Use scores to calculate a distribution with shape `[batch_size, Tq, Tv]`: `distribution = tf.nn.softmax(scores)`. 3. Use `distribution` to create a linear combination of `value` with shape `[batch_size, Tq, dim]`: `return tf.matmul(distribution, value)`. Args: use_scale: If `True`, will create a scalar variable to scale the attention scores. causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such that position `i` cannot attend to positions `j > i`. This prevents the flow of information from the future towards the past. Defaults to `False`. dropout: Float between 0 and 1. Fraction of the units to drop for the attention scores. Defaults to 0.0. Call Args: inputs: List of the following tensors: * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not given, will use `value` for both `key` and `value`, which is the most common case. mask: List of the following tensors: * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. If given, the output will be zero at the positions where `mask==False`. * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. If given, will apply the mask such that values at positions where `mask==False` do not contribute to the result. return_attention_scores: bool, it `True`, returns the attention scores (after masking and softmax) as an additional output argument. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Output: Attention outputs of shape `[batch_size, Tq, dim]`. [Optional] Attention scores after masking and softmax with shape `[batch_size, Tq, Tv]`. The meaning of `query`, `value` and `key` depend on the application. In the case of text similarity, for example, `query` is the sequence embeddings of the first piece of text and `value` is the sequence embeddings of the second piece of text. `key` is usually the same tensor as `value`. Here is a code example for using `Attention` in a CNN+Attention network: ```python # Variable-length int sequences. query_input = tf.keras.Input(shape=(None,), dtype='int32') value_input = tf.keras.Input(shape=(None,), dtype='int32') # Embedding lookup. token_embedding = tf.keras.layers.Embedding(input_dim=1000, output_dim=64) # Query embeddings of shape [batch_size, Tq, dimension]. query_embeddings = token_embedding(query_input) # Value embeddings of shape [batch_size, Tv, dimension]. value_embeddings = token_embedding(value_input) # CNN layer. cnn_layer = tf.keras.layers.Conv1D( filters=100, kernel_size=4, # Use 'same' padding so outputs have the same shape as inputs. padding='same') # Query encoding of shape [batch_size, Tq, filters]. query_seq_encoding = cnn_layer(query_embeddings) # Value encoding of shape [batch_size, Tv, filters]. value_seq_encoding = cnn_layer(value_embeddings) # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = tf.keras.layers.Attention()( [query_seq_encoding, value_seq_encoding]) # Reduce over the sequence axis to produce encodings of shape # [batch_size, filters]. query_encoding = tf.keras.layers.GlobalAveragePooling1D()( query_seq_encoding) query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( query_value_attention_seq) # Concatenate query and document encodings to produce a DNN input layer. input_layer = tf.keras.layers.Concatenate()( [query_encoding, query_value_attention]) # Add DNN layers, and create Model. # ... ``` """ def __init__(self, use_scale=False, **kwargs): super(Attention, self).__init__(**kwargs) self.use_scale = use_scale def build(self, input_shape): """Creates scale variable if use_scale==True.""" if self.use_scale: self.scale = self.add_weight( name='scale', shape=(), initializer='ones', dtype=self.dtype, trainable=True) else: self.scale = None super(Attention, self).build(input_shape) def _calculate_scores(self, query, key): """Calculates attention scores as a query-key dot product. Args: query: Query tensor of shape `[batch_size, Tq, dim]`. key: Key tensor of shape `[batch_size, Tv, dim]`. Returns: Tensor of shape `[batch_size, Tq, Tv]`. """ scores = tf.matmul(query, key, transpose_b=True) if self.scale is not None: scores *= self.scale return scores def get_config(self): config = {'use_scale': self.use_scale} base_config = super(Attention, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.AdditiveAttention') class AdditiveAttention(BaseDenseAttention): """Additive attention layer, a.k.a. Bahdanau-style attention. Inputs are `query` tensor of shape `[batch_size, Tq, dim]`, `value` tensor of shape `[batch_size, Tv, dim]` and `key` tensor of shape `[batch_size, Tv, dim]`. The calculation follows the steps: 1. Reshape `query` and `key` into shapes `[batch_size, Tq, 1, dim]` and `[batch_size, 1, Tv, dim]` respectively. 2. Calculate scores with shape `[batch_size, Tq, Tv]` as a non-linear sum: `scores = tf.reduce_sum(tf.tanh(query + key), axis=-1)` 3. Use scores to calculate a distribution with shape `[batch_size, Tq, Tv]`: `distribution = tf.nn.softmax(scores)`. 4. Use `distribution` to create a linear combination of `value` with shape `[batch_size, Tq, dim]`: `return tf.matmul(distribution, value)`. Args: use_scale: If `True`, will create a variable to scale the attention scores. causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such that position `i` cannot attend to positions `j > i`. This prevents the flow of information from the future towards the past. Defaults to `False`. dropout: Float between 0 and 1. Fraction of the units to drop for the attention scores. Defaults to 0.0. Call Args: inputs: List of the following tensors: * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not given, will use `value` for both `key` and `value`, which is the most common case. mask: List of the following tensors: * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. If given, the output will be zero at the positions where `mask==False`. * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. If given, will apply the mask such that values at positions where `mask==False` do not contribute to the result. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). return_attention_scores: bool, it `True`, returns the attention scores (after masking and softmax) as an additional output argument. Output: Attention outputs of shape `[batch_size, Tq, dim]`. [Optional] Attention scores after masking and softmax with shape `[batch_size, Tq, Tv]`. The meaning of `query`, `value` and `key` depend on the application. In the case of text similarity, for example, `query` is the sequence embeddings of the first piece of text and `value` is the sequence embeddings of the second piece of text. `key` is usually the same tensor as `value`. Here is a code example for using `AdditiveAttention` in a CNN+Attention network: ```python # Variable-length int sequences. query_input = tf.keras.Input(shape=(None,), dtype='int32') value_input = tf.keras.Input(shape=(None,), dtype='int32') # Embedding lookup. token_embedding = tf.keras.layers.Embedding(max_tokens, dimension) # Query embeddings of shape [batch_size, Tq, dimension]. query_embeddings = token_embedding(query_input) # Value embeddings of shape [batch_size, Tv, dimension]. value_embeddings = token_embedding(value_input) # CNN layer. cnn_layer = tf.keras.layers.Conv1D( filters=100, kernel_size=4, # Use 'same' padding so outputs have the same shape as inputs. padding='same') # Query encoding of shape [batch_size, Tq, filters]. query_seq_encoding = cnn_layer(query_embeddings) # Value encoding of shape [batch_size, Tv, filters]. value_seq_encoding = cnn_layer(value_embeddings) # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = tf.keras.layers.AdditiveAttention()( [query_seq_encoding, value_seq_encoding]) # Reduce over the sequence axis to produce encodings of shape # [batch_size, filters]. query_encoding = tf.keras.layers.GlobalAveragePooling1D()( query_seq_encoding) query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( query_value_attention_seq) # Concatenate query and document encodings to produce a DNN input layer. input_layer = tf.keras.layers.Concatenate()( [query_encoding, query_value_attention]) # Add DNN layers, and create Model. # ... ``` """ def __init__(self, use_scale=True, **kwargs): super(AdditiveAttention, self).__init__(**kwargs) self.use_scale = use_scale def build(self, input_shape): v_shape = tf.TensorShape(input_shape[1]) dim = v_shape[-1] dim = tf.compat.dimension_value(dim) if self.use_scale: self.scale = self.add_weight( name='scale', shape=[dim], initializer='glorot_uniform', dtype=self.dtype, trainable=True) else: self.scale = None super(AdditiveAttention, self).build(input_shape) def _calculate_scores(self, query, key): """Calculates attention scores as a nonlinear sum of query and key. Args: query: Query tensor of shape `[batch_size, Tq, dim]`. key: Key tensor of shape `[batch_size, Tv, dim]`. Returns: Tensor of shape `[batch_size, Tq, Tv]`. """ # Reshape tensors to enable broadcasting. # Reshape into [batch_size, Tq, 1, dim]. q_reshaped = tf.expand_dims(query, axis=-2) # Reshape into [batch_size, 1, Tv, dim]. k_reshaped = tf.expand_dims(key, axis=-3) if self.use_scale: scale = self.scale else: scale = 1. return tf.reduce_sum( scale * tf.tanh(q_reshaped + k_reshaped), axis=-1) def get_config(self): config = {'use_scale': self.use_scale} base_config = super(AdditiveAttention, self).get_config() return dict(list(base_config.items()) + list(config.items())) def _lower_triangular_mask(shape): """Creates a lower-triangular boolean mask over the last 2 dimensions.""" row_index = tf.cumsum( tf.ones(shape=shape, dtype=tf.int32), axis=-2) col_index = tf.cumsum( tf.ones(shape=shape, dtype=tf.int32), axis=-1) return tf.greater_equal(row_index, col_index) def _merge_masks(x, y): if x is None: return y if y is None: return x return tf.logical_and(x, y)
20,485
38.472062
80
py
keras
keras-master/keras/layers/dense_attention_test.py
# 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 dense attention layers.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np import keras from keras import combinations from keras import testing_utils from keras.layers import core from keras.layers import dense_attention from keras.mixed_precision import policy @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class BaseDenseAttentionTest(tf.test.TestCase, parameterized.TestCase): def test_one_dim_with_mask(self): # Scores tensor of shape [1, 1, 1] scores = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 1, 1] v = np.array([[[1.6]]], dtype=np.float32) # Scores mask tensor of shape [1, 1, 1] scores_mask = np.array([[[True]]], dtype=np.bool_) actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores( scores=scores, value=v, scores_mask=scores_mask) # Expected softmax_scores = [[[1]]] expected_scores = np.array([[[1.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 1, 1]. # expected000 = softmax_scores[0, 0] * 1.6 = 1.6 expected = np.array([[[1.6]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_one_dim_no_mask(self): # Scores tensor of shape [1, 1, 1] scores = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 1, 1] v = np.array([[[1.6]]], dtype=np.float32) actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores( scores=scores, value=v) # Expected softmax_scores = [[[1]]] expected_scores = np.array([[[1.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 1, 1]. # expected000 = softmax_scores[0, 0] * 1.6 = 1.6 expected = np.array([[[1.6]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_multi_dim_with_mask(self): # Scores tensor of shape [1, 1, 3] scores = np.array([[[1., 0., 1.]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Scores mask tensor of shape [1, 1, 3] scores_mask = np.array([[[True, True, False]]], dtype=np.bool_) actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores( scores=scores, value=v, scores_mask=scores_mask) # Expected softmax scores = softmax(scores) with zeros in positions where # v_mask == False. # => softmax_scores000 = exp(1)/(exp(1) + exp(0)) = 0.73105857863 # softmax_scores001 = exp(0)/(exp(1) + exp(0)) = 0.26894142137 # softmax_scores002 = 0 expected_scores = np.array([[[0.73105857863, 0.26894142137, 0.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 1, 1]. # expected000 = 0.73105857863 * 1.6 + 0.26894142137 * 0.7 - 0 * 0.8 # = 1.35795272077 expected = np.array([[[1.35795272077]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_multi_dim_no_mask(self): # Scores tensor of shape [1, 1, 3] scores = np.array([[[1., 0., 1.]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores( scores=scores, value=v) # Expected softmax_scores = softmax(scores). # => softmax_scores000 = exp(1)/(exp(1) + exp(0) + exp(1)) # = 0.42231879825 # softmax_scores001 = exp(0)/(exp(1) + exp(0) + exp(1)) # = 0.15536240349 # softmax_scores002 = exp(1)/(exp(1) + exp(0) + exp(1)) # = 0.42231879825 expected_scores = np.array( [[[0.42231879825, 0.15536240349, 0.42231879825]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 1, 1]. # expected000 = 0.42231879825 * 1.6 + 0.15536240349 * 0.7 # - 0.42231879825 * 0.8 # = 0.44660872104 expected = np.array([[[0.44660872104]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_one_dim_batch_size_two(self): # Scores tensor of shape [2, 1, 1] scores = np.array([[[1.1]], [[2.1]]], dtype=np.float32) # Value tensor of shape [2, 1, 1] v = np.array([[[1.6]], [[2.6]]], dtype=np.float32) # Scpres mask tensor of shape [2, 1, 1] scores_mask = np.array([[[True]], [[True]]], dtype=np.bool_) actual, actual_scores = dense_attention.BaseDenseAttention()._apply_scores( scores=scores, value=v, scores_mask=scores_mask) # Expected softmax_scores = [[[1]], [[1]]] expected_scores = np.array([[[1.]], [[1.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [2, 1, 1]. # expected000 = softmax_scores[0, 0] * 1.6 = 1.6 # expected100 = softmax_scores[1, 0] * 2.6 = 2.6 expected = np.array([[[1.6]], [[2.6]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_shape_with_dropout(self): # scores: Scores float tensor of shape `[batch_size, tq, tv]`. # value: Value tensor of shape `[batch_size, tv, dim]`. batch_size = 4 tq = 5 tv = 6 dim = 7 scores = np.ones((batch_size, tq, tv)) value = np.ones((batch_size, tv, dim)) actual, actual_scores = dense_attention.BaseDenseAttention( dropout=0.1)._apply_scores( scores=scores, value=value, training=False) # Expected Tensor of shape `[batch_size, tq, tv]`. expected_scores_shape = [batch_size, tq, tv] self.assertAllEqual(expected_scores_shape, tf.shape(actual_scores)) # Expected Tensor of shape `[batch_size, tq, dim]`. expected_shape = [batch_size, tq, dim] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_serialization(self): # Test serialization with causal layer = dense_attention.BaseDenseAttention(causal=True) config = keras.layers.serialize(layer) new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.causal, True) config = layer.get_config() new_layer = dense_attention.BaseDenseAttention.from_config(config) self.assertEqual(new_layer.causal, True) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class AttentionTest(tf.test.TestCase, parameterized.TestCase): def test_calculate_scores_one_dim(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Key tensor of shape [1, 1, 1] k = np.array([[[1.6]]], dtype=np.float32) attention_layer = dense_attention.Attention() attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [1, 1, 1]. # expected000 = 1.1*1.6 = 1.76 expected = np.array([[[1.76]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_calculate_scores_multi_dim(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Key tensor of shape [1, 3, 4] k = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) attention_layer = dense_attention.Attention() attention_layer.build(input_shape=([1, 2, 4], [1, 3, 4])) actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [1, 2, 3]. # expected000 = 1.*1.5+1.1*1.6+1.2*1.7+1.3*1.8 = 7.64 # expected001 = 1.*2.5+1.1*2.6+1.2*2.7+1.3*2.8 = 12.24 # expected002 = 1.*3.5+1.1*3.6+1.2*3.7+1.3*3.8 = 16.84 # expected010 = 2.*1.5+2.1*1.6+2.2*1.7+2.3*1.8 = 14.24 # expected011 = 2.*2.5+2.1*2.6+2.2*2.7+2.3*2.8 = 22.84 # expected012 = 2.*3.5+2.1*3.6+2.2*3.7+2.3*3.8 = 31.44 expected = np.array([[[7.64, 12.24, 16.84], [14.24, 22.84, 31.44]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_calculate_scores_one_dim_batch_size_two(self): # Query tensor of shape [2, 1, 1] q = np.array([[[1.1]], [[2.1]]], dtype=np.float32) # Key tensor of shape [2, 1, 1] k = np.array([[[1.6]], [[2.6]]], dtype=np.float32) attention_layer = dense_attention.Attention() attention_layer.build(input_shape=([2, 1, 1], [2, 1, 1])) actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [2, 1, 1]. # expected000 = 1.1*1.6 = 1.76 # expected100 = 2.1*2.6 = 5.46 expected = np.array([[[1.76]], [[5.46]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_calculate_scores_one_dim_with_scale(self): """Tests that scores are multiplied by scale.""" # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Key tensor of shape [1, 1, 1] k = np.array([[[1.6]]], dtype=np.float32) attention_layer = dense_attention.Attention(use_scale=True) attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) attention_layer.scale = -2. actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [1, 1, 1]. # expected000 = -2*1.1*1.6 = -3.52 expected = np.array([[[-3.52]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_shape(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Value tensor of shape [1, 3, 4] v = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.Attention() actual = attention_layer([q, v], mask=[None, v_mask]) expected_shape = [1, 2, 4] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_shape_with_key(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Value tensor of shape [1, 3, 4] v = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Key tensor of shape [1, 3, 4] k = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.Attention() actual = attention_layer([q, v, k], mask=[None, v_mask]) expected_shape = [1, 2, 4] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_multi_dim(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.Attention() actual = attention_layer([q, v], mask=[None, v_mask]) # Expected scores of shape [1, 1, 3] # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8]]] = [[[1.76, 0.77, -0.88]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77)) # = 0.72908792234 # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77)) # = 0.27091207765 # attention_distribution002 = 0 # # Expected tensor of shape [1, 1, 1]. # expected000 = 0.72908792234 * 1.6 + 0.27091207765 * 0.7 - 0 * 0.8 # = 1.3561791301 expected = np.array([[[1.3561791301]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_multi_dim_with_key(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32) # Key tensor of shape [1, 3, 1] k = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.Attention() actual = attention_layer([q, v, k], mask=[None, v_mask]) # Expected scores of shape [1, 1, 3] # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8]]] = [[[1.76, 0.77, -0.88]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77)) # = 0.72908792234 # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77)) # = 0.27091207765 # attention_distribution002 = 0 # # Expected tensor of shape [1, 1, 1]. # expected000 = 0.72908792234 * 0.5 + 0.27091207765 * 0.8 - 0 * 0.3 # = 0.58127362329 expected = np.array([[[0.58127362329]]], dtype=np.float32) self.assertAllClose(expected, actual) @parameterized.named_parameters( ('', False), ('return_attention_scores', True), ) def test_multi_dim_with_query_mask(self, return_attention_scores): # Query tensor of shape [1, 2, 1] q = np.array([[[1.1], [-0.5]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Query mask tensor of shape [1, 2] q_mask = np.array([[True, False]], dtype=np.bool_) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.Attention() if return_attention_scores: actual, actual_scores = attention_layer( [q, v], mask=[q_mask, v_mask], return_attention_scores=return_attention_scores) else: actual = attention_layer([q, v], mask=[q_mask, v_mask], return_attention_scores=return_attention_scores) # Expected scores of shape [1, 2, 3] # scores = [[[1.1*1.6, 1.1*0.7, -1.1*0.8], [-0.5*1.6, -0.5*0.7, 0.5*0.8]]] # = [[[1.76, 0.77, -0.88], [-0.8, -0.35, 0.4]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 = exp(1.76)/(exp(1.76) + exp(0.77)) # = 0.72908792234 # attention_distribution001 = exp(0.77)/(exp(1.76) + exp(0.77)) # = 0.27091207765 # attention_distribution002 = 0 # => attention_distribution010 = exp(-0.8)/(exp(-0.8) + exp(-0.35)) # = 0.38936076605 # attention_distribution011 = exp(-0.35)/(exp(-0.8) + exp(-0.35)) # = 0.61063923394 # attention_distribution012 = 0 if return_attention_scores: expected_scores = np.array([[[0.72908792234, 0.27091207765, 0.], [0.38936076605, 0.61063923394, 0.]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 2, 1] with zeros where q_mask == False. # expected000 = 0.72908792234 * 1.6 + 0.27091207765 * 0.7 - 0 * 0.8 # = 1.3561791301 # expected000 = 0 expected = np.array([[[1.3561791301], [0.]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_scale_None(self): """Tests that scale is None by default.""" attention_layer = dense_attention.Attention() attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) self.assertIsNone(attention_layer.scale) def test_scale_init_eager(self): """Tests that scale initializes to 1 when use_scale=True.""" if not tf.executing_eagerly(): self.skipTest('Only run in eager mode') attention_layer = dense_attention.Attention(use_scale=True) attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) self.assertAllClose(1., attention_layer.scale.value()) def test_scale_init_graph(self): """Tests that scale initializes to 1 when use_scale=True.""" with self.cached_session() as sess: attention_layer = dense_attention.Attention(use_scale=True) attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) sess.run(attention_layer.scale.initializer) self.assertAllClose(1., attention_layer.scale.value()) @parameterized.named_parameters( ('', False), ('return_attention_scores', True), ) def test_self_attention_causal(self, return_attention_scores): # Query-value tensor of shape [1, 3, 1] q = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32) attention_layer = dense_attention.Attention(causal=True) if return_attention_scores: actual, actual_scores = attention_layer( [q, q], return_attention_scores=return_attention_scores) else: actual = attention_layer([q, q], return_attention_scores=return_attention_scores) # Expected scores of shape [1, 3, 3] # scores = [[0.25, 0.4, -0.15], [0.4, 0.64, -0.24], [-0.15, -0.24, 0.09]] # Expected attention distribution = softmax(scores) lower triangular # => attention_distribution00 = [1., 0., 0.] # attention_distribution01 # = [exp(0.4), exp(0.64), 0.] / (exp(0.4) + exp(0.64)) # = [0.44028635073, 0.55971364926, 0.] # attention_distribution02 # = [exp(-0.15), exp(-0.24), exp(0.09)] # / (exp(-0.15) + exp(-0.24) + exp(0.09)) # = [0.31395396638, 0.28693232061, 0.399113713] if return_attention_scores: expected_scores = np.array( [[[1., 0., 0.], [0.44028635073, 0.55971364926, 0.], [0.31395396638, 0.28693232061, 0.399113713]]], dtype=np.float32) self.assertAllClose(expected_scores, actual_scores) # Expected tensor of shape [1, 3, 1]. # expected000 = 0.5 # expected010 = 0.44028635073 * 0.5 + 0.55971364926 * 0.8 # = 0.66791409477 # expected020 = 0.31395396638 * 0.5 +0.28693232061 * 0.8 -0.399113713 * 0.3 # = 0.26678872577 expected = np.array([[[0.5], [0.66791409477], [0.26678872577]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_inputs_not_list(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) with self.assertRaisesRegex( ValueError, 'Attention layer must be called on a list of inputs'): attention_layer(q) def test_inputs_too_short(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) with self.assertRaisesRegex( ValueError, 'Attention layer accepts inputs list of length 2 or 3'): attention_layer([q]) def test_inputs_too_long(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) with self.assertRaisesRegex( ValueError, 'Attention layer accepts inputs list of length 2 or 3'): attention_layer([q, q, q, q]) def test_mask_not_list(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) mask = np.array([[True]], dtype=np.bool_) with self.assertRaisesRegex(ValueError, 'Attention layer mask must be a list'): attention_layer([q, q], mask=mask) def test_mask_too_short(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) mask = np.array([[True]], dtype=np.bool_) with self.assertRaisesRegex( ValueError, 'Attention layer mask must be a list of length 2'): attention_layer([q, q], mask=[mask]) def test_mask_too_long(self): attention_layer = dense_attention.Attention() q = np.array([[[1.1]]], dtype=np.float32) mask = np.array([[True]], dtype=np.bool_) with self.assertRaisesRegex( ValueError, 'Attention layer mask must be a list of length 2'): attention_layer([q, q], mask=[mask, mask, mask]) def test_override_mask(self): attention_layer = dense_attention.Attention() q = core.Masking()(np.array([[[1.1]]], dtype=np.float32)) mask = np.array([[False]], dtype=np.bool_) actual = attention_layer([q, q], mask=[mask, mask]) self.assertAllClose([[[0]]], actual) def test_implicit_mask(self): attention_layer = dense_attention.Attention() q = core.Masking(1.1)(np.array([[[1.1], [1]]], dtype=np.float32)) v = core.Masking(1.2)(np.array([[[1.2], [1]]], dtype=np.float32)) actual = attention_layer([q, v]) self.assertAllClose([[[0], [1]]], actual) @parameterized.named_parameters( ('', False), ('use_scale', True), ) def test_serialization(self, use_scale): # Test serialization with use_scale layer = dense_attention.Attention(use_scale=use_scale) config = keras.layers.serialize(layer) new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.use_scale, use_scale) config = layer.get_config() new_layer = dense_attention.Attention.from_config(config) self.assertEqual(new_layer.use_scale, use_scale) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class AdditiveAttentionTest(tf.test.TestCase, parameterized.TestCase): def test_calculate_scores_one_dim(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Key tensor of shape [1, 1, 1] k = np.array([[[1.6]]], dtype=np.float32) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1])) # Scale tensor of shape [1] attention_layer.scale = np.array([[[0.5]]], dtype=np.float32) actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [1, 1, 1]. # expected000 = 0.5 * tanh(1.1 + 1.6) = 0.49550372683 expected = np.array([[[0.49550372683]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_calculate_scores_multi_dim(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Key tensor of shape [1, 3, 4] k = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([1, 2, 4], [1, 3, 4])) # Scale tensor of shape [4] attention_layer.scale = np.array([[[0.5, 0.6, 0.7, 0.8]]], dtype=np.float32) actual = attention_layer._calculate_scores(query=q, key=k) # pylint:disable=line-too-long # expected000 = 0.5*tanh(1.+1.5) + 0.6*tanh(1.1+1.6) + 0.7*tanh(1.2+1.7) + 0.8*tanh(1.3+1.8) = 2.58044532581 # expected001 = 0.5*tanh(1.+2.5) + 0.6*tanh(1.1+2.6) + 0.7*tanh(1.2+2.7) + 0.8*tanh(1.3+2.8) = 2.59734317449 # expected002 = 0.5*tanh(1.+3.5) + 0.6*tanh(1.1+3.6) + 0.7*tanh(1.2+3.7) + 0.8*tanh(1.3+3.8) = 2.59964024652 # expected010 = 0.5*tanh(2.+1.5) + 0.6*tanh(2.1+1.6) + 0.7*tanh(2.2+1.7) + 0.8*tanh(2.3+1.8) = 2.59734317449 # expected011 = 0.5*tanh(2.+2.5) + 0.6*tanh(2.1+2.6) + 0.7*tanh(2.2+2.7) + 0.8*tanh(2.3+2.8) = 2.59964024652 # expected012 = 0.5*tanh(2.+3.5) + 0.6*tanh(2.1+3.6) + 0.7*tanh(2.2+3.7) + 0.8*tanh(2.3+3.8) = 2.59995130916 # pylint:enable=line-too-long expected = np.array([[[2.58044532581, 2.59734317449, 2.59964024652], [2.59734317449, 2.59964024652, 2.59995130916]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_calculate_scores_one_dim_batch_size_two(self): # Query tensor of shape [2, 1, 1] q = np.array([[[1.1]], [[2.1]]], dtype=np.float32) # Key tensor of shape [2, 1, 1] k = np.array([[[1.6]], [[2.6]]], dtype=np.float32) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([2, 1, 1], [2, 1, 1])) # Scale tensor of shape [1] attention_layer.scale = np.array([[[0.5]]], dtype=np.float32) actual = attention_layer._calculate_scores(query=q, key=k) # Expected tensor of shape [2, 1, 1]. # expected000 = 0.5 * tanh(1.1 + 1.6) = 0.49550372683 # expected100 = 0.5 * tanh(2.1 + 2.6) = 0.49991728277 expected = np.array([[[0.49550372683]], [[0.49991728277]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_shape(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Value tensor of shape [1, 3, 4] v = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention() actual = attention_layer([q, v], mask=[None, v_mask]) expected_shape = [1, 2, 4] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_shape_no_scale(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Value tensor of shape [1, 3, 4] v = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention(use_scale=False) actual = attention_layer([q, v], mask=[None, v_mask]) expected_shape = [1, 2, 4] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_shape_with_key(self): # Query tensor of shape [1, 2, 4] q = np.array([[[1., 1.1, 1.2, 1.3], [2., 2.1, 2.2, 2.3]]], dtype=np.float32) # Value tensor of shape [1, 3, 4] v = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Key tensor of shape [1, 3, 4] k = np.array( [[[1.5, 1.6, 1.7, 1.8], [2.5, 2.6, 2.7, 2.8], [3.5, 3.6, 3.7, 3.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention() actual = attention_layer([q, v, k], mask=[None, v_mask]) expected_shape = [1, 2, 4] self.assertAllEqual(expected_shape, tf.shape(actual)) def test_multi_dim(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1])) # Scale tensor of shape [1] attention_layer.scale = np.array([[[0.5]]], dtype=np.float32) actual = attention_layer([q, v], mask=[None, v_mask]) # pylint:disable=line-too-long # Expected scores of shape [1, 1, 3] # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)]]] # = [[[0.49550372683, 0.47340300642, 0.14565630622]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.50552495521 # attention_distribution001 # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.49447504478 # attention_distribution002 = 0 # # Expected tensor of shape [1, 1, 1]. # expected000 = 0.50552495521 * 1.6 + 0.49447504478 * 0.7 - 0 * 0.8 # = 1.15497245968 # pylint:enable=line-too-long expected = np.array([[[1.15497245968]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_multi_dim_with_key(self): # Query tensor of shape [1, 1, 1] q = np.array([[[1.1]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[0.5], [0.8], [-0.3]]], dtype=np.float32) # Key tensor of shape [1, 3, 1] k = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1])) # Scale tensor of shape [1] attention_layer.scale = np.array([[[0.5]]], dtype=np.float32) actual = attention_layer([q, v, k], mask=[None, v_mask]) # pylint:disable=line-too-long # Expected scores of shape [1, 1, 3] # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)]]] # = [[[0.49550372683, 0.47340300642, 0.14565630622]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.50552495521 # attention_distribution001 # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.49447504478 # attention_distribution002 = 0 # # Expected tensor of shape [1, 1, 1]. # expected000 = 0.50552495521 * 0.5 + 0.49447504478 * 0.8 - 0 * 0.3 # = 0.64834251342 # pylint:enable=line-too-long expected = np.array([[[0.64834251342]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_multi_dim_with_query_mask(self): # Query tensor of shape [1, 2, 1] q = np.array([[[1.1], [-0.5]]], dtype=np.float32) # Value tensor of shape [1, 3, 1] v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32) # Query mask tensor of shape [1, 2] q_mask = np.array([[True, False]], dtype=np.bool_) # Value mask tensor of shape [1, 3] v_mask = np.array([[True, True, False]], dtype=np.bool_) attention_layer = dense_attention.AdditiveAttention() attention_layer.build(input_shape=([1, 1, 1], [1, 3, 1])) # Scale tensor of shape [1] attention_layer.scale = np.array([[[0.5]]], dtype=np.float32) actual = attention_layer([q, v], mask=[q_mask, v_mask]) # pylint:disable=line-too-long # Expected scores of shape [1, 2, 3] # scores = [[[0.5 * tanh(1.1 + 1.6), 0.5 * tanh(1.1 + 0.7), 0.5 * tanh(1.1 - 0.8)], # [0.5 * tanh(-0.5 + 1.6), 0.5 * tanh(-0.5 + 0.7), 0.5 * tanh(-0.5 - 0.8)]]] # = [[[0.49550372683, 0.47340300642, 0.14565630622], # [0.40024951088, 0.09868766011, -0.43086157965]]] # Expected attention distribution = softmax(scores) with zeros in # positions where v_mask == False. # => attention_distribution000 # = exp(0.49550372683)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.50552495521 # attention_distribution001 # = exp(0.47340300642)/(exp(0.49550372683) + exp(0.47340300642)) # = 0.49447504478 # attention_distribution002 = 0 # => attention_distribution010 # = exp(0.40024951088)/(exp(0.40024951088) + exp(0.09868766011)) # = 0.57482427975 # attention_distribution011 # = exp(0.09868766011)/(exp(0.40024951088) + exp(0.09868766011)) # = 0.42517572025 # attention_distribution012 = 0 # # Expected tensor of shape [1, 2, 1] with zeros where q_mask == False. # expected000 = 0.50552495521 * 1.6 + 0.49447504478 * 0.7 - 0 * 0.8 # = 1.15497245968 # expected000 = 0 # pylint:enable=line-too-long expected = np.array([[[1.15497245968], [0.]]], dtype=np.float32) self.assertAllClose(expected, actual) def test_serialization(self): # Test serialization with use_scale layer = dense_attention.AdditiveAttention(use_scale=True) config = keras.layers.serialize(layer) new_layer = keras.layers.deserialize(config) self.assertEqual(new_layer.use_scale, True) config = layer.get_config() new_layer = dense_attention.AdditiveAttention.from_config(config) self.assertEqual(new_layer.use_scale, True) @testing_utils.enable_v2_dtype_behavior def test_mixed_float16_policy(self): # Test case for GitHub issue: # https://github.com/tensorflow/tensorflow/issues/46064 with policy.policy_scope('mixed_float16'): q = tf.cast(tf.random.uniform((2, 3, 4), seed=1), 'float16') v = tf.cast(tf.random.uniform((2, 3, 4), seed=2), 'float16') k = tf.cast(tf.random.uniform((2, 3, 4), seed=3), 'float16') layer = dense_attention.AdditiveAttention(causal=True) _ = layer([q, v, k]) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) class LowerTriangularMaskTest(tf.test.TestCase, parameterized.TestCase): def test_square_shape(self): actual = dense_attention._lower_triangular_mask([3, 3]) expected = np.array( [[True, False, False], [True, True, False], [True, True, True]], dtype=np.bool_) self.assertAllEqual(expected, actual) def test_orthogonal_shape(self): actual = dense_attention._lower_triangular_mask([3, 2]) expected = np.array([[True, False], [True, True], [True, True]], dtype=np.bool_) self.assertAllEqual(expected, actual) def test_three_dim(self): actual = dense_attention._lower_triangular_mask([1, 3, 3]) expected = np.array( [[[True, False, False], [True, True, False], [True, True, True]]], dtype=np.bool_) self.assertAllEqual(expected, actual) if __name__ == '__main__': tf.test.main()
34,784
42.754717
112
py
keras
keras-master/keras/layers/embeddings.py
# 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. # ============================================================================== """Embedding layer.""" import tensorflow.compat.v2 as tf # pylint: disable=g-classes-have-attributes from keras import backend from keras import constraints from keras import initializers from keras import regularizers from keras.engine import base_layer_utils from keras.engine.base_layer import Layer from keras.utils import tf_utils from tensorflow.python.util.tf_export import keras_export @keras_export('keras.layers.Embedding') class Embedding(Layer): """Turns positive integers (indexes) into dense vectors of fixed size. e.g. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]` This layer can only be used as the first layer in a model. Example: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Embedding(1000, 64, input_length=10)) >>> # The model will take as input an integer matrix of size (batch, >>> # input_length), and the largest integer (i.e. word index) in the input >>> # should be no larger than 999 (vocabulary size). >>> # Now model.output_shape is (None, 10, 64), where `None` is the batch >>> # dimension. >>> input_array = np.random.randint(1000, size=(32, 10)) >>> model.compile('rmsprop', 'mse') >>> output_array = model.predict(input_array) >>> print(output_array.shape) (32, 10, 64) Args: input_dim: Integer. Size of the vocabulary, i.e. maximum integer index + 1. output_dim: Integer. Dimension of the dense embedding. embeddings_initializer: Initializer for the `embeddings` matrix (see `keras.initializers`). embeddings_regularizer: Regularizer function applied to the `embeddings` matrix (see `keras.regularizers`). embeddings_constraint: Constraint function applied to the `embeddings` matrix (see `keras.constraints`). mask_zero: Boolean, whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is `True`, then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal size of vocabulary + 1). input_length: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). Input shape: 2D tensor with shape: `(batch_size, input_length)`. Output shape: 3D tensor with shape: `(batch_size, input_length, output_dim)`. **Note on variable placement:** By default, if a GPU is available, the embedding matrix will be placed on the GPU. This achieves the best performance, but it might cause issues: - You may be using an optimizer that does not support sparse GPU kernels. In this case you will see an error upon training your model. - Your embedding matrix may be too large to fit on your GPU. In this case you will see an Out Of Memory (OOM) error. In such cases, you should place the embedding matrix on the CPU memory. You can do so with a device scope, as such: ```python with tf.device('cpu:0'): embedding_layer = Embedding(...) embedding_layer.build() ``` The pre-built `embedding_layer` instance can then be added to a `Sequential` model (e.g. `model.add(embedding_layer)`), called in a Functional model (e.g. `x = embedding_layer(x)`), or used in a subclassed model. """ def __init__(self, input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None, **kwargs): if 'input_shape' not in kwargs: if input_length: kwargs['input_shape'] = (input_length,) else: kwargs['input_shape'] = (None,) if input_dim <= 0 or output_dim <= 0: raise ValueError( 'Both `input_dim` and `output_dim` should be positive, ' f'Received input_dim = {input_dim} and output_dim = {output_dim}') if (not base_layer_utils.v2_dtype_behavior_enabled() and 'dtype' not in kwargs): # In TF1, the dtype defaults to the input dtype which is typically int32, # so explicitly set it to floatx kwargs['dtype'] = backend.floatx() # We set autocast to False, as we do not want to cast floating- point inputs # to self.dtype. In call(), we cast to int32, and casting to self.dtype # before casting to int32 might cause the int32 values to be different due # to a loss of precision. kwargs['autocast'] = False super(Embedding, self).__init__(**kwargs) self.input_dim = input_dim self.output_dim = output_dim self.embeddings_initializer = initializers.get(embeddings_initializer) self.embeddings_regularizer = regularizers.get(embeddings_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.embeddings_constraint = constraints.get(embeddings_constraint) self.mask_zero = mask_zero self.supports_masking = mask_zero self.input_length = input_length @tf_utils.shape_type_conversion def build(self, input_shape=None): self.embeddings = self.add_weight( shape=(self.input_dim, self.output_dim), initializer=self.embeddings_initializer, name='embeddings', regularizer=self.embeddings_regularizer, constraint=self.embeddings_constraint, experimental_autocast=False) self.built = True def compute_mask(self, inputs, mask=None): if not self.mask_zero: return None return tf.not_equal(inputs, 0) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.input_length is None: return input_shape + (self.output_dim,) else: # input_length can be tuple if input is 3D or higher if isinstance(self.input_length, (list, tuple)): in_lens = list(self.input_length) else: in_lens = [self.input_length] if len(in_lens) != len(input_shape) - 1: raise ValueError( f'"input_length" is {self.input_length}, but received input has ' f'shape {input_shape}') else: for i, (s1, s2) in enumerate(zip(in_lens, input_shape[1:])): if s1 is not None and s2 is not None and s1 != s2: raise ValueError( f'"input_length" is {self.input_length}, but received input ' f'has shape {input_shape}') elif s1 is None: in_lens[i] = s2 return (input_shape[0],) + tuple(in_lens) + (self.output_dim,) def call(self, inputs): dtype = backend.dtype(inputs) if dtype != 'int32' and dtype != 'int64': inputs = tf.cast(inputs, 'int32') out = tf.nn.embedding_lookup(self.embeddings, inputs) if self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype: # Instead of casting the variable as in most layers, cast the output, as # this is mathematically equivalent but is faster. out = tf.cast(out, self._dtype_policy.compute_dtype) return out def get_config(self): config = { 'input_dim': self.input_dim, 'output_dim': self.output_dim, 'embeddings_initializer': initializers.serialize(self.embeddings_initializer), 'embeddings_regularizer': regularizers.serialize(self.embeddings_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'embeddings_constraint': constraints.serialize(self.embeddings_constraint), 'mask_zero': self.mask_zero, 'input_length': self.input_length } base_config = super(Embedding, self).get_config() return dict(list(base_config.items()) + list(config.items()))
8,712
39.525581
80
py
keras
keras-master/keras/layers/convolutional_test.py
# 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 convolutional layers.""" import tensorflow.compat.v2 as tf from absl.testing import parameterized import numpy as np import keras from tensorflow.python.framework import test_util from keras import keras_parameterized from keras import testing_utils @keras_parameterized.run_all_keras_modes class Conv1DTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape): num_samples = 2 stack_size = 3 length = 7 with self.cached_session(): testing_utils.layer_test( keras.layers.Conv1D, kwargs=kwargs, input_shape=(num_samples, length, stack_size), expected_output_shape=expected_output_shape) def _run_test_extra_batch_dim(self, kwargs, expected_output_shape): batch_shape = (2, 11) stack_size = 3 length = 7 with self.cached_session(): if expected_output_shape is not None: expected_output_shape = (None,) + expected_output_shape testing_utils.layer_test( keras.layers.Conv1D, kwargs=kwargs, input_shape=batch_shape + (length, stack_size), expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', { 'padding': 'valid' }, (None, 5, 2)), ('padding_same', { 'padding': 'same' }, (None, 7, 2)), ('padding_same_dilation_2', { 'padding': 'same', 'dilation_rate': 2 }, (None, 7, 2)), ('padding_same_dilation_3', { 'padding': 'same', 'dilation_rate': 3 }, (None, 7, 2)), ('padding_causal', { 'padding': 'causal' }, (None, 7, 2)), ('strides', { 'strides': 2 }, (None, 3, 2)), ('dilation_rate', { 'dilation_rate': 2 }, (None, 3, 2)), # Only runs on GPU with CUDA, groups are not supported on CPU. # https://github.com/tensorflow/tensorflow/issues/29005 ('group', { 'groups': 3, 'filters': 6 }, (None, 5, 6), True), ) def test_conv1d(self, kwargs, expected_output_shape, requires_gpu=False): kwargs['filters'] = kwargs.get('filters', 2) kwargs['kernel_size'] = 3 if not requires_gpu or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape) self._run_test_extra_batch_dim(kwargs, expected_output_shape) def test_conv1d_regularizers(self): kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv1D(**kwargs) layer.build((None, 5, 2)) self.assertEqual(len(layer.losses), 2) layer(keras.backend.variable(np.ones((1, 5, 2)))) self.assertEqual(len(layer.losses), 3) def test_conv1d_constraints(self): k_constraint = lambda x: x b_constraint = lambda x: x kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_constraint': k_constraint, 'bias_constraint': b_constraint, 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv1D(**kwargs) layer.build((None, 5, 2)) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) def test_conv1d_recreate_conv(self): with self.cached_session(): layer = keras.layers.Conv1D(filters=1, kernel_size=3, strides=1, dilation_rate=2, padding='causal') inpt1 = np.random.normal(size=[1, 2, 1]) inpt2 = np.random.normal(size=[1, 1, 1]) outp1_shape = layer(inpt1).shape _ = layer(inpt2).shape self.assertEqual(outp1_shape, layer(inpt1).shape) def test_conv1d_recreate_conv_unknown_dims(self): with self.cached_session(): layer = keras.layers.Conv1D(filters=1, kernel_size=3, strides=1, dilation_rate=2, padding='causal') inpt1 = np.random.normal(size=[1, 9, 1]).astype(np.float32) inpt2 = np.random.normal(size=[1, 2, 1]).astype(np.float32) outp1_shape = layer(inpt1).shape @tf.function(input_signature=[ tf.TensorSpec([1, None, 1])]) def fn(inpt): return layer(inpt) fn(inpt2) self.assertEqual(outp1_shape, layer(inpt1).shape) @keras_parameterized.run_all_keras_modes class Conv2DTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape, spatial_shape=(7, 6)): num_samples = 2 stack_size = 3 num_row, num_col = spatial_shape input_data = None # Generate valid input data. if None in spatial_shape: input_data_shape = (num_samples, num_row or 7, num_col or 6, stack_size) input_data = 10 * np.random.random(input_data_shape).astype(np.float32) with self.cached_session(): testing_utils.layer_test( keras.layers.Conv2D, kwargs=kwargs, input_shape=(num_samples, num_row, num_col, stack_size), input_data=input_data, expected_output_shape=expected_output_shape) def _run_test_extra_batch_dim(self, kwargs, expected_output_shape, spatial_shape=(7, 6)): batch_shape = (2, 11) stack_size = 3 num_row, num_col = spatial_shape input_data = None # Generate valid input data. if None in spatial_shape: input_data_shape = batch_shape + (num_row or 7, num_col or 6, stack_size) input_data = 10 * np.random.random(input_data_shape).astype(np.float32) with self.cached_session(): if expected_output_shape is not None: expected_output_shape = (None,) + expected_output_shape testing_utils.layer_test( keras.layers.Conv2D, kwargs=kwargs, input_shape=batch_shape + (num_row, num_col, stack_size), input_data=input_data, expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', { 'padding': 'valid' }, (None, 5, 4, 2)), ('padding_same', { 'padding': 'same' }, (None, 7, 6, 2)), ('padding_same_dilation_2', { 'padding': 'same', 'dilation_rate': 2 }, (None, 7, 6, 2)), ('strides', { 'strides': (2, 2) }, (None, 3, 2, 2)), ('dilation_rate', { 'dilation_rate': (2, 2) }, (None, 3, 2, 2)), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', { 'data_format': 'channels_first' }, None, True), # Only runs on GPU with CUDA, groups are not supported on CPU. # https://github.com/tensorflow/tensorflow/issues/29005 ('group', { 'groups': 3, 'filters': 6 }, (None, 5, 4, 6), True), ('dilation_2_unknown_width', { 'dilation_rate': (2, 2) }, (None, None, 2, 2), False, (None, 6)), ('dilation_2_unknown_height', { 'dilation_rate': (2, 2) }, (None, 3, None, 2), False, (7, None)), ) def test_conv2d(self, kwargs, expected_output_shape=None, requires_gpu=False, spatial_shape=(7, 6)): kwargs['filters'] = kwargs.get('filters', 2) kwargs['kernel_size'] = (3, 3) if not requires_gpu or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape, spatial_shape) self._run_test_extra_batch_dim(kwargs, expected_output_shape, spatial_shape) def test_conv2d_regularizers(self): kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv2D(**kwargs) layer.build((None, 5, 5, 2)) self.assertEqual(len(layer.losses), 2) layer(keras.backend.variable(np.ones((1, 5, 5, 2)))) self.assertEqual(len(layer.losses), 3) def test_conv2d_constraints(self): k_constraint = lambda x: x b_constraint = lambda x: x kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_constraint': k_constraint, 'bias_constraint': b_constraint, 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv2D(**kwargs) layer.build((None, 5, 5, 2)) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) def test_conv2d_zero_kernel_size(self): kwargs = {'filters': 2, 'kernel_size': 0} with self.assertRaises(ValueError): keras.layers.Conv2D(**kwargs) @keras_parameterized.run_all_keras_modes class Conv3DTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape, validate_training=True): num_samples = 2 stack_size = 3 num_row = 7 num_col = 6 depth = 5 with self.cached_session(): testing_utils.layer_test( keras.layers.Conv3D, kwargs=kwargs, input_shape=(num_samples, depth, num_row, num_col, stack_size), expected_output_shape=expected_output_shape, validate_training=validate_training) def _run_test_extra_batch_dim(self, kwargs, expected_output_shape, validate_training=True): batch_shape = (2, 11) stack_size = 3 num_row = 7 num_col = 6 depth = 5 with self.cached_session(): if expected_output_shape is not None: expected_output_shape = (None,) + expected_output_shape testing_utils.layer_test( keras.layers.Conv3D, kwargs=kwargs, input_shape=batch_shape + (depth, num_row, num_col, stack_size), expected_output_shape=expected_output_shape, validate_training=validate_training) @parameterized.named_parameters( ('padding_valid', { 'padding': 'valid' }, (None, 3, 5, 4, 2)), ('padding_same', { 'padding': 'same' }, (None, 5, 7, 6, 2)), ('strides', { 'strides': (2, 2, 2) }, (None, 2, 3, 2, 2)), ('dilation_rate', { 'dilation_rate': (2, 2, 2) }, (None, 1, 3, 2, 2)), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', { 'data_format': 'channels_first' }, None, True), # Only runs on GPU with CUDA, groups are not supported on CPU. # https://github.com/tensorflow/tensorflow/issues/29005 ('group', { 'groups': 3, 'filters': 6 }, (None, 3, 5, 4, 6), True), ) def test_conv3d(self, kwargs, expected_output_shape=None, requires_gpu=False): kwargs['filters'] = kwargs.get('filters', 2) kwargs['kernel_size'] = (3, 3, 3) # train_on_batch currently fails with XLA enabled on GPUs test_training = 'groups' not in kwargs or not test_util.is_xla_enabled() if not requires_gpu or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape, test_training) self._run_test_extra_batch_dim(kwargs, expected_output_shape, test_training) def test_conv3d_regularizers(self): kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv3D(**kwargs) layer.build((None, 5, 5, 5, 2)) self.assertEqual(len(layer.losses), 2) self.assertEqual(len(layer.losses), 2) layer(keras.backend.variable(np.ones((1, 5, 5, 5, 2)))) self.assertEqual(len(layer.losses), 3) def test_conv3d_constraints(self): k_constraint = lambda x: x b_constraint = lambda x: x kwargs = { 'filters': 3, 'kernel_size': 3, 'padding': 'valid', 'kernel_constraint': k_constraint, 'bias_constraint': b_constraint, 'strides': 1 } with self.cached_session(): layer = keras.layers.Conv3D(**kwargs) layer.build((None, 5, 5, 5, 2)) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) def test_conv3d_dynamic_shape(self): input_data = np.random.random((1, 3, 3, 3, 3)).astype(np.float32) with self.cached_session(): # Won't raise error here. testing_utils.layer_test( keras.layers.Conv3D, kwargs={ 'data_format': 'channels_last', 'filters': 3, 'kernel_size': 3 }, input_shape=(None, None, None, None, 3), input_data=input_data) if tf.test.is_gpu_available(cuda_only=True): testing_utils.layer_test( keras.layers.Conv3D, kwargs={ 'data_format': 'channels_first', 'filters': 3, 'kernel_size': 3 }, input_shape=(None, 3, None, None, None), input_data=input_data) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) class GroupedConvTest(keras_parameterized.TestCase): @parameterized.named_parameters( ('Conv1D', keras.layers.Conv1D), ('Conv2D', keras.layers.Conv2D), ('Conv3D', keras.layers.Conv3D), ) def test_group_conv_incorrect_use(self, layer): with self.assertRaisesRegex(ValueError, 'The number of filters'): layer(16, 3, groups=3) with self.assertRaisesRegex(ValueError, 'The number of input channels'): layer(16, 3, groups=4).build((32, 12, 12, 3)) @parameterized.named_parameters( ('Conv1D', keras.layers.Conv1D, (32, 12, 32)), ('Conv2D', keras.layers.Conv2D, (32, 12, 12, 32)), ('Conv3D', keras.layers.Conv3D, (32, 12, 12, 12, 32)), ) def test_group_conv(self, layer_cls, input_shape): if tf.test.is_gpu_available(cuda_only=True): with testing_utils.use_gpu(): inputs = tf.random.uniform(shape=input_shape) layer = layer_cls(16, 3, groups=4, use_bias=False) layer.build(input_shape) input_slices = tf.split(inputs, 4, axis=-1) weight_slices = tf.split(layer.kernel, 4, axis=-1) expected_outputs = tf.concat([ tf.nn.convolution(inputs, weights) for inputs, weights in zip(input_slices, weight_slices) ], axis=-1) self.assertAllClose( layer(inputs), expected_outputs, rtol=3e-5, atol=3e-5) def test_group_conv_depthwise(self): if tf.test.is_gpu_available(cuda_only=True): with testing_utils.use_gpu(): inputs = tf.random.uniform(shape=(3, 27, 27, 32)) layer = keras.layers.Conv2D(32, 3, groups=32, use_bias=False) layer.build((3, 27, 27, 32)) weights_dw = tf.reshape(layer.kernel, [3, 3, 32, 1]) expected_outputs = tf.compat.v1.nn.depthwise_conv2d( inputs, weights_dw, strides=[1, 1, 1, 1], padding='VALID') self.assertAllClose(layer(inputs), expected_outputs, rtol=1e-5) @keras_parameterized.run_all_keras_modes class Conv1DTransposeTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape): num_samples = 2 stack_size = 3 num_col = 6 with testing_utils.use_gpu(): testing_utils.layer_test( keras.layers.Conv1DTranspose, kwargs=kwargs, input_shape=(num_samples, num_col, stack_size), expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}, (None, 8, 2)), ('padding_same', {'padding': 'same'}, (None, 6, 2)), ('strides', {'strides': 2}, (None, 13, 2)), # Only runs on GPU with CUDA, dilation_rate>1 is not supported on CPU. ('dilation_rate', {'dilation_rate': 2}, (None, 10, 2)), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', {'data_format': 'channels_first'}), ) def test_conv1d_transpose(self, kwargs, expected_output_shape=None): kwargs['filters'] = 2 kwargs['kernel_size'] = 3 if (('data_format' not in kwargs and 'dilation_rate' not in kwargs) or tf.test.is_gpu_available(cuda_only=True)): self._run_test(kwargs, expected_output_shape) @keras_parameterized.run_all_keras_modes class Conv3DTransposeTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape): num_samples = 2 stack_size = 3 num_row = 7 num_col = 6 depth = 5 with testing_utils.use_gpu(): testing_utils.layer_test( keras.layers.Conv3DTranspose, kwargs=kwargs, input_shape=(num_samples, depth, num_row, num_col, stack_size), expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}, (None, 7, 9, 8, 2)), ('padding_same', {'padding': 'same'}, (None, 5, 7, 6, 2)), ('strides', {'strides': (2, 2, 2)}, (None, 11, 15, 13, 2)), ('dilation_rate', {'dilation_rate': (2, 2, 2)}, (None, 7, 9, 8, 2)), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', {'data_format': 'channels_first'}), ) def test_conv3d_transpose(self, kwargs, expected_output_shape=None): kwargs['filters'] = 2 kwargs['kernel_size'] = (3, 3, 3) if 'data_format' not in kwargs or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape) @keras_parameterized.run_all_keras_modes class ConvSequentialTest(keras_parameterized.TestCase): def _run_test(self, conv_layer_cls, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2): kwargs['filters'] = 1 kwargs['kernel_size'] = 3 kwargs['dilation_rate'] = 2 with self.cached_session(): layer = conv_layer_cls(**kwargs) output1 = layer(np.zeros(input_shape1)) self.assertEqual(output1.shape, expected_output_shape1) output2 = layer(np.zeros(input_shape2)) self.assertEqual(output2.shape, expected_output_shape2) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}, (1, 8, 2), (1, 5, 2), (1, 4, 1), (1, 1, 1)), ('padding_same', {'padding': 'same'}, (1, 8, 2), (1, 5, 2), (1, 8, 1), (1, 5, 1)), ('padding_causal', {'padding': 'causal'}, (1, 8, 2), (1, 5, 2), (1, 8, 1), (1, 5, 1)), ) def test_conv1d(self, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2): self._run_test(keras.layers.Conv1D, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}, (1, 7, 6, 2), (1, 6, 5, 2), (1, 3, 2, 1), (1, 2, 1, 1)), ('padding_same', {'padding': 'same'}, (1, 7, 6, 2), (1, 6, 5, 2), (1, 7, 6, 1), (1, 6, 5, 1)), ) def test_conv2d(self, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2): self._run_test(keras.layers.Conv2D, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}, (1, 5, 7, 6, 2), (1, 8, 6, 5, 2), (1, 1, 3, 2, 1), (1, 4, 2, 1, 1)), ('padding_same', {'padding': 'same'}, (1, 5, 7, 6, 2), (1, 8, 6, 5, 2), (1, 5, 7, 6, 1), (1, 8, 6, 5, 1)), ) def test_conv3d(self, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2): self._run_test(keras.layers.Conv3D, kwargs, input_shape1, input_shape2, expected_output_shape1, expected_output_shape2) def test_dynamic_shape(self): with self.cached_session(): layer = keras.layers.Conv3D(2, 3) input_shape = (5, None, None, 2) inputs = keras.Input(shape=input_shape) x = layer(inputs) # Won't raise error here with None values in input shape (b/144282043). layer(x) @keras_parameterized.run_all_keras_modes class ZeroPaddingTest(keras_parameterized.TestCase): def test_zero_padding_1d(self): num_samples = 2 input_dim = 2 num_steps = 5 shape = (num_samples, num_steps, input_dim) inputs = np.ones(shape) with self.cached_session(): # basic test testing_utils.layer_test( keras.layers.ZeroPadding1D, kwargs={'padding': 2}, input_shape=inputs.shape) testing_utils.layer_test( keras.layers.ZeroPadding1D, kwargs={'padding': (1, 2)}, input_shape=inputs.shape) # correctness test layer = keras.layers.ZeroPadding1D(padding=2) layer.build(shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) for offset in [0, 1, -1, -2]: np.testing.assert_allclose(np_output[:, offset, :], 0.) np.testing.assert_allclose(np_output[:, 2:-2, :], 1.) layer = keras.layers.ZeroPadding1D(padding=(1, 2)) layer.build(shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) for left_offset in [0]: np.testing.assert_allclose(np_output[:, left_offset, :], 0.) for right_offset in [-1, -2]: np.testing.assert_allclose(np_output[:, right_offset, :], 0.) np.testing.assert_allclose(np_output[:, 1:-2, :], 1.) layer.get_config() # test incorrect use with self.assertRaises(ValueError): keras.layers.ZeroPadding1D(padding=(1, 1, 1)) with self.assertRaises(ValueError): keras.layers.ZeroPadding1D(padding=None) @parameterized.named_parameters(('channels_first', 'channels_first'), ('channels_last', 'channels_last')) def test_zero_padding_2d(self, data_format): num_samples = 2 stack_size = 2 input_num_row = 4 input_num_col = 5 if data_format == 'channels_first': inputs = np.ones((num_samples, stack_size, input_num_row, input_num_col)) elif data_format == 'channels_last': inputs = np.ones((num_samples, input_num_row, input_num_col, stack_size)) # basic test with self.cached_session(): testing_utils.layer_test( keras.layers.ZeroPadding2D, kwargs={ 'padding': (2, 2), 'data_format': data_format }, input_shape=inputs.shape) testing_utils.layer_test( keras.layers.ZeroPadding2D, kwargs={ 'padding': ((1, 2), (3, 4)), 'data_format': data_format }, input_shape=inputs.shape) # correctness test with self.cached_session(): layer = keras.layers.ZeroPadding2D( padding=(2, 2), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_last': for offset in [0, 1, -1, -2]: np.testing.assert_allclose(np_output[:, offset, :, :], 0.) np.testing.assert_allclose(np_output[:, :, offset, :], 0.) np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.) elif data_format == 'channels_first': for offset in [0, 1, -1, -2]: np.testing.assert_allclose(np_output[:, :, offset, :], 0.) np.testing.assert_allclose(np_output[:, :, :, offset], 0.) np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.) layer = keras.layers.ZeroPadding2D( padding=((1, 2), (3, 4)), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_last': for top_offset in [0]: np.testing.assert_allclose(np_output[:, top_offset, :, :], 0.) for bottom_offset in [-1, -2]: np.testing.assert_allclose(np_output[:, bottom_offset, :, :], 0.) for left_offset in [0, 1, 2]: np.testing.assert_allclose(np_output[:, :, left_offset, :], 0.) for right_offset in [-1, -2, -3, -4]: np.testing.assert_allclose(np_output[:, :, right_offset, :], 0.) np.testing.assert_allclose(np_output[:, 1:-2, 3:-4, :], 1.) elif data_format == 'channels_first': for top_offset in [0]: np.testing.assert_allclose(np_output[:, :, top_offset, :], 0.) for bottom_offset in [-1, -2]: np.testing.assert_allclose(np_output[:, :, bottom_offset, :], 0.) for left_offset in [0, 1, 2]: np.testing.assert_allclose(np_output[:, :, :, left_offset], 0.) for right_offset in [-1, -2, -3, -4]: np.testing.assert_allclose(np_output[:, :, :, right_offset], 0.) np.testing.assert_allclose(np_output[:, :, 1:-2, 3:-4], 1.) # test incorrect use with self.assertRaises(ValueError): keras.layers.ZeroPadding2D(padding=(1, 1, 1)) with self.assertRaises(ValueError): keras.layers.ZeroPadding2D(padding=None) @parameterized.named_parameters(('channels_first', 'channels_first'), ('channels_last', 'channels_last')) def test_zero_padding_3d(self, data_format): num_samples = 2 stack_size = 2 input_len_dim1 = 4 input_len_dim2 = 5 input_len_dim3 = 3 if data_format == 'channels_first': inputs = np.ones((num_samples, stack_size, input_len_dim1, input_len_dim2, input_len_dim3)) elif data_format == 'channels_last': inputs = np.ones((num_samples, input_len_dim1, input_len_dim2, input_len_dim3, stack_size)) with self.cached_session(): # basic test testing_utils.layer_test( keras.layers.ZeroPadding3D, kwargs={ 'padding': (2, 2, 2), 'data_format': data_format }, input_shape=inputs.shape) testing_utils.layer_test( keras.layers.ZeroPadding3D, kwargs={ 'padding': ((1, 2), (3, 4), (0, 2)), 'data_format': data_format }, input_shape=inputs.shape) with self.cached_session(): # correctness test layer = keras.layers.ZeroPadding3D( padding=(2, 2, 2), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_last': for offset in [0, 1, -1, -2]: np.testing.assert_allclose(np_output[:, offset, :, :, :], 0.) np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, 2:-2, :], 1.) elif data_format == 'channels_first': for offset in [0, 1, -1, -2]: np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) np.testing.assert_allclose(np_output[:, :, :, :, offset], 0.) np.testing.assert_allclose(np_output[:, :, 2:-2, 2:-2, 2:-2], 1.) layer = keras.layers.ZeroPadding3D( padding=((1, 2), (3, 4), (0, 2)), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_last': for offset in [0]: np.testing.assert_allclose(np_output[:, offset, :, :, :], 0.) for offset in [-1, -2]: np.testing.assert_allclose(np_output[:, offset, :, :, :], 0.) for offset in [0, 1, 2]: np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) for offset in [-1, -2, -3, -4]: np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) for offset in [-1, -2]: np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) np.testing.assert_allclose(np_output[:, 1:-2, 3:-4, 0:-2, :], 1.) elif data_format == 'channels_first': for offset in [0]: np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) for offset in [-1, -2]: np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) for offset in [0, 1, 2]: np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) for offset in [-1, -2, -3, -4]: np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) for offset in [-1, -2]: np.testing.assert_allclose(np_output[:, :, :, :, offset], 0.) np.testing.assert_allclose(np_output[:, :, 1:-2, 3:-4, 0:-2], 1.) # test incorrect use with self.assertRaises(ValueError): keras.layers.ZeroPadding3D(padding=(1, 1)) with self.assertRaises(ValueError): keras.layers.ZeroPadding3D(padding=None) @test_util.for_all_test_methods(test_util.disable_xla, 'align_corners=False not supported by XLA') @keras_parameterized.run_all_keras_modes class UpSamplingTest(keras_parameterized.TestCase): def test_upsampling_1d(self): with self.cached_session(): testing_utils.layer_test( keras.layers.UpSampling1D, kwargs={'size': 2}, input_shape=(3, 5, 4)) def test_upsampling_2d(self): num_samples = 2 stack_size = 2 input_num_row = 11 input_num_col = 12 for data_format in ['channels_first', 'channels_last']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_num_row, input_num_col) else: inputs = np.random.rand(num_samples, input_num_row, input_num_col, stack_size) # basic test with self.cached_session(): testing_utils.layer_test( keras.layers.UpSampling2D, kwargs={'size': (2, 2), 'data_format': data_format}, input_shape=inputs.shape) for length_row in [2]: for length_col in [2, 3]: layer = keras.layers.UpSampling2D( size=(length_row, length_col), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_first': assert np_output.shape[2] == length_row * input_num_row assert np_output.shape[3] == length_col * input_num_col else: # tf assert np_output.shape[1] == length_row * input_num_row assert np_output.shape[2] == length_col * input_num_col # compare with numpy if data_format == 'channels_first': expected_out = np.repeat(inputs, length_row, axis=2) expected_out = np.repeat(expected_out, length_col, axis=3) else: # tf expected_out = np.repeat(inputs, length_row, axis=1) expected_out = np.repeat(expected_out, length_col, axis=2) np.testing.assert_allclose(np_output, expected_out) def test_upsampling_2d_bilinear(self): num_samples = 2 stack_size = 2 input_num_row = 11 input_num_col = 12 for data_format in ['channels_first', 'channels_last']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_num_row, input_num_col) else: inputs = np.random.rand(num_samples, input_num_row, input_num_col, stack_size) testing_utils.layer_test(keras.layers.UpSampling2D, kwargs={'size': (2, 2), 'data_format': data_format, 'interpolation': 'bilinear'}, input_shape=inputs.shape) if not tf.executing_eagerly(): for length_row in [2]: for length_col in [2, 3]: layer = keras.layers.UpSampling2D( size=(length_row, length_col), data_format=data_format) layer.build(inputs.shape) outputs = layer(keras.backend.variable(inputs)) np_output = keras.backend.eval(outputs) if data_format == 'channels_first': self.assertEqual(np_output.shape[2], length_row * input_num_row) self.assertEqual(np_output.shape[3], length_col * input_num_col) else: self.assertEqual(np_output.shape[1], length_row * input_num_row) self.assertEqual(np_output.shape[2], length_col * input_num_col) def test_upsampling_3d(self): num_samples = 2 stack_size = 2 input_len_dim1 = 10 input_len_dim2 = 11 input_len_dim3 = 12 for data_format in ['channels_first', 'channels_last']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_len_dim1, input_len_dim2, input_len_dim3) else: inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2, input_len_dim3, stack_size) # basic test with self.cached_session(): testing_utils.layer_test( keras.layers.UpSampling3D, kwargs={'size': (2, 2, 2), 'data_format': data_format}, input_shape=inputs.shape) for length_dim1 in [2, 3]: for length_dim2 in [2]: for length_dim3 in [3]: layer = keras.layers.UpSampling3D( size=(length_dim1, length_dim2, length_dim3), data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) if data_format == 'channels_first': assert np_output.shape[2] == length_dim1 * input_len_dim1 assert np_output.shape[3] == length_dim2 * input_len_dim2 assert np_output.shape[4] == length_dim3 * input_len_dim3 else: # tf assert np_output.shape[1] == length_dim1 * input_len_dim1 assert np_output.shape[2] == length_dim2 * input_len_dim2 assert np_output.shape[3] == length_dim3 * input_len_dim3 # compare with numpy if data_format == 'channels_first': expected_out = np.repeat(inputs, length_dim1, axis=2) expected_out = np.repeat(expected_out, length_dim2, axis=3) expected_out = np.repeat(expected_out, length_dim3, axis=4) else: # tf expected_out = np.repeat(inputs, length_dim1, axis=1) expected_out = np.repeat(expected_out, length_dim2, axis=2) expected_out = np.repeat(expected_out, length_dim3, axis=3) np.testing.assert_allclose(np_output, expected_out) @keras_parameterized.run_all_keras_modes class CroppingTest(keras_parameterized.TestCase): def test_cropping_1d(self): num_samples = 2 time_length = 4 input_len_dim1 = 2 inputs = np.random.rand(num_samples, time_length, input_len_dim1) with self.cached_session(): testing_utils.layer_test( keras.layers.Cropping1D, kwargs={'cropping': (2, 2)}, input_shape=inputs.shape) # test incorrect use with self.assertRaises(ValueError): keras.layers.Cropping1D(cropping=(1, 1, 1)) with self.assertRaises(ValueError): keras.layers.Cropping1D(cropping=None) def test_cropping_2d(self): num_samples = 2 stack_size = 2 input_len_dim1 = 9 input_len_dim2 = 9 cropping = ((2, 2), (3, 3)) for data_format in ['channels_first', 'channels_last']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_len_dim1, input_len_dim2) else: inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2, stack_size) with self.cached_session(): # basic test testing_utils.layer_test( keras.layers.Cropping2D, kwargs={'cropping': cropping, 'data_format': data_format}, input_shape=inputs.shape) # correctness test layer = keras.layers.Cropping2D( cropping=cropping, data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) # compare with numpy if data_format == 'channels_first': expected_out = inputs[:, :, cropping[0][0]:-cropping[0][1], cropping[ 1][0]:-cropping[1][1]] else: expected_out = inputs[:, cropping[0][0]:-cropping[0][1], cropping[1][ 0]:-cropping[1][1], :] np.testing.assert_allclose(np_output, expected_out) for data_format in ['channels_first', 'channels_last']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_len_dim1, input_len_dim2) else: inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2, stack_size) # another correctness test (no cropping) with self.cached_session(): cropping = ((0, 0), (0, 0)) layer = keras.layers.Cropping2D( cropping=cropping, data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) # compare with input np.testing.assert_allclose(np_output, inputs) # test incorrect use with self.assertRaises(ValueError): keras.layers.Cropping2D(cropping=(1, 1, 1)) with self.assertRaises(ValueError): keras.layers.Cropping2D(cropping=None) def test_cropping_3d(self): num_samples = 2 stack_size = 2 input_len_dim1 = 8 input_len_dim2 = 8 input_len_dim3 = 8 croppings = [((2, 2), (1, 1), (2, 3)), 3, (0, 1, 1)] for cropping in croppings: for data_format in ['channels_last', 'channels_first']: if data_format == 'channels_first': inputs = np.random.rand(num_samples, stack_size, input_len_dim1, input_len_dim2, input_len_dim3) else: inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2, input_len_dim3, stack_size) # basic test with self.cached_session(): testing_utils.layer_test( keras.layers.Cropping3D, kwargs={'cropping': cropping, 'data_format': data_format}, input_shape=inputs.shape) if len(croppings) == 3 and len(croppings[0]) == 2: # correctness test with self.cached_session(): layer = keras.layers.Cropping3D( cropping=cropping, data_format=data_format) layer.build(inputs.shape) output = layer(keras.backend.variable(inputs)) if tf.executing_eagerly(): np_output = output.numpy() else: np_output = keras.backend.eval(output) # compare with numpy if data_format == 'channels_first': expected_out = inputs[:, :, cropping[0][0]:-cropping[0][1], cropping[1][0]:-cropping[1][1], cropping[2][0]:-cropping[2][1]] else: expected_out = inputs[:, cropping[0][0]:-cropping[0][1], cropping[1][0]:-cropping[1][1], cropping[2][0]:-cropping[2][1], :] np.testing.assert_allclose(np_output, expected_out) # test incorrect use with self.assertRaises(ValueError): keras.layers.Cropping3D(cropping=(1, 1)) with self.assertRaises(ValueError): keras.layers.Cropping3D(cropping=None) @keras_parameterized.run_all_keras_modes class DepthwiseConv1DTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape=None): num_samples = 2 stack_size = 3 num_row = 7 with self.cached_session(): testing_utils.layer_test( keras.layers.DepthwiseConv1D, kwargs=kwargs, input_shape=(num_samples, num_row, stack_size), expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', { 'padding': 'valid' }), ('padding_same', { 'padding': 'same' }), ('strides', { 'strides': 2 }), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', { 'data_format': 'channels_first' }), ('depth_multiplier_1', { 'depth_multiplier': 1 }), ('depth_multiplier_2', { 'depth_multiplier': 2 }), ('dilation_rate', { 'dilation_rate': 2 }, (None, 3, 3)), ) def test_depthwise_conv1d(self, kwargs, expected_output_shape=None): kwargs['kernel_size'] = 3 if 'data_format' not in kwargs or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape) def test_depthwise_conv1d_full(self): kwargs = { 'kernel_size': 3, 'padding': 'valid', 'data_format': 'channels_last', 'dilation_rate': 1, 'activation': None, 'depthwise_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'depthwise_constraint': 'unit_norm', 'use_bias': True, 'strides': 2, 'depth_multiplier': 1, } self._run_test(kwargs) @keras_parameterized.run_all_keras_modes class DepthwiseConv2DTest(keras_parameterized.TestCase): def _run_test(self, kwargs, expected_output_shape=None): num_samples = 2 stack_size = 3 num_row = 7 num_col = 6 with self.cached_session(): testing_utils.layer_test( keras.layers.DepthwiseConv2D, kwargs=kwargs, input_shape=(num_samples, num_row, num_col, stack_size), expected_output_shape=expected_output_shape) @parameterized.named_parameters( ('padding_valid', {'padding': 'valid'}), ('padding_same', {'padding': 'same'}), ('strides', {'strides': (2, 2)}), # Only runs on GPU with CUDA, channels_first is not supported on CPU. # TODO(b/62340061): Support channels_first on CPU. ('data_format', {'data_format': 'channels_first'}), ('depth_multiplier_1', {'depth_multiplier': 1}), ('depth_multiplier_2', {'depth_multiplier': 2}), ('dilation_rate', {'dilation_rate': (2, 2)}, (None, 3, 2, 3)), ) def test_depthwise_conv2d(self, kwargs, expected_output_shape=None): kwargs['kernel_size'] = (3, 3) if 'data_format' not in kwargs or tf.test.is_gpu_available(cuda_only=True): self._run_test(kwargs, expected_output_shape) def test_depthwise_conv2d_full(self): kwargs = { 'kernel_size': 3, 'padding': 'valid', 'data_format': 'channels_last', 'dilation_rate': (1, 1), 'activation': None, 'depthwise_regularizer': 'l2', 'bias_regularizer': 'l2', 'activity_regularizer': 'l2', 'depthwise_constraint': 'unit_norm', 'use_bias': True, 'strides': (2, 2), 'depth_multiplier': 1, } self._run_test(kwargs) if __name__ == '__main__': tf.test.main()
46,546
36.207834
80
py