-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
base_layer.py
3853 lines (3346 loc) · 153 KB
/
base_layer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Contains the base Layer class, from which all layers inherit."""
import collections
import contextlib
import functools
import itertools
import textwrap
import threading
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from keras import backend
from keras import constraints
from keras import initializers
from keras import regularizers
from keras.dtensor import lazy_variable
from keras.engine import base_layer_utils
from keras.engine import input_spec
from keras.engine import keras_tensor
from keras.engine import node as node_module
from keras.mixed_precision import autocast_variable
from keras.mixed_precision import policy
from keras.saving import serialization_lib
from keras.saving.legacy.saved_model import layer_serialization
from keras.utils import generic_utils
from keras.utils import layer_utils
from keras.utils import object_identity
from keras.utils import tf_inspect
from keras.utils import tf_utils
from keras.utils import traceback_utils
from keras.utils import version_utils
# A module that only depends on `keras.layers` import these from here.
from keras.utils.generic_utils import to_snake_case # noqa: F401
from keras.utils.tf_utils import is_tensor_or_tensor_list # noqa: F401
# isort: off
from google.protobuf import json_format
from tensorflow.python.platform import tf_logging
from tensorflow.python.util.tf_export import (
get_canonical_name_for_symbol,
)
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
metrics_mod = generic_utils.LazyLoader(
"metrics_mod", globals(), "keras.metrics"
)
# Prefix that is added to the TF op layer names.
_TF_OP_LAYER_NAME_PREFIX = "tf_op_layer_"
# TODO(mdan): Should we have a single generic type for types that can be passed
# to tf.cast?
_AUTOCAST_TYPES = (tf.Tensor, tf.SparseTensor, tf.RaggedTensor)
keras_layers_gauge = tf.__internal__.monitoring.BoolGauge(
"/tensorflow/api/keras/layers", "keras layers usage", "method"
)
keras_models_gauge = tf.__internal__.monitoring.BoolGauge(
"/tensorflow/api/keras/models", "keras model usage", "method"
)
keras_api_gauge = tf.__internal__.monitoring.BoolGauge(
"/tensorflow/api/keras", "keras api usage", "method"
)
keras_premade_model_gauge = tf.__internal__.monitoring.BoolGauge(
"/tensorflow/api/keras/premade_models", "premade keras model usage", "type"
)
_is_name_scope_on_model_declaration_enabled = False
_name_scope_unnester_stack = threading.local()
@contextlib.contextmanager
def _name_scope_unnester(full_name_scope):
"""Helper to get relative name scope from fully-speced nested name scopes.
Args:
full_name_scope: full(absolute) name scope path.
Yields:
Relative name scope path from the parent `_name_scope_unnester` context
manager.
Example:
```
with _name_scope_unnester('a') as name1: # name1 == 'a'
with _name_scope_unnester('a/b') as name2: # name2 == 'b'
with _name_scope_unnester('a/b/c') as name3: # name3 == 'c'
pass
```
"""
if not getattr(_name_scope_unnester_stack, "value", None):
_name_scope_unnester_stack.value = [""]
_name_scope_unnester_stack.value.append(full_name_scope)
try:
full_name_scope = _name_scope_unnester_stack.value[-1]
outer_name_scope = _name_scope_unnester_stack.value[-2]
relative_name_scope = full_name_scope.lstrip(outer_name_scope)
relative_name_scope = relative_name_scope.lstrip("/")
yield relative_name_scope
finally:
_name_scope_unnester_stack.value.pop()
@keras_export("keras.layers.Layer")
class Layer(tf.Module, version_utils.LayerVersionSelector):
"""This is the class from which all layers inherit.
A layer is a callable object that takes as input one or more tensors and
that outputs one or more tensors. It involves *computation*, defined
in the `call()` method, and a *state* (weight variables). State can be
created in various places, at the convenience of the subclass implementer:
* in `__init__()`;
* in the optional `build()` method, which is invoked by the first
`__call__()` to the layer, and supplies the shape(s) of the input(s),
which may not have been known at initialization time;
* in the first invocation of `call()`, with some caveats discussed
below.
Layers are recursively composable: If you assign a Layer instance as an
attribute of another Layer, the outer layer will start tracking the weights
created by the inner layer. Nested layers should be instantiated in the
`__init__()` method.
Users will just instantiate a layer and then treat it as a callable.
Args:
trainable: Boolean, whether the layer's variables should be trainable.
name: String name of the layer.
dtype: The dtype of the layer's computations and weights. Can also be a
`tf.keras.mixed_precision.Policy`, which allows the computation and
weight dtype to differ. Default of `None` means to use
`tf.keras.mixed_precision.global_policy()`, which is a float32 policy
unless set to different value.
dynamic: Set this to `True` if your layer should only be run eagerly, and
should not be used to generate a static computation graph.
This would be the case for a Tree-RNN or a recursive network,
for example, or generally for any layer that manipulates tensors
using Python control flow. If `False`, we assume that the layer can
safely be used to generate a static computation graph.
Attributes:
name: The name of the layer (string).
dtype: The dtype of the layer's weights.
variable_dtype: Alias of `dtype`.
compute_dtype: The dtype of the layer's computations. Layers automatically
cast inputs to this dtype which causes the computations and output to
also be in this dtype. When mixed precision is used with a
`tf.keras.mixed_precision.Policy`, this will be different than
`variable_dtype`.
dtype_policy: The layer's dtype policy. See the
`tf.keras.mixed_precision.Policy` documentation for details.
trainable_weights: List of variables to be included in backprop.
non_trainable_weights: List of variables that should not be
included in backprop.
weights: The concatenation of the lists trainable_weights and
non_trainable_weights (in this order).
trainable: Whether the layer should be trained (boolean), i.e. whether
its potentially-trainable weights should be returned as part of
`layer.trainable_weights`.
input_spec: Optional (list of) `InputSpec` object(s) specifying the
constraints on inputs that can be accepted by the layer.
We recommend that descendants of `Layer` implement the following methods:
* `__init__()`: Defines custom layer attributes, and creates layer weights
that do not depend on input shapes, using `add_weight()`, or other state.
* `build(self, input_shape)`: This method can be used to create weights that
depend on the shape(s) of the input(s), using `add_weight()`, or other
state. `__call__()` will automatically build the layer (if it has not been
built yet) by calling `build()`.
* `call(self, inputs, *args, **kwargs)`: Called in `__call__` after making
sure `build()` has been called. `call()` performs the logic of applying
the layer to the `inputs`. The first invocation may additionally create
state that could not be conveniently created in `build()`; see its
docstring for details.
Two reserved keyword arguments you can optionally use in `call()` are:
- `training` (boolean, whether the call is in inference mode or training
mode). See more details in [the layer/model subclassing guide](
https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_training_argument_in_the_call_method)
- `mask` (boolean tensor encoding masked timesteps in the input, used
in RNN layers). See more details in
[the layer/model subclassing guide](
https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_mask_argument_in_the_call_method)
A typical signature for this method is `call(self, inputs)`, and user
could optionally add `training` and `mask` if the layer need them. `*args`
and `**kwargs` is only useful for future extension when more input
parameters are planned to be added.
* `get_config(self)`: Returns a dictionary containing the configuration used
to initialize this layer. If the keys differ from the arguments
in `__init__`, then override `from_config(self)` as well.
This method is used when saving
the layer or a model that contains this layer.
Examples:
Here's a basic example: a layer with two variables, `w` and `b`,
that returns `y = w . x + b`.
It shows how to implement `build()` and `call()`.
Variables set as attributes of a layer are tracked as weights
of the layers (in `layer.weights`).
```python
class SimpleDense(Layer):
def __init__(self, units=32):
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape): # Create the state of the layer (weights)
w_init = tf.random_normal_initializer()
self.w = tf.Variable(
initial_value=w_init(shape=(input_shape[-1], self.units),
dtype='float32'),
trainable=True)
b_init = tf.zeros_initializer()
self.b = tf.Variable(
initial_value=b_init(shape=(self.units,), dtype='float32'),
trainable=True)
def call(self, inputs): # Defines the computation from inputs to outputs
return tf.matmul(inputs, self.w) + self.b
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(tf.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
```
Note that the method `add_weight()` offers a shortcut to create weights:
```python
class SimpleDense(Layer):
def __init__(self, units=32):
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer='random_normal',
trainable=True)
self.b = self.add_weight(shape=(self.units,),
initializer='random_normal',
trainable=True)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
```
Besides trainable weights, updated via backpropagation during training,
layers can also have non-trainable weights. These weights are meant to
be updated manually during `call()`. Here's a example layer that computes
the running sum of its inputs:
```python
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = tf.Variable(initial_value=tf.zeros((input_dim,)),
trainable=False)
def call(self, inputs):
self.total.assign_add(tf.reduce_sum(inputs, axis=0))
return self.total
my_sum = ComputeSum(2)
x = tf.ones((2, 2))
y = my_sum(x)
print(y.numpy()) # [2. 2.]
y = my_sum(x)
print(y.numpy()) # [4. 4.]
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
```
For more information about creating layers, see the guide
[Making new Layers and Models via subclassing](
https://www.tensorflow.org/guide/keras/custom_layers_and_models)
"""
@tf.__internal__.tracking.no_automatic_dependency_tracking
def __init__(
self, trainable=True, name=None, dtype=None, dynamic=False, **kwargs
):
self._instrument_layer_creation()
# These properties should be set by the user via keyword arguments.
# note that 'dtype', 'input_shape' and 'batch_input_shape'
# are only applicable to input layers: do not pass these keywords
# to non-input layers.
allowed_kwargs = {
"input_dim",
"input_shape",
"batch_input_shape",
"batch_size",
"weights",
"activity_regularizer",
"autocast",
"implementation",
}
# Validate optional keyword arguments.
generic_utils.validate_kwargs(kwargs, allowed_kwargs)
# Mutable properties
# Indicates whether the layer's weights are updated during training
# and whether the layer's updates are run during training.
if not (
isinstance(trainable, bool)
or (
isinstance(trainable, (tf.Tensor, tf.Variable))
and trainable.dtype is tf.bool
)
):
raise TypeError(
"Expected `trainable` argument to be a boolean, "
f"but got: {trainable}"
)
self._trainable = trainable
# A stateful layer is a layer whose updates are run during inference
# too, for instance stateful RNNs.
self._stateful = False
# Indicates whether `build` needs to be called upon layer call, to
# create the layer's weights. (Note that the first call() may also
# create weights, independent of build().)
self.built = False
# Provides information about which inputs are compatible with the layer.
self._input_spec = None
# SavedModel-related attributes.
# Record the build input shape for loading purposes.
# TODO(kathywu): Move this to Layer._set_save_spec once cl/290121460 is
# submitted.
self._build_input_shape = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
# `Layer.compute_mask` will be called at the end of `Layer.__call__` if
# `Layer.compute_mask` is overridden, or if the `Layer` subclass sets
# `self.supports_masking=True`.
self._supports_masking = not generic_utils.is_default(self.compute_mask)
self._init_set_name(name)
self._activity_regularizer = regularizers.get(
kwargs.pop("activity_regularizer", None)
)
self._maybe_create_attribute("_trainable_weights", [])
self._maybe_create_attribute("_non_trainable_weights", [])
self._updates = []
# Object to store all thread local layer properties.
self._thread_local = threading.local()
# A list of zero-argument lambdas which return Tensors, used for
# variable regularizers.
self._callable_losses = []
# A list of symbolic Tensors containing activity regularizers and losses
# manually added through `add_loss` in graph-building mode.
self._losses = []
# A list of metric instances corresponding to the symbolic metric
# tensors added using the `add_metric` API.
self._metrics = []
# Ensures the same metric is not added multiple times in
# `MirroredStrategy`.
self._metrics_lock = threading.Lock()
# Note that models also have a dtype policy, as they are layers. For
# functional models, the policy is only used in Model.compile, which
# wraps the optimizer with a LossScaleOptimizer if the policy name is
# "mixed_float16". Subclassed models additionally use the policy's
# compute and variable dtypes, as like any ordinary layer.
self._set_dtype_policy(dtype)
# Boolean indicating whether the layer automatically casts its inputs to
# the layer's compute_dtype.
self._autocast = kwargs.get(
"autocast", base_layer_utils.v2_dtype_behavior_enabled()
)
# Tracks `TrackableDataStructure`s, `Module`s, and `Layer`s.
# Ordered by when the object was assigned as an attr.
# Entries are unique.
self._maybe_create_attribute("_self_tracked_trackables", [])
# These lists will be filled via successive calls
# to self._add_inbound_node().
# Used in symbolic mode only, only in conjunction with graph-networks
self._inbound_nodes_value = []
self._outbound_nodes_value = []
self._init_call_fn_args()
# Whether the `call` method can be used to build a TF graph without
# issues. This attribute has no effect if the model is created using
# the Functional API. Instead, `model.dynamic` is determined based on
# the internal layers.
if not isinstance(dynamic, bool):
raise TypeError(
"Expected `dynamic` argument to be a boolean, "
f"but got: {dynamic}"
)
self._dynamic = dynamic
# Manage input shape information if passed.
if "input_dim" in kwargs and "input_shape" not in kwargs:
# Backwards compatibility: alias 'input_dim' to 'input_shape'.
kwargs["input_shape"] = (kwargs["input_dim"],)
if "input_shape" in kwargs or "batch_input_shape" in kwargs:
# In this case we will later create an input layer
# to insert before the current layer
if "batch_input_shape" in kwargs:
batch_input_shape = tuple(kwargs["batch_input_shape"])
elif "input_shape" in kwargs:
if "batch_size" in kwargs:
batch_size = kwargs["batch_size"]
else:
batch_size = None
batch_input_shape = (batch_size,) + tuple(kwargs["input_shape"])
self._batch_input_shape = batch_input_shape
# Manage initial weight values if passed.
self._initial_weights = kwargs.get("weights", None)
# Whether the layer will track any layers that is set as attribute on
# itself as sub-layers, the weights from the sub-layers will be included
# in the parent layer's variables() as well. Defaults to `True`, which
# means auto tracking is turned on. Certain subclass might want to turn
# it off, like Sequential model.
self._auto_track_sub_layers = True
# For backwards compat reasons, most built-in layers do not guarantee
# That they will 100% preserve the structure of input args when saving
# / loading configs. E.g. they may un-nest an arg that is
# a list with one element.
self._preserve_input_structure_in_config = False
# Save outer name scope at layer declaration so that it is preserved at
# the actual layer construction.
self._name_scope_on_declaration = tf.get_current_name_scope()
# Save the temp regularization losses created in the DTensor use case.
# When DTensor is enable, we will first create LazyInitVariable and then
# DVariable with proper layout afterward. For the weights regularization
# loss, we have to create against the DVariable as well.
self._captured_weight_regularizer = []
@tf.__internal__.tracking.no_automatic_dependency_tracking
@generic_utils.default
def build(self, input_shape):
"""Creates the variables of the layer (for subclass implementers).
This is a method that implementers of subclasses of `Layer` or `Model`
can override if they need a state-creation step in-between
layer instantiation and layer call. It is invoked automatically before
the first execution of `call()`.
This is typically used to create the weights of `Layer` subclasses
(at the discretion of the subclass implementer).
Args:
input_shape: Instance of `TensorShape`, or list of instances of
`TensorShape` if the layer expects a list of inputs
(one instance per input).
"""
self._build_input_shape = input_shape
self.built = True
@doc_controls.for_subclass_implementers
def call(self, inputs, *args, **kwargs):
"""This is where the layer's logic lives.
The `call()` method may not create state (except in its first
invocation, wrapping the creation of variables or other resources in
`tf.init_scope()`). It is recommended to create state, including
`tf.Variable` instances and nested `Layer` instances,
in `__init__()`, or in the `build()` method that is
called automatically before `call()` executes for the first time.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
The first positional `inputs` argument is subject to special rules:
- `inputs` must be explicitly passed. A layer cannot have zero
arguments, and `inputs` cannot be provided via the default value
of a keyword argument.
- NumPy array or Python scalar values in `inputs` get cast as
tensors.
- Keras mask metadata is only collected from `inputs`.
- Layers are built (`build(input_shape)` method)
using shape info from `inputs` only.
- `input_spec` compatibility is only checked against `inputs`.
- Mixed precision input casting is only applied to `inputs`.
If a layer has tensor arguments in `*args` or `**kwargs`, their
casting behavior in mixed precision should be handled manually.
- The SavedModel input specification is generated using `inputs`
only.
- Integration with various ecosystem packages like TFMOT, TFLite,
TF.js, etc is only supported for `inputs` and not for tensors in
positional and keyword arguments.
*args: Additional positional arguments. May contain tensors, although
this is not recommended, for the reasons above.
**kwargs: Additional keyword arguments. May contain tensors, although
this is not recommended, for the reasons above.
The following optional keyword arguments are reserved:
- `training`: Boolean scalar tensor of Python boolean indicating
whether the `call` is meant for training or inference.
- `mask`: Boolean input mask. If the layer's `call()` method takes a
`mask` argument, its default value will be set to the mask
generated for `inputs` by the previous layer (if `input` did come
from a layer that generated a corresponding mask, i.e. if it came
from a Keras layer with masking support).
Returns:
A tensor or list/tuple of tensors.
"""
return inputs
@doc_controls.for_subclass_implementers
def add_weight(
self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
use_resource=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE,
**kwargs,
):
"""Adds a new variable to the layer.
Args:
name: Variable name.
shape: Variable shape. Defaults to scalar if unspecified.
dtype: The type of the variable. Defaults to `self.dtype`.
initializer: Initializer instance (callable).
regularizer: Regularizer instance (callable).
trainable: Boolean, whether the variable should be part of the layer's
"trainable_variables" (e.g. variables, biases)
or "non_trainable_variables" (e.g. BatchNorm mean and variance).
Note that `trainable` cannot be `True` if `synchronization`
is set to `ON_READ`.
constraint: Constraint instance (callable).
use_resource: Whether to use a `ResourceVariable` or not.
See [this guide](
https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables)
for more information.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set
to `AUTO` and the current `DistributionStrategy` chooses when to
synchronize. If `synchronization` is set to `ON_READ`, `trainable`
must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
**kwargs: Additional keyword arguments. Accepted values are `getter`,
`collections`, `experimental_autocast` and `caching_device`.
Returns:
The variable created.
Raises:
ValueError: When giving unsupported dtype and no initializer or when
trainable has been set to True with synchronization set as
`ON_READ`.
"""
if shape is None:
shape = ()
kwargs.pop("partitioner", None) # Ignored.
# Validate optional keyword arguments.
for kwarg in kwargs:
if kwarg not in [
"collections",
"experimental_autocast",
"caching_device",
"getter",
"layout",
"experimental_enable_variable_lifting",
]:
raise TypeError("Unknown keyword argument:", kwarg)
collections_arg = kwargs.pop("collections", None)
# 'experimental_autocast' can be set to False by the caller to indicate
# an AutoCastVariable should never be created.
autocast = kwargs.pop("experimental_autocast", True)
# See the docstring for tf.Variable about the details for
# caching_device.
caching_device = kwargs.pop("caching_device", None)
layout = kwargs.pop("layout", None)
# Specially handling of auto layout fetch, based on the variable name
# and attribute name. For built-in keras layers, usually the variable
# name, eg 'kernel', will match with a 'kernel_layout' attribute name on
# the instance. We will try to do this auto fetch if layout is not
# explicitly specified. This is mainly a quick workaround for not
# applying too many interface change to built-in layers, until DTensor
# is a public API. Also see dtensor.utils.allow_initializer_layout for
# more details.
# TODO(scottzhu): Remove this once dtensor is public to end user.
if not layout and name:
layout = getattr(self, name + "_layout", None)
if dtype is None:
dtype = self.dtype or backend.floatx()
dtype = tf.as_dtype(dtype)
if self._dtype_policy.variable_dtype is None:
# The policy is "_infer", so we infer the policy from the variable
# dtype.
self._set_dtype_policy(policy.Policy(dtype.base_dtype.name))
initializer = initializers.get(initializer)
regularizer = regularizers.get(regularizer)
constraint = constraints.get(constraint)
if synchronization == tf.VariableSynchronization.ON_READ:
if trainable:
raise ValueError(
"Synchronization value can be set to "
"VariableSynchronization.ON_READ only for non-trainable "
"variables. You have specified trainable=True and "
"synchronization=VariableSynchronization.ON_READ."
)
else:
# Set trainable to be false when variable is to be synced on
# read.
trainable = False
elif trainable is None:
trainable = True
# Initialize variable when no initializer provided
if initializer is None:
# If dtype is DT_FLOAT, provide a uniform unit scaling initializer
if dtype.is_floating:
initializer = initializers.get("glorot_uniform")
# If dtype is DT_INT/DT_UINT, provide a default value `zero`
# If dtype is DT_BOOL, provide a default value `FALSE`
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:
initializer = initializers.get("zeros")
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX
# here?
elif "getter" not in kwargs:
# When `getter` is specified, it's possibly fine for
# `initializer` to be None since it's up to the custom `getter`
# to raise error in case it indeed needs `initializer`.
raise ValueError(
f"An initializer for variable {name} of type "
f"{dtype.base_dtype} is required for layer "
f"{self.name}. Received: {initializer}."
)
getter = kwargs.pop("getter", base_layer_utils.make_variable)
if (
autocast
and self._dtype_policy.compute_dtype
!= self._dtype_policy.variable_dtype
and dtype.is_floating
):
old_getter = getter
# Wrap variable constructor to return an AutoCastVariable.
def getter(*args, **kwargs):
variable = old_getter(*args, **kwargs)
return autocast_variable.create_autocast_variable(variable)
# Also the caching_device does not work with the mixed precision
# API, disable it if it is specified.
# TODO(b/142020079): Re-enable it once the bug is fixed.
if caching_device is not None:
tf_logging.warning(
"`caching_device` does not work with mixed precision API. "
"Ignoring user specified `caching_device`."
)
caching_device = None
if layout:
getter = functools.partial(getter, layout=layout)
variable = self._add_variable_with_custom_getter(
name=name,
shape=shape,
# TODO(allenl): a `make_variable` equivalent should be added as a
# `Trackable` method.
getter=getter,
# Manage errors in Layer rather than Trackable.
overwrite=True,
initializer=initializer,
dtype=dtype,
constraint=constraint,
trainable=trainable,
use_resource=use_resource,
collections=collections_arg,
synchronization=synchronization,
aggregation=aggregation,
caching_device=caching_device,
)
if regularizer is not None:
# TODO(fchollet): in the future, this should be handled at the
# level of variable creation, and weight regularization losses
# should be variable attributes.
name_in_scope = variable.name[: variable.name.find(":")]
self._handle_weight_regularization(
name_in_scope, variable, regularizer
)
if base_layer_utils.is_split_variable(variable):
for v in variable:
backend.track_variable(v)
if trainable:
self._trainable_weights.append(v)
else:
self._non_trainable_weights.append(v)
else:
backend.track_variable(variable)
if trainable:
self._trainable_weights.append(variable)
else:
self._non_trainable_weights.append(variable)
return variable
def __new__(cls, *args, **kwargs):
# Generate a config to be returned by default by `get_config()`.
arg_names = tf_inspect.getfullargspec(cls.__init__).args
kwargs.update(dict(zip(arg_names[1 : len(args) + 1], args)))
instance = super(Layer, cls).__new__(cls, *args, **kwargs)
# For safety, we only rely on auto-configs for a small set of
# serializable types.
supported_types = (str, int, float, bool, type(None))
try:
flat_arg_values = tf.nest.flatten(kwargs)
auto_get_config = True
for value in flat_arg_values:
if not isinstance(value, supported_types):
auto_get_config = False
break
except TypeError:
auto_get_config = False
try:
instance._auto_get_config = auto_get_config
if auto_get_config:
instance._auto_config = serialization_lib.Config(**kwargs)
except RecursionError:
# Setting an instance attribute in __new__ has the potential
# to trigger an infinite recursion if a subclass overrides
# setattr in an unsafe way.
pass
return instance
@generic_utils.default
def get_config(self):
"""Returns the config of the layer.
A layer config is a Python dictionary (serializable)
containing the configuration of a layer.
The same layer can be reinstantiated later
(without its trained weights) from this configuration.
The config of a layer does not include connectivity
information, nor the layer class name. These are handled
by `Network` (one layer of abstraction above).
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Returns:
Python dictionary.
"""
config = {
"name": self.name,
"trainable": self.trainable,
}
config["dtype"] = policy.serialize(self._dtype_policy)
if hasattr(self, "_batch_input_shape"):
config["batch_input_shape"] = self._batch_input_shape
if not generic_utils.is_default(self.get_config):
# In this case the subclass implements get_config()
return config
# In this case the subclass doesn't implement get_config():
# Let's see if we can autogenerate it.
if getattr(self, "_auto_get_config", False):
xtra_args = set(config.keys())
config.update(self._auto_config.config)
# Remove args non explicitly supported
argspec = tf_inspect.getfullargspec(self.__init__)
if argspec.varkw != "kwargs":
for key in xtra_args - xtra_args.intersection(argspec.args[1:]):
config.pop(key, None)
return config
else:
raise NotImplementedError(
textwrap.dedent(
f"""
Layer {self.__class__.__name__} was created by passing
non-serializable argument values in `__init__()`,
and therefore the layer must override `get_config()` in
order to be serializable. Please implement `get_config()`.
Example:
class CustomLayer(keras.layers.Layer):
def __init__(self, arg1, arg2, **kwargs):
super().__init__(**kwargs)
self.arg1 = arg1
self.arg2 = arg2
def get_config(self):
config = super().get_config()
config.update({{
"arg1": self.arg1,
"arg2": self.arg2,
}})
return config"""
)
)
@classmethod
def from_config(cls, config):
"""Creates a layer from its config.
This method is the reverse of `get_config`,
capable of instantiating the same layer from the config
dictionary. It does not handle layer connectivity
(handled by Network), nor weights (handled by `set_weights`).
Args:
config: A Python dictionary, typically the
output of get_config.
Returns:
A layer instance.
"""
try:
return cls(**config)
except Exception as e:
raise TypeError(
f"Error when deserializing class '{cls.__name__}' using "
f"config={config}.\n\nException encountered: {e}"
)
def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
This method will cause the layer's state to be built, if that has not
happened before. This requires that the layer will later be used with
inputs that match the input shape provided here.
Args:
input_shape: Shape tuple (tuple of integers) or `tf.TensorShape`,
or structure of shape tuples / `tf.TensorShape` instances
(one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
A `tf.TensorShape` instance
or structure of `tf.TensorShape` instances.
"""
if tf.executing_eagerly():
# In this case we build the model first in order to do shape
# inference. This is acceptable because the framework only calls
# `compute_output_shape` on shape values that the layer would later
# be built for. It would however cause issues in case a user
# attempts to use `compute_output_shape` manually with shapes that
# are incompatible with the shape the Layer will be called on (these
# users will have to implement `compute_output_shape` themselves).
self._maybe_build(input_shape)
graph_name = str(self.name) + "_scratch_graph"
with tf.__internal__.FuncGraph(graph_name).as_default():
input_shape = tf_utils.convert_shapes(
input_shape, to_tuples=False
)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
inputs = tf.nest.map_structure(
_make_placeholder_like, input_shape
)
try:
outputs = self(inputs, training=False)
except TypeError as e:
raise NotImplementedError(
"We could not automatically infer the static shape of "
"the layer's output. Please implement the "
"`compute_output_shape` method on your layer (%s)."
% self.__class__.__name__
) from e
return tf.nest.map_structure(lambda t: t.shape, outputs)
raise NotImplementedError(
"Please run in eager mode or implement the `compute_output_shape` "
"method on your layer (%s)." % self.__class__.__name__
)
@doc_controls.for_subclass_implementers
def compute_output_signature(self, input_signature):
"""Compute the output tensor signature of the layer based on the inputs.
Unlike a TensorShape object, a TensorSpec object contains both shape
and dtype information for a tensor. This method allows layers to provide
output dtype information if it is different from the input dtype.
For any layer that doesn't implement this function,
the framework will fall back to use `compute_output_shape`, and will
assume that the output dtype matches the input dtype.
Args:
input_signature: Single TensorSpec or nested structure of TensorSpec
objects, describing a candidate input for the layer.
Returns:
Single TensorSpec or nested structure of TensorSpec objects,
describing how the layer would transform the provided input.
Raises:
TypeError: If input_signature contains a non-TensorSpec object.
"""
def check_type_return_shape(s):
if not isinstance(s, tf.TensorSpec):
raise TypeError(
"Only TensorSpec signature types are supported. "
f"Received: {s}."
)
return s.shape
input_shape = tf.nest.map_structure(
check_type_return_shape, input_signature
)
output_shape = self.compute_output_shape(input_shape)
try:
dtype = self.output.dtype
except AttributeError:
dtype = self._compute_dtype
if dtype is None:
input_dtypes = [s.dtype for s in tf.nest.flatten(input_signature)]
# Default behavior when self.dtype is None, is to use the first
# input's dtype.
dtype = input_dtypes[0]
return tf.nest.map_structure(
lambda s: tf.TensorSpec(dtype=dtype, shape=s), output_shape
)
@generic_utils.default
def compute_mask(self, inputs, mask=None):
"""Computes an output mask tensor.
Args:
inputs: Tensor or list of tensors.
mask: Tensor or list of tensors.
Returns:
None or a tensor (or list of tensors,
one per output tensor of the layer).
"""
if not self._supports_masking:
if any(m is not None for m in tf.nest.flatten(mask)):
raise TypeError(
"Layer " + self.name + " does not support masking, "
"but was passed an input_mask: " + str(mask)
)
# masking not explicitly supported: return None as mask.
return None