-
Notifications
You must be signed in to change notification settings - Fork 19.6k
/
Copy pathlayer.py
1638 lines (1452 loc) · 62.4 KB
/
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
"""Layer is an Operation with state.
Takes care of:
- Weights / variables (and tracking thereof)
- deferred build
- trainable argument value inference
- masking
- autocasting
And some more magic:
- add_loss
- metric tracking
- RNG seed tracking
- activity regularization
"""
import collections
import inspect
import warnings
from functools import wraps
from keras.src import backend
from keras.src import constraints
from keras.src import dtype_policies
from keras.src import initializers
from keras.src import regularizers
from keras.src import tree
from keras.src import utils
from keras.src.api_export import keras_export
from keras.src.backend import KerasTensor
from keras.src.backend.common import global_state
from keras.src.backend.common.name_scope import current_path
from keras.src.distribution import distribution_lib
from keras.src.layers import input_spec
from keras.src.metrics.metric import Metric
from keras.src.ops.operation import Operation
from keras.src.saving.keras_saveable import KerasSaveable
from keras.src.utils import python_utils
from keras.src.utils import summary_utils
from keras.src.utils import traceback_utils
from keras.src.utils import tracking
if backend.backend() == "tensorflow":
from keras.src.backend.tensorflow.layer import TFLayer as BackendLayer
elif backend.backend() == "jax":
from keras.src.backend.jax.layer import JaxLayer as BackendLayer
elif backend.backend() == "torch":
from keras.src.backend.torch.layer import TorchLayer as BackendLayer
elif backend.backend() == "numpy":
from keras.src.backend.numpy.layer import NumpyLayer as BackendLayer
else:
raise RuntimeError(
f"Backend '{backend.backend()}' must implement a layer mixin class."
)
@keras_export(["keras.Layer", "keras.layers.Layer"])
class Layer(BackendLayer, Operation, KerasSaveable):
"""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 `__init__()`, for instance via `self.add_weight()`;
* 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.
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 or `build()` 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
`keras.DTypePolicy`,
which allows the computation and
weight dtype to differ. Defaults to `None`. `None` means to use
`keras.config.dtype_policy()`,
which is a `float32` policy unless set to different value
(via `keras.config.set_dtype_policy()`).
Attributes:
name: The name of the layer (string).
dtype: Dtype of the layer's weights. Alias of `layer.variable_dtype`.
variable_dtype: Dtype of the layer's weights.
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
`keras.DTypePolicy`, this will be different
than `variable_dtype`.
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, *args, **kwargs)`: Called in `__call__` after making
sure `build()` has been called. `call()` performs the logic of applying
the layer to the input arguments.
Two reserved keyword arguments you can optionally use in `call()` are:
1. `training` (boolean, whether the call is in inference mode or
training mode).
2. `mask` (boolean tensor encoding masked timesteps in the input,
used e.g. in RNN layers).
A typical signature for this method is `call(self, inputs)`, and user
could optionally add `training` and `mask` if the layer need them.
* `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().__init__()
self.units = units
# Create the state of the layer (weights)
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="glorot_uniform",
trainable=True,
name="kernel",
)
self.bias = self.add_weight(
shape=(self.units,),
initializer="zeros",
trainable=True,
name="bias",
)
# Defines the computation
def call(self, inputs):
return ops.matmul(inputs, self.kernel) + self.bias
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(ops.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
```
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 = self.add_weight(
shape=(),
initializer="zeros",
trainable=False,
name="total",
)
def call(self, inputs):
self.total.assign(self.total + ops.sum(inputs))
return self.total
my_sum = ComputeSum(2)
x = ops.ones((2, 2))
y = my_sum(x)
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
```
"""
def __new__(cls, *args, **kwargs):
# Wrap the user-provided build method in the build_decorator
# to add name scope support and serialization support.
obj = super().__new__(cls, *args, **kwargs)
original_build_method = obj.build
@wraps(original_build_method)
def build_wrapper(*args, **kwargs):
with obj._open_name_scope():
original_build_method(*args, **kwargs)
# Record build config.
signature = inspect.signature(original_build_method)
obj._build_shapes_dict = signature.bind(*args, **kwargs).arguments
# Set built, post build actions, and lock state.
obj.built = True
obj._post_build()
obj._lock_state()
obj.build = build_wrapper
return obj
def __init__(
self,
*,
activity_regularizer=None,
trainable=True,
dtype=None,
autocast=True,
name=None,
**kwargs,
):
BackendLayer.__init__(self)
self._lock = False
Operation.__init__(self, dtype=dtype, name=name)
self.activity_regularizer = regularizers.get(activity_regularizer)
input_dim_arg = kwargs.pop("input_dim", None)
if input_dim_arg is not None:
input_shape_arg = (input_dim_arg,)
else:
input_shape_arg = kwargs.pop("input_shape", None)
if input_shape_arg is not None:
warnings.warn(
"Do not pass an `input_shape`/`input_dim` argument to "
"a layer. When using Sequential models, "
"prefer using an `Input(shape)` object as the "
"first layer in the model instead.",
stacklevel=2,
)
self._input_shape_arg = input_shape_arg
if kwargs:
raise ValueError(
"Unrecognized keyword arguments "
f"passed to {self.__class__.__name__}: {kwargs}"
)
self.built = False
self.autocast = autocast
self._input_spec = None
self._called = False
self.supports_jit = True
self._trainable = trainable
self._losses = []
self._loss_ids = set()
self._losses_override = []
self._call_signature = inspect.signature(self.call)
call_signature_parameters = [
p.name for p in self._call_signature.parameters.values()
]
self._call_has_training_arg = "training" in call_signature_parameters
self._call_has_mask_arg = "mask" in call_signature_parameters
self._supports_masking = not utils.is_default(self.compute_mask)
# Whether to automatically convert (+ auto-cast) inputs to `call()`.
self._convert_input_args = True
# Whether to allow non-tensors as positional arguments in `call()`.
self._allow_non_tensor_positional_args = False
# Dict of shapes that were used to call `build()`.
self._build_shapes_dict = None
# Parent path
self._parent_path = None
self._initialize_tracker()
@tracking.no_automatic_dependency_tracking
def _initialize_tracker(self):
if hasattr(self, "_tracker"):
return
trainable_variables = []
non_trainable_variables = []
layers = []
metrics = []
seed_generators = []
self._tracker = tracking.Tracker(
{
"trainable_variables": (
lambda x: isinstance(x, backend.Variable) and x.trainable,
trainable_variables,
),
"non_trainable_variables": (
lambda x: isinstance(x, backend.Variable)
and not x.trainable,
non_trainable_variables,
),
"metrics": (lambda x: isinstance(x, Metric), metrics),
"layers": (
lambda x: isinstance(x, Layer)
and not isinstance(x, Metric),
layers,
),
"seed_generators": (
lambda x: isinstance(x, backend.random.SeedGenerator),
seed_generators,
),
},
exclusions={"non_trainable_variables": ["trainable_variables"]},
)
if backend.backend() == "tensorflow":
# Remove attribute tracking for lists (TF-specific attribute)
_self_setattr_tracking = getattr(
self, "_self_setattr_tracking", True
)
self._self_setattr_tracking = False
self._trainable_variables = trainable_variables
self._non_trainable_variables = non_trainable_variables
self._layers = layers
self._metrics = metrics
self._seed_generators = seed_generators
if backend.backend() == "tensorflow":
# Reset attribute tracking (TF-specific)
self._self_setattr_tracking = _self_setattr_tracking
@property
def input_spec(self):
return self._input_spec
@input_spec.setter
def input_spec(self, value):
self._input_spec = value
@utils.default
def build(self, input_shape):
self._check_super_called()
if utils.is_default(self.build) and might_have_unbuilt_state(self):
warnings.warn(
f"`build()` was called on layer '{self.name}', however "
"the layer does not have a `build()` method implemented "
"and it looks like it has unbuilt state. This will cause "
"the layer to be marked as built, despite not being "
"actually built, which may cause failures down the line. "
"Make sure to implement a proper `build()` method."
)
self.built = True
def _lock_state(self):
"""Prevent further state updates, called automatically in `build()`."""
if not self._tracker.locked:
self._tracker.lock(
msg=(
"You cannot add new elements of state "
"(variables or sub-layers) "
"to a layer that is already built. All state "
"must be created in the `__init__()` method or "
"in the `build()` method."
)
)
def get_build_config(self):
"""Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
`build_from_config(config)` to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer
was built with. If you're writing a custom layer that creates state in
an unusual way, you should override this method to make sure this state
is already created when Keras attempts to load its value upon model
loading.
Returns:
A dict containing the input shape associated with the layer.
"""
if self._build_shapes_dict is not None:
if len(self._build_shapes_dict) == 1:
return {
"input_shape": tuple(self._build_shapes_dict.values())[0],
}
else:
return {"shapes_dict": self._build_shapes_dict}
def build_from_config(self, config):
"""Builds the layer's states with the supplied config dict.
By default, this method calls the `build(config["input_shape"])` method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
Args:
config: Dict containing the input shape associated with this layer.
"""
if config:
if "input_shape" in config:
self.build(config["input_shape"])
elif "shapes_dict" in config:
self.build(**config["shapes_dict"])
self.built = True
def _obj_type(self):
return "Layer"
def add_variable(
self,
shape,
initializer,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
name=None,
):
"""Add a weight variable to the layer.
Alias of `add_weight()`.
"""
return self.add_weight(
shape=shape,
initializer=initializer,
dtype=dtype,
trainable=trainable,
autocast=autocast,
regularizer=regularizer,
constraint=constraint,
name=name,
)
def add_weight(
self,
shape=None,
initializer=None,
dtype=None,
trainable=True,
autocast=True,
regularizer=None,
constraint=None,
aggregation="mean",
name=None,
):
"""Add a weight variable to the layer.
Args:
shape: Shape tuple for the variable. Must be fully-defined
(no `None` entries). Defaults to `()` (scalar) if unspecified.
initializer: Initializer object to use to populate the initial
variable value, or string name of a built-in initializer
(e.g. `"random_normal"`). If unspecified, defaults to
`"glorot_uniform"` for floating-point variables and to `"zeros"`
for all other types (e.g. int, bool).
dtype: Dtype of the variable to create, e.g. `"float32"`. If
unspecified, defaults to the layer's variable dtype
(which itself defaults to `"float32"` if unspecified).
trainable: Boolean, whether the variable should be trainable via
backprop or whether its updates are managed manually. Defaults
to `True`.
autocast: Boolean, whether to autocast layers variables when
accessing them. Defaults to `True`.
regularizer: Regularizer object to call to apply penalty on the
weight. These penalties are summed into the loss function
during optimization. Defaults to `None`.
constraint: Contrainst object to call on the variable after any
optimizer update, or string name of a built-in constraint.
Defaults to `None`.
aggregation: String, one of `'mean'`, `'sum'`,
`'only_first_replica'`. Annotates the variable with the type
of multi-replica aggregation to be used for this variable
when writing custom data parallel training loops.
name: String name of the variable. Useful for debugging purposes.
"""
self._check_super_called()
if shape is None:
shape = ()
if dtype is not None:
dtype = backend.standardize_dtype(dtype)
else:
dtype = self.variable_dtype
if initializer is None:
if "float" in dtype:
initializer = "glorot_uniform"
else:
initializer = "zeros"
initializer = initializers.get(initializer)
with self._open_name_scope():
variable = backend.Variable(
initializer=initializer,
shape=shape,
dtype=dtype,
trainable=trainable,
autocast=autocast,
aggregation=aggregation,
name=name,
)
# Will be added to layer.losses
variable.regularizer = regularizers.get(regularizer)
variable.constraint = constraints.get(constraint)
self._track_variable(variable)
return variable
@property
def trainable(self):
"""Settable boolean, whether this layer should be trainable or not."""
return self._trainable
@trainable.setter
def trainable(self, value):
"""Sets trainable attribute for the layer and its sublayers.
When this value is changed during training (e.g. with a
`Callback`) you need to call the parent
`Model.make_train_function` with `force=True` in order to
recompile the training graph.
Args:
value: Boolean with the desired state for the layer's trainable
attribute.
"""
value = bool(value)
self._trainable = value
for v in self._trainable_variables:
v.trainable = value
for layer in self._layers:
layer.trainable = value
@property
def variables(self):
"""List of all layer state, including random seeds.
This extends `layer.weights` to include all state used by the layer
including `SeedGenerator`s.
Note that metrics variables are not included here, use
`metrics_variables` to visit all the metric variables.
"""
# Return all `Variables` associate with the layer including metrics
# and random seeds. Also deduplicate them.
variables = []
seen_ids = set()
for v in self._trainable_variables + self._non_trainable_variables:
if id(v) not in seen_ids:
variables.append(v)
seen_ids.add(id(v))
for sg in self._seed_generators:
variables.append(sg.state)
for layer in self._layers:
for v in layer.variables:
if id(v) not in seen_ids:
variables.append(v)
seen_ids.add(id(v))
return variables
@property
def trainable_variables(self):
"""List of all trainable layer state.
This is equivalent to `layer.trainable_weights`.
"""
if not self.trainable:
return []
return [v for v in self.variables if v.trainable]
@property
def non_trainable_variables(self):
"""List of all non-trainable layer state.
This extends `layer.non_trainable_weights` to include all state used by
the layer including state for metrics and `SeedGenerator`s.
"""
if not self.trainable:
return self.variables
return [v for v in self.variables if not v.trainable]
@property
def weights(self):
"""List of all weight variables of the layer.
Unlike, `layer.variables` this excludes metric state and random seeds.
"""
# Return only `Variables` directly owned by layers and sub-layers.
# Also deduplicate them.
weights = []
seen_ids = set()
for w in self._trainable_variables + self._non_trainable_variables:
if id(w) not in seen_ids:
weights.append(w)
seen_ids.add(id(w))
for layer in self._layers:
for w in layer.weights:
if id(w) not in seen_ids:
weights.append(w)
seen_ids.add(id(w))
return weights
@property
def trainable_weights(self):
"""List of all trainable weight variables of the layer.
These are the weights that get updated by the optimizer during training.
"""
if not self.trainable:
return []
return [v for v in self.weights if v.trainable]
@property
def non_trainable_weights(self):
"""List of all non-trainable weight variables of the layer.
These are the weights that should not be updated by the optimizer during
training. Unlike, `layer.non_trainable_variables` this excludes metric
state and random seeds.
"""
if not self.trainable:
return self.weights
return [v for v in self.weights if not v.trainable]
@property
def metrics(self):
"""List of all metrics."""
metrics = list(self._metrics)
for layer in self._layers:
metrics.extend(layer.metrics)
return metrics
@property
def metrics_variables(self):
"""List of all metric variables."""
vars = []
for metric in self.metrics:
vars.extend(metric.variables)
return vars
def get_weights(self):
"""Return the values of `layer.weights` as a list of NumPy arrays."""
return [v.numpy() for v in self.weights]
def set_weights(self, weights):
"""Sets the values of `layer.weights` from a list of NumPy arrays."""
layer_weights = self.weights
if len(layer_weights) != len(weights):
raise ValueError(
f"You called `set_weights(weights)` on layer '{self.name}' "
f"with a weight list of length {len(weights)}, but the layer "
f"was expecting {len(layer_weights)} weights."
)
for variable, value in zip(layer_weights, weights):
if variable.shape != value.shape:
raise ValueError(
f"Layer {self.name} weight shape {variable.shape} "
"is not compatible with provided weight "
f"shape {value.shape}."
)
variable.assign(value)
@property
def dtype_policy(self):
return self._dtype_policy
@dtype_policy.setter
def dtype_policy(self, value):
self._dtype_policy = dtype_policies.get(value)
if isinstance(self._dtype_policy, dtype_policies.QuantizedDTypePolicy):
if self.built:
self.quantize(self._dtype_policy.quantization_mode)
@property
def dtype(self):
"""Alias of `layer.variable_dtype`."""
return self.variable_dtype
@property
def compute_dtype(self):
"""The dtype of the computations performed by the layer."""
return self.dtype_policy.compute_dtype
@property
def variable_dtype(self):
"""The dtype of the state (weights) of the layer."""
return self.dtype_policy.variable_dtype
@property
def input_dtype(self):
"""The dtype layer inputs should be converted to."""
return self.dtype_policy.compute_dtype
@property
def supports_masking(self):
"""Whether this layer supports computing a mask using `compute_mask`."""
return self._supports_masking
@supports_masking.setter
def supports_masking(self, value):
self._supports_masking = value
@utils.default
def compute_mask(self, inputs, previous_mask):
return previous_mask
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
self._check_super_called()
self._called = True
#####################################
# 1. Convert any array arguments to tensors of correct dtype.
def maybe_convert(x):
return self.dtype_policy.convert_input(
x, self.autocast, self.input_dtype
)
# Used to avoid expensive `tree` operations in the most common case.
if (
kwargs
or len(args) != 1
or not backend.is_tensor(args[0])
or backend.standardize_dtype(args[0].dtype) != self.input_dtype
) and self._convert_input_args:
args = tree.map_structure(maybe_convert, args)
kwargs = tree.map_structure(maybe_convert, kwargs)
##########################################################
# 2. Enforce that only tensors can be passed positionally.
if not self._allow_non_tensor_positional_args:
for arg in tree.flatten(args):
if not isinstance(arg, KerasTensor) and not backend.is_tensor(
arg
):
raise ValueError(
"Only input tensors may be passed as "
"positional arguments. The following argument value "
f"should be passed as a keyword argument: {arg} "
f"(of type {type(arg)})"
)
# Caches info about `call()` signature, args, kwargs.
call_spec = CallSpec(self._call_signature, args, kwargs)
############################################
# 3. Check input spec for 1st positional arg.
# TODO: consider extending this to all args and kwargs.
self._assert_input_compatibility(call_spec.first_arg)
################
# 4. Call build
with self._open_name_scope():
self._maybe_build(call_spec)
##########################
# 5. Infer training value
# Training phase for `Layer.call` is set via (in order of priority):
# (1) The `training` argument passed to this `Layer.call`, if not None
# (2) The training argument of an outer `Layer.call`.
# (4) Any non-None default value for `training` in the call signature
# (5) False (treating the layer as if it's in inference)
# Maintains info about the `Layer.call` stack
# across nested calls.
call_context = self._get_call_context()
# This is the value explicitly passed by the user
training = call_spec.user_arguments_dict.get("training", None)
if training is None:
# Wasn't passed explicitly: use context value
training = call_context.training
if training is None:
# Get signature default value
training = call_spec.arguments_dict.get("training", None)
call_context.training = training
if self._call_has_training_arg and training is not None:
# Only populate arg if it has a concrete value
kwargs["training"] = training
##############################
# 6. Populate mask argument(s)
if len(call_spec.tensor_arguments_dict) == 1:
if (
"mask" in call_spec.argument_names
and call_spec.arguments_dict["mask"] is None
):
arg_name = list(call_spec.tensor_arguments_dict.keys())[0]
only_tensor_arg = call_spec.tensor_arguments_dict[arg_name]
mask = tree.map_structure(
lambda x: getattr(x, "_keras_mask", None),
only_tensor_arg,
)
kwargs["mask"] = mask
elif len(call_spec.tensor_arguments_dict) > 1:
for k, v in call_spec.tensor_arguments_dict.items():
expected_mask_arg_name = f"{k}_mask"
if expected_mask_arg_name in call_spec.argument_names:
if call_spec.arguments_dict[expected_mask_arg_name] is None:
mask = tree.map_structure(
lambda x: getattr(x, "_keras_mask", None), v
)
kwargs[expected_mask_arg_name] = mask
####################
# 7. Call the layer.
try:
with self._open_name_scope():
current_scope = backend.get_autocast_scope()
new_scope = None
if current_scope is not None:
# Clear or update the current scope if necessary.
if not self.autocast:
new_scope = backend.AutocastScope(None)
elif not backend.is_float_dtype(self.compute_dtype):
# Some preprocessing layers might have a non-float
# dtype, we should not autocast in this case.
new_scope = backend.AutocastScope(None)
elif current_scope.dtype != self.compute_dtype:
new_scope = backend.AutocastScope(self.compute_dtype)
elif self.compute_dtype != self.variable_dtype:
# Enter a new scope if our dtypes are "mixed".
new_scope = backend.AutocastScope(self.compute_dtype)
if new_scope is not None:
with new_scope:
outputs = super().__call__(*args, **kwargs)
else:
outputs = super().__call__(*args, **kwargs)
# Change the layout for the layer output if needed.
# This is useful for relayout intermediate tensor in the model
# to achieve the optimal performance.
distribution = distribution_lib.distribution()
if distribution is not None:
current_layer_path = current_path()
current_layer_path += "/output"
layout = distribution.get_tensor_layout(current_layer_path)
if layout:
outputs = distribution_lib.distribute_tensor(
outputs, layout
)
if not self.built:
self.built = True
# Record activity regularizer loss.
if self.activity_regularizer is not None:
for output in tree.flatten(outputs):
if backend.is_tensor(output):
self.add_loss(self.activity_regularizer(output))
# Set masks on outputs,
# provided only the first positional input arg and its mask.
# TODO: consider extending this to all args and kwargs.
previous_mask = getattr(call_spec.first_arg, "_keras_mask", None)
if self.supports_masking:
self._set_mask_metadata(
call_spec.first_arg, outputs, previous_mask
)
elif previous_mask is not None:
warnings.warn(
f"Layer '{self.name}' (of type {self.__class__.__name__}) "
"was passed an input with a mask attached to it. "
"However, this layer does not support masking and will "
"therefore destroy the mask information. Downstream "
"layers will not see the mask."
)
finally:
# Destroy call context if we created it
self._maybe_reset_call_context()
return outputs
def call(self, *args, **kwargs):
raise NotImplementedError(
f"Layer {self.__class__.__name__} does not have a `call()` "
"method implemented."
)
def quantized_call(self, *args, **kwargs):
raise NotImplementedError(
f"Layer {self.__class__.__name__} does not have a "
"`quantized_call()` method implemented."
)
@traceback_utils.filter_traceback
def stateless_call(
self,
trainable_variables,
non_trainable_variables,
*args,
return_losses=False,
**kwargs,
):
"""Call the layer without any side effects.
Args:
trainable_variables: List of trainable variables of the model.
non_trainable_variables: List of non-trainable variables of the
model.
*args: Positional arguments to be passed to `call()`.
return_losses: If `True`, `stateless_call()` will return the list of
losses created during `call()` as part of its return values.
**kwargs: Keyword arguments to be passed to `call()`.
Returns:
A tuple. By default, returns `(outputs, non_trainable_variables)`.
If `return_losses = True`, then returns
`(outputs, non_trainable_variables, losses)`.
Note: `non_trainable_variables` include not only non-trainable weights
such as `BatchNormalization` statistics, but also RNG seed state
(if there are any random operations part of the layer, such as dropout),
and `Metric` state (if there are any metrics attached to the layer).
These are all elements of state of the layer.
Example:
```python
model = ...
data = ...
trainable_variables = model.trainable_variables
non_trainable_variables = model.non_trainable_variables
# Call the model with zero side effects
outputs, non_trainable_variables = model.stateless_call(
trainable_variables,
non_trainable_variables,
data,
)
# Attach the updated state to the model
# (until you do this, the model is still in its pre-call state).
for ref_var, value in zip(
model.non_trainable_variables, non_trainable_variables
):
ref_var.assign(value)
```
"""
self._check_super_called()
if not self.built:
raise ValueError(
f"To call stateless_call, {self.__class__.__name__} must be "
"built (i.e. its variables must have been already created). "
"You can build it by calling it on some data."
)
if len(trainable_variables) != len(self.trainable_variables):
raise ValueError(
"Argument `trainable_variables` must be a list of tensors "
"corresponding 1:1 to "
f"{self.__class__.__name__}().trainable_variables. "
f"Received list with length {len(trainable_variables)}, "
f"but expected {len(self.trainable_variables)} variables."
)
if len(non_trainable_variables) != len(self.non_trainable_variables):
raise ValueError(
"Argument `non_trainable_variables` must be a list of tensors "
"corresponding 1:1 to "
f"{self.__class__.__name__}().non_trainable_variables. "
f"Received list with length {len(non_trainable_variables)}, "
f"but expected {len(self.non_trainable_variables)} variables."
)
# Gather variable mapping
trainable_mapping = zip(self.trainable_variables, trainable_variables)
non_trainable_mapping = zip(
self.non_trainable_variables, non_trainable_variables
)
mapping = list(trainable_mapping) + list(non_trainable_mapping)
# Call in stateless scope
losses = None
with backend.StatelessScope(
state_mapping=mapping, collect_losses=return_losses
) as scope:
if isinstance(
self.dtype_policy, dtype_policies.QuantizedDTypePolicy
):
outputs = self.quantized_call(*args, **kwargs)
else:
outputs = self.call(*args, **kwargs)
if return_losses:
losses = self.losses
# Gather updated non-trainable variables
non_trainable_variables = []