customize_encoder.ipynb 20.8 KB
Newer Older
1
{
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Customizing a Transformer Encoder",
      "private_outputs": true,
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
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
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Bp8t2AI8i7uP"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "rxPj2Lsni9O4"
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
45
46
47
      ],
      "execution_count": null,
      "outputs": []
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6xS-9i5DrRvO"
      },
      "source": [
        "# Customizing a Transformer Encoder"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mwb9uw1cDXsa"
      },
      "source": [
64
65
66
67
68
69
70
71
72
73
74
75
76
77
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/official_models/nlp/customize_encoder\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/models/blob/master/official/colab/nlp/customize_encoder.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/official/colab/nlp/customize_encoder.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/models/official/colab/nlp/customize_encoder.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
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
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iLrcV4IyrcGX"
      },
      "source": [
        "## Learning objectives\n",
        "\n",
        "The [TensorFlow Models NLP library](https://github.com/tensorflow/models/tree/master/official/nlp/modeling) is a collection of tools for building and training modern high performance natural language models.\n",
        "\n",
        "The [TransformEncoder](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/networks/encoder_scaffold.py) is the core of this library, and lots of new network architectures are proposed to improve the encoder. In this Colab notebook, we will learn how to customize the encoder to employ new network architectures."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YYxdyoWgsl8t"
      },
      "source": [
        "## Install and import"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fEJSFutUsn_h"
      },
      "source": [
        "### Install the TensorFlow Model Garden pip package\n",
        "\n",
110
111
        "*  `tf-models-official` is the stable Model Garden package. Note that it may not include the latest changes in the `tensorflow_models` github repo. To include latest changes, you may install `tf-models-nightly`,\n",
        "which is the nightly Model Garden package created daily automatically.\n",
112
113
114
115
116
117
118
119
120
        "*  `pip` will install all models and dependencies automatically."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "thsKZDjhswhR"
      },
      "source": [
121
122
123
124
        "!pip install -q tf-models-official==2.4.0"
      ],
      "execution_count": null,
      "outputs": []
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hpf7JPCVsqtv"
      },
      "source": [
        "### Import Tensorflow and other libraries"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "my4dp-RMssQe"
      },
      "source": [
        "import numpy as np\n",
        "import tensorflow as tf\n",
        "\n",
        "from official.modeling import activations\n",
        "from official.nlp import modeling\n",
        "from official.nlp.modeling import layers, losses, models, networks"
147
148
149
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vjDmVsFfs85n"
      },
      "source": [
        "## Canonical BERT encoder\n",
        "\n",
        "Before learning how to customize the encoder, let's firstly create a canonical BERT enoder and use it to instantiate a `BertClassifier` for classification task."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Oav8sbgstWc-"
      },
      "source": [
        "cfg = {\n",
        "    \"vocab_size\": 100,\n",
        "    \"hidden_size\": 32,\n",
        "    \"num_layers\": 3,\n",
        "    \"num_attention_heads\": 4,\n",
        "    \"intermediate_size\": 64,\n",
        "    \"activation\": activations.gelu,\n",
        "    \"dropout_rate\": 0.1,\n",
        "    \"attention_dropout_rate\": 0.1,\n",
177
        "    \"max_sequence_length\": 16,\n",
178
179
180
        "    \"type_vocab_size\": 2,\n",
        "    \"initializer\": tf.keras.initializers.TruncatedNormal(stddev=0.02),\n",
        "}\n",
181
        "bert_encoder = modeling.networks.BertEncoder(**cfg)\n",
182
183
184
185
186
        "\n",
        "def build_classifier(bert_encoder):\n",
        "  return modeling.models.BertClassifier(bert_encoder, num_classes=2)\n",
        "\n",
        "canonical_classifier_model = build_classifier(bert_encoder)"
187
188
189
      ],
      "execution_count": null,
      "outputs": []
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Qe2UWI6_tsHo"
      },
      "source": [
        "`canonical_classifier_model` can be trained using the training data. For details about how to train the model, please see the colab [fine_tuning_bert.ipynb](https://github.com/tensorflow/models/blob/master/official/colab/fine_tuning_bert.ipynb). We skip the code that trains the model here.\n",
        "\n",
        "After training, we can apply the model to do prediction.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "csED2d-Yt5h6"
      },
      "source": [
        "def predict(model):\n",
        "  batch_size = 3\n",
        "  np.random.seed(0)\n",
        "  word_ids = np.random.randint(\n",
212
213
        "      cfg[\"vocab_size\"], size=(batch_size, cfg[\"max_sequence_length\"]))\n",
        "  mask = np.random.randint(2, size=(batch_size, cfg[\"max_sequence_length\"]))\n",
214
        "  type_ids = np.random.randint(\n",
215
        "      cfg[\"type_vocab_size\"], size=(batch_size, cfg[\"max_sequence_length\"]))\n",
216
217
218
        "  print(model([word_ids, mask, type_ids], training=False))\n",
        "\n",
        "predict(canonical_classifier_model)"
219
220
221
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PzKStEK9t_Pb"
      },
      "source": [
        "## Customize BERT encoder\n",
        "\n",
        "One BERT encoder consists of an embedding network and multiple transformer blocks, and each transformer block contains an attention layer and a feedforward layer."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rmwQfhj6fmKz"
      },
      "source": [
        "We provide easy ways to customize each of those components via (1)\n",
        "[EncoderScaffold](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/networks/encoder_scaffold.py) and (2) [TransformerScaffold](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/transformer_scaffold.py)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xsMgEVHAui11"
      },
      "source": [
        "### Use EncoderScaffold\n",
        "\n",
        "`EncoderScaffold` allows users to provide a custom embedding subnetwork\n",
        "  (which will replace the standard embedding logic) and/or a custom hidden layer class (which will replace the `Transformer` instantiation in the encoder)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-JBabpa2AOz8"
      },
      "source": [
        "#### Without Customization\n",
        "\n",
264
        "Without any customization, `EncoderScaffold` behaves the same the canonical `BertEncoder`.\n",
265
        "\n",
266
        "As shown in the following example, `EncoderScaffold` can load `BertEncoder`'s weights and output the same values:"
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ktNzKuVByZQf"
      },
      "source": [
        "default_hidden_cfg = dict(\n",
        "    num_attention_heads=cfg[\"num_attention_heads\"],\n",
        "    intermediate_size=cfg[\"intermediate_size\"],\n",
        "    intermediate_activation=activations.gelu,\n",
        "    dropout_rate=cfg[\"dropout_rate\"],\n",
        "    attention_dropout_rate=cfg[\"attention_dropout_rate\"],\n",
        "    kernel_initializer=tf.keras.initializers.TruncatedNormal(0.02),\n",
        ")\n",
        "default_embedding_cfg = dict(\n",
        "    vocab_size=cfg[\"vocab_size\"],\n",
        "    type_vocab_size=cfg[\"type_vocab_size\"],\n",
        "    hidden_size=cfg[\"hidden_size\"],\n",
        "    initializer=tf.keras.initializers.TruncatedNormal(0.02),\n",
        "    dropout_rate=cfg[\"dropout_rate\"],\n",
289
        "    max_seq_length=cfg[\"max_sequence_length\"]\n",
290
291
292
293
294
295
296
297
298
        ")\n",
        "default_kwargs = dict(\n",
        "    hidden_cfg=default_hidden_cfg,\n",
        "    embedding_cfg=default_embedding_cfg,\n",
        "    num_hidden_instances=cfg[\"num_layers\"],\n",
        "    pooled_output_dim=cfg[\"hidden_size\"],\n",
        "    return_all_layer_outputs=True,\n",
        "    pooler_layer_initializer=tf.keras.initializers.TruncatedNormal(0.02),\n",
        ")\n",
299
        "\n",
300
301
302
303
304
        "encoder_scaffold = modeling.networks.EncoderScaffold(**default_kwargs)\n",
        "classifier_model_from_encoder_scaffold = build_classifier(encoder_scaffold)\n",
        "classifier_model_from_encoder_scaffold.set_weights(\n",
        "    canonical_classifier_model.get_weights())\n",
        "predict(classifier_model_from_encoder_scaffold)"
305
306
307
      ],
      "execution_count": null,
      "outputs": []
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sMaUmLyIuwcs"
      },
      "source": [
        "#### Customize Embedding\n",
        "\n",
        "Next, we show how to use a customized embedding network.\n",
        "\n",
        "We firstly build an embedding network that will replace the default network. This one will have 2 inputs (`mask` and `word_ids`) instead of 3, and won't use positional embeddings."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LTinnaG6vcsw"
      },
      "source": [
        "word_ids = tf.keras.layers.Input(\n",
329
        "    shape=(cfg['max_sequence_length'],), dtype=tf.int32, name=\"input_word_ids\")\n",
330
        "mask = tf.keras.layers.Input(\n",
331
        "    shape=(cfg['max_sequence_length'],), dtype=tf.int32, name=\"input_mask\")\n",
332
333
334
335
336
337
338
339
340
        "embedding_layer = modeling.layers.OnDeviceEmbedding(\n",
        "    vocab_size=cfg['vocab_size'],\n",
        "    embedding_width=cfg['hidden_size'],\n",
        "    initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n",
        "    name=\"word_embeddings\")\n",
        "word_embeddings = embedding_layer(word_ids)\n",
        "attention_mask = layers.SelfAttentionMask()([word_embeddings, mask])\n",
        "new_embedding_network = tf.keras.Model([word_ids, mask],\n",
        "                                       [word_embeddings, attention_mask])"
341
342
343
      ],
      "execution_count": null,
      "outputs": []
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HN7_yu-6O3qI"
      },
      "source": [
        "Inspecting `new_embedding_network`, we can see it takes two inputs:\n",
        "`input_word_ids` and `input_mask`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fO9zKFE4OpHp"
      },
      "source": [
        "tf.keras.utils.plot_model(new_embedding_network, show_shapes=True, dpi=48)"
362
363
364
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9cOaGQHLv12W"
      },
      "source": [
        "We then can build a new encoder using the above `new_embedding_network`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mtFDMNf2vIl9"
      },
      "source": [
        "kwargs = dict(default_kwargs)\n",
        "\n",
        "# Use new embedding network.\n",
        "kwargs['embedding_cls'] = new_embedding_network\n",
        "kwargs['embedding_data'] = embedding_layer.embeddings\n",
        "\n",
        "encoder_with_customized_embedding = modeling.networks.EncoderScaffold(**kwargs)\n",
        "classifier_model = build_classifier(encoder_with_customized_embedding)\n",
        "# ... Train the model ...\n",
        "print(classifier_model.inputs)\n",
        "\n",
        "# Assert that there are only two inputs.\n",
        "assert len(classifier_model.inputs) == 2"
394
395
396
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z73ZQDtmwg9K"
      },
      "source": [
        "#### Customized Transformer\n",
        "\n",
        "User can also override the [hidden_cls](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/networks/encoder_scaffold.py#L103) argument in `EncoderScaffold`'s constructor to employ a customized Transformer layer.\n",
        "\n",
        "See [ReZeroTransformer](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/rezero_transformer.py) for how to implement a customized Transformer layer.\n",
        "\n",
        "Following is an example of using `ReZeroTransformer`:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "uAIarLZgw6pA"
      },
      "source": [
        "kwargs = dict(default_kwargs)\n",
        "\n",
        "# Use ReZeroTransformer.\n",
        "kwargs['hidden_cls'] = modeling.layers.ReZeroTransformer\n",
        "\n",
        "encoder_with_rezero_transformer = modeling.networks.EncoderScaffold(**kwargs)\n",
        "classifier_model = build_classifier(encoder_with_rezero_transformer)\n",
        "# ... Train the model ...\n",
        "predict(classifier_model)\n",
        "\n",
        "# Assert that the variable `rezero_alpha` from ReZeroTransformer exists.\n",
        "assert 'rezero_alpha' in ''.join([x.name for x in classifier_model.trainable_weights])"
431
432
433
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6PMHFdvnxvR0"
      },
      "source": [
        "### Use [TransformerScaffold](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/transformer_scaffold.py)\n",
        "\n",
        "The above method of customizing `Transformer` requires rewriting the whole `Transformer` layer, while sometimes you may only want to customize either attention layer or feedforward block. In this case, [TransformerScaffold](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/transformer_scaffold.py) can be used.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "D6FejlgwyAy_"
      },
      "source": [
        "#### Customize Attention Layer\n",
        "\n",
        "User can also override the [attention_cls](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/transformer_scaffold.py#L45) argument in `TransformerScaffold`'s constructor to employ a customized Attention layer.\n",
        "\n",
        "See [TalkingHeadsAttention](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/talking_heads_attention.py) for how to implement a customized `Attention` layer.\n",
        "\n",
        "Following is an example of using [TalkingHeadsAttention](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/talking_heads_attention.py):"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nFrSMrZuyNeQ"
      },
      "source": [
        "# Use TalkingHeadsAttention\n",
        "hidden_cfg = dict(default_hidden_cfg)\n",
        "hidden_cfg['attention_cls'] = modeling.layers.TalkingHeadsAttention\n",
        "\n",
        "kwargs = dict(default_kwargs)\n",
        "kwargs['hidden_cls'] = modeling.layers.TransformerScaffold\n",
        "kwargs['hidden_cfg'] = hidden_cfg\n",
        "\n",
        "encoder = modeling.networks.EncoderScaffold(**kwargs)\n",
        "classifier_model = build_classifier(encoder)\n",
        "# ... Train the model ...\n",
        "predict(classifier_model)\n",
        "\n",
        "# Assert that the variable `pre_softmax_weight` from TalkingHeadsAttention exists.\n",
        "assert 'pre_softmax_weight' in ''.join([x.name for x in classifier_model.trainable_weights])"
483
484
485
      ],
      "execution_count": null,
      "outputs": []
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
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kuEJcTyByVvI"
      },
      "source": [
        "#### Customize Feedforward Layer\n",
        "\n",
        "Similiarly, one could also customize the feedforward layer.\n",
        "\n",
        "See [GatedFeedforward](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/gated_feedforward.py) for how to implement a customized feedforward layer.\n",
        "\n",
        "Following is an example of using [GatedFeedforward](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/layers/gated_feedforward.py)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XAbKy_l4y_-i"
      },
      "source": [
        "# Use TalkingHeadsAttention\n",
        "hidden_cfg = dict(default_hidden_cfg)\n",
        "hidden_cfg['feedforward_cls'] = modeling.layers.GatedFeedforward\n",
        "\n",
        "kwargs = dict(default_kwargs)\n",
        "kwargs['hidden_cls'] = modeling.layers.TransformerScaffold\n",
        "kwargs['hidden_cfg'] = hidden_cfg\n",
        "\n",
        "encoder_with_gated_feedforward = modeling.networks.EncoderScaffold(**kwargs)\n",
        "classifier_model = build_classifier(encoder_with_gated_feedforward)\n",
        "# ... Train the model ...\n",
        "predict(classifier_model)\n",
        "\n",
        "# Assert that the variable `gate` from GatedFeedforward exists.\n",
        "assert 'gate' in ''.join([x.name for x in classifier_model.trainable_weights])"
523
524
525
      ],
      "execution_count": null,
      "outputs": []
526
527
528
529
530
531
532
533
534
535
536
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "a_8NWUhkzeAq"
      },
      "source": [
        "### Build a new Encoder using building blocks from KerasBERT.\n",
        "\n",
        "Finally, you could also build a new encoder using building blocks in the modeling library.\n",
        "\n",
537
        "See [AlbertEncoder](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/networks/albert_encoder.py) as an example:\n"
538
539
540
541
542
543
544
545
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xsiA3RzUzmUM"
      },
      "source": [
546
        "albert_encoder = modeling.networks.AlbertEncoder(**cfg)\n",
547
548
549
        "classifier_model = build_classifier(albert_encoder)\n",
        "# ... Train the model ...\n",
        "predict(classifier_model)"
550
551
552
      ],
      "execution_count": null,
      "outputs": []
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MeidDfhlHKSO"
      },
      "source": [
        "Inspecting the `albert_encoder`, we see it stacks the same `Transformer` layer multiple times."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Uv_juT22HERW"
      },
      "source": [
        "tf.keras.utils.plot_model(albert_encoder, show_shapes=True, dpi=48)"
570
571
572
      ],
      "execution_count": null,
      "outputs": []
573
    }
574
575
  ]
}