|
| 1 | +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Keras-based gated feedforward layer.""" |
| 16 | +# pylint: disable=g-classes-have-attributes |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +import tensorflow as tf |
| 20 | + |
| 21 | + |
| 22 | +class BlockDiagFeedforward(tf.keras.layers.Layer): |
| 23 | + """Block diagonal feedforward layer. |
| 24 | +
|
| 25 | + This layer replaces the weight matrix of the output_dense layer with a block |
| 26 | + diagonal matrix to save layer parameters and FLOPs. A linear mixing layer can |
| 27 | + be added optionally to improve layer expressibility. |
| 28 | +
|
| 29 | + Args: |
| 30 | + intermediate_size: Size of the intermediate layer. |
| 31 | + intermediate_activation: Activation for the intermediate layer. |
| 32 | + dropout: Dropout probability for the output dropout. |
| 33 | + num_blocks: The number of blocks for the block diagonal matrix of the |
| 34 | + output_dense layer. |
| 35 | + apply_mixing: Apply linear mixing if True. |
| 36 | + kernel_initializer: Initializer for dense layer kernels. |
| 37 | + bias_initializer: Initializer for dense layer biases. |
| 38 | + kernel_regularizer: Regularizer for dense layer kernels. |
| 39 | + bias_regularizer: Regularizer for dense layer biases. |
| 40 | + activity_regularizer: Regularizer for dense layer activity. |
| 41 | + kernel_constraint: Constraint for dense layer kernels. |
| 42 | + bias_constraint: Constraint for dense layer kernels. |
| 43 | + """ |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + intermediate_size: int, |
| 48 | + intermediate_activation: str, |
| 49 | + dropout: float, |
| 50 | + num_blocks: int = 1, |
| 51 | + apply_mixing: bool = True, |
| 52 | + kernel_initializer: str = "glorot_uniform", |
| 53 | + bias_initializer: str = "zeros", |
| 54 | + kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None, |
| 55 | + bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None, |
| 56 | + activity_regularizer: Optional[tf.keras.regularizers.Regularizer] = None, |
| 57 | + kernel_constraint: Optional[tf.keras.constraints.Constraint] = None, |
| 58 | + bias_constraint: Optional[tf.keras.constraints.Constraint] = None, |
| 59 | + **kwargs): # pylint: disable=g-doc-args |
| 60 | + super(BlockDiagFeedforward, self).__init__(**kwargs) |
| 61 | + self._intermediate_size = intermediate_size |
| 62 | + self._intermediate_activation = intermediate_activation |
| 63 | + self._dropout = dropout |
| 64 | + self._num_blocks = num_blocks |
| 65 | + self._apply_mixing = apply_mixing |
| 66 | + |
| 67 | + if intermediate_size % num_blocks != 0: |
| 68 | + raise ValueError("Intermediate_size (%d) isn't a multiple of num_blocks " |
| 69 | + "(%d)." % (intermediate_size, num_blocks)) |
| 70 | + |
| 71 | + self._kernel_initializer = tf.keras.initializers.get(kernel_initializer) |
| 72 | + self._bias_initializer = tf.keras.initializers.get(bias_initializer) |
| 73 | + self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer) |
| 74 | + self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer) |
| 75 | + self._activity_regularizer = tf.keras.regularizers.get(activity_regularizer) |
| 76 | + self._kernel_constraint = tf.keras.constraints.get(kernel_constraint) |
| 77 | + self._bias_constraint = tf.keras.constraints.get(bias_constraint) |
| 78 | + |
| 79 | + def build(self, input_shape): |
| 80 | + hidden_size = input_shape.as_list()[-1] |
| 81 | + |
| 82 | + common_kwargs = dict( |
| 83 | + kernel_initializer=self._kernel_initializer, |
| 84 | + bias_initializer=self._bias_initializer, |
| 85 | + kernel_regularizer=self._kernel_regularizer, |
| 86 | + bias_regularizer=self._bias_regularizer, |
| 87 | + activity_regularizer=self._activity_regularizer, |
| 88 | + kernel_constraint=self._kernel_constraint, |
| 89 | + bias_constraint=self._bias_constraint) |
| 90 | + |
| 91 | + self._intermediate_dense = tf.keras.layers.experimental.EinsumDense( |
| 92 | + "abc,cde->abde", |
| 93 | + output_shape=(None, self._num_blocks, |
| 94 | + self._intermediate_size // self._num_blocks), |
| 95 | + bias_axes="de", |
| 96 | + name="intermediate", |
| 97 | + **common_kwargs) |
| 98 | + |
| 99 | + policy = tf.keras.mixed_precision.global_policy() |
| 100 | + if policy.name == "mixed_bfloat16": |
| 101 | + # bfloat16 causes BERT with the LAMB optimizer to not converge |
| 102 | + # as well, so we use float32. |
| 103 | + policy = tf.float32 |
| 104 | + self._intermediate_activation_layer = tf.keras.layers.Activation( |
| 105 | + self._intermediate_activation, dtype=policy) |
| 106 | + |
| 107 | + self._output_dense = tf.keras.layers.experimental.EinsumDense( |
| 108 | + "abde,deo->abdo", |
| 109 | + output_shape=(None, self._num_blocks, |
| 110 | + hidden_size // self._num_blocks), |
| 111 | + bias_axes="do", |
| 112 | + name="output", |
| 113 | + **common_kwargs) |
| 114 | + |
| 115 | + if self._apply_mixing: |
| 116 | + self._output_mixing = tf.keras.layers.experimental.EinsumDense( |
| 117 | + "abdo,de->abeo", |
| 118 | + output_shape=(None, self._num_blocks, |
| 119 | + hidden_size // self._num_blocks), |
| 120 | + name="output_mixing", |
| 121 | + **common_kwargs) |
| 122 | + self._output_reshape = tf.keras.layers.Reshape((-1, hidden_size)) |
| 123 | + |
| 124 | + self._output_dropout = tf.keras.layers.Dropout(rate=self._dropout) |
| 125 | + |
| 126 | + def get_config(self): |
| 127 | + config = { |
| 128 | + "intermediate_size": |
| 129 | + self._intermediate_size, |
| 130 | + "intermediate_activation": |
| 131 | + self._intermediate_activation, |
| 132 | + "dropout": |
| 133 | + self._dropout, |
| 134 | + "num_blocks": |
| 135 | + self._num_blocks, |
| 136 | + "apply_mixing": |
| 137 | + self._apply_mixing, |
| 138 | + "kernel_initializer": |
| 139 | + tf.keras.initializers.serialize(self._kernel_initializer), |
| 140 | + "bias_initializer": |
| 141 | + tf.keras.initializers.serialize(self._bias_initializer), |
| 142 | + "kernel_regularizer": |
| 143 | + tf.keras.regularizers.serialize(self._kernel_regularizer), |
| 144 | + "bias_regularizer": |
| 145 | + tf.keras.regularizers.serialize(self._bias_regularizer), |
| 146 | + "activity_regularizer": |
| 147 | + tf.keras.regularizers.serialize(self._activity_regularizer), |
| 148 | + "kernel_constraint": |
| 149 | + tf.keras.constraints.serialize(self._kernel_constraint), |
| 150 | + "bias_constraint": |
| 151 | + tf.keras.constraints.serialize(self._bias_constraint) |
| 152 | + } |
| 153 | + base_config = super(BlockDiagFeedforward, self).get_config() |
| 154 | + return dict(list(base_config.items()) + list(config.items())) |
| 155 | + |
| 156 | + def call(self, inputs): |
| 157 | + intermediate_output = self._intermediate_dense(inputs) |
| 158 | + intermediate_output = self._intermediate_activation_layer( |
| 159 | + intermediate_output) |
| 160 | + layer_output = self._output_dense(intermediate_output) |
| 161 | + if self._apply_mixing: |
| 162 | + layer_output = self._output_mixing(layer_output) |
| 163 | + layer_output = self._output_reshape(layer_output) |
| 164 | + layer_output = self._output_dropout(layer_output) |
| 165 | + |
| 166 | + return layer_output |
0 commit comments