MCPcopy Create free account
hub / github.com/NVIDIA/FasterTransformer / tf_bert

Function tf_bert

examples/tensorflow/bert/utils/bert.py:159–252  ·  view source on GitHub ↗

Run the bert transformer layer by TensorFlow. Args: inputs: A tf.Tensor with shape [batch_size, seq_len, hidden_dimension]. The inputs tensor of encoder. The rank must be 3. encoder_args: The arguments for encoder. The details are in the class

(input_tensor,
            encoder_args,
            attention_mask=None,
            intermediate_act_fn=gelu,
            initializer_range=0.02)

Source from the content-addressed store, hash-verified

157
158
159def tf_bert(input_tensor,
160 encoder_args,
161 attention_mask=None,
162 intermediate_act_fn=gelu,
163 initializer_range=0.02):
164 '''
165 Run the bert transformer layer by TensorFlow.
166
167 Args:
168 inputs: A tf.Tensor with shape [batch_size, seq_len, hidden_dimension].
169 The inputs tensor of encoder. The rank must be 3.
170 encoder_args: The arguments for encoder. The details are in the class
171 "TransformerArgument" of common.py
172 attention_mask: A tf.Tensor. The attention mask for self attention.
173 intermediate_act_fn: A callable function.
174 The activation function in the FFN. It is gelu in BERT.
175 initializer_range: A float value.
176 The range of initializer for all weights.
177
178 Outputs:
179 outputs: A tf.Tensor with shape [batch_size, seq_len, hidden_dimension].
180 The results of encoder.
181 '''
182
183 if encoder_args.hidden_dim % encoder_args.head_num != 0:
184 raise ValueError(
185 "The hidden size (%d) is not a multiple of the number of attention "
186 "heads (%d)" % (encoder_args.hidden_dim, encoder_args.head_num))
187
188 input_shape = get_shape_list(input_tensor, expected_rank=3)
189 batch_size = input_shape[0]
190 seq_length = input_shape[1]
191
192 prev_output = reshape_to_matrix(input_tensor)
193
194 for layer_idx in range(encoder_args.num_layer):
195 with tf.variable_scope("layer_%d" % layer_idx, reuse=tf.AUTO_REUSE):
196 layer_input = prev_output
197 with tf.variable_scope("attention"):
198 with tf.variable_scope("self"):
199 attention_head = attention_layer(
200 from_tensor=layer_input,
201 to_tensor=layer_input,
202 attention_mask=attention_mask,
203 num_attention_heads=encoder_args.head_num,
204 size_per_head=encoder_args.size_per_head,
205 initializer_range=initializer_range,
206 do_return_2d_tensor=True,
207 batch_size=batch_size,
208 from_seq_length=seq_length,
209 to_seq_length=seq_length,
210 tf_datatype=encoder_args.dtype)
211 attention_output = attention_head
212
213 with tf.variable_scope("output"):
214 attention_output = tf.layers.dense(
215 attention_output,
216 encoder_args.hidden_dim,

Callers 2

bert_exampleFunction · 0.90
_tf_bodyFunction · 0.90

Calls 5

create_initializerFunction · 0.90
get_shape_listFunction · 0.70
reshape_to_matrixFunction · 0.70
attention_layerFunction · 0.70
layer_normFunction · 0.70

Tested by

no test coverage detected