├── .gitignore
├── LICENSE
├── README.md
├── assets
└── performance.png
├── bert
├── data-preparation-sentence-splitter.ipynb
├── data-preparation.ipynb
├── train-model-split-sentence.ipynb
└── train-vanilla-bert.ipynb
├── bigram-tfidf-shallow-mlp.ipynb
└── smart-batching-shallow-mlp.ipynb
/.gitignore:
--------------------------------------------------------------------------------
1 | data/
2 | tfrecords/
3 | tfrecords-sentence-splitter
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2021 Carted
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Handling variable-length text sequences in TensorFlow
2 |
3 | This repository hosts code for the following series of blog posts:
4 |
5 | * [Variable-Length Sequences in TensorFlow Part 1: Optimizing Sequence Padding](https://car.td/3d0891)
6 | * [Variable-Length Sequences in TensorFlow Part 2: Training with a Simple BERT Model](https://car.td/8oa)
7 | * [Variable-Length Sequences in TensorFlow Part 3: Using a Sentence-Conditioned BERT Encoder](https://car.td/q0c)
8 |
9 | We provide code in the form of Jupyter Notebook so that you can experiment with the methods interactively.
10 |
11 | ## What is it about?
12 |
13 | Text data comes in different shapes and forms. Sometimes they come as sequences of characters, sometimes as sequences
14 | of words, and sometimes even as sequences of sentences, and so on. Now, for machine learning (ML) algorithms to process
15 | text sequences in batches the batches need to have uniform-length sequences. However, text sequences can come in varying
16 | lengths.
17 |
18 | In this project, we implement different strategies to handle variable-length sequences in TensorFlow with a focus
19 | on performance. We will discuss the pros and cons of each strategy along with their implementations in TensorFlow.
20 | We have successfully applied some of these strategies to the large-scale data here at Carted and have greatly benefited
21 | from them. We hope you’ll be able to apply them in your own projects as well. Below is a side-by-side comparison
22 | of how efficient handling of variable-length sequences can boost up the model training time:
23 |
24 |
25 |
26 |
27 |
28 | ## General setup
29 |
30 | We’ll be using [this dataset](https://www.kaggle.com/hijest/genre-classification-dataset-imdb) from Kaggle which
31 | concerns a text classification problem. Specifically, given some description of a movie, we need to predict its
32 | genre. Each description consists of multiple sentences and there are 27 unique genres (such as action, adult, adventure,
33 | animation, biography, comedy, etc.).
34 |
35 | As a disclaimer, our focus is on designing efficient data pipelines for handling variable-length text sequences
36 | that can help us reduce compute waste. But we will also see how to use these pipelines to train text classification
37 | models for completeness.
38 |
39 | **Note**: One central theme around our code is to be able to process text sequences in the following manner. Padding a
40 | batch of sequences with respect to the maximum sequence length of the batch instead of a fixed sequence length.
41 |
42 | ## Navigating through the notebooks
43 |
44 | * `bigram-tfidf-shallow-mlp.ipynb`: Shows how to use bigrams along with TF-IDF vectorization to train a simple
45 | test classification model with fully-connected layers.
46 | * `smart-batching-shallow-mlp.ipynb`: Shows how to train a text classifier using simple models consisting of
47 | embeddings, GRUs, and fully-connected layers.
48 | * `bert/`
49 | * `data-preparation.ipynb`: Shows how to prepare text data into TensorFlow Records (TFRecords) with tokenization. The
50 | corresponding modeling notebook is present at `bert/train-vanilla-bert.ipynb`.
51 | * `data-preparation-sentence-splitter.ipynb`: Treats each movie description as a sequence of sentences and
52 | serializes them into TFRecords. The corresponding modeling notebook is present at `bert/train-model-split-sentence.ipynb`.
53 |
54 | All the results discussed in the above-mentioned articles can be found at the following links:
55 |
56 | * https://wandb.ai/carted/smart-batching-simpler-models (simpler models)
57 | * https://wandb.ai/carted/batching-experiments (BERT models)
58 |
59 | ## Questions
60 |
61 | Feel free to open an issue and let us know.
62 |
63 |
--------------------------------------------------------------------------------
/assets/performance.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carted/handling-variable-length-text-tf/9af878fe5e4dc38a15c52d9acb8fe8073f82e3d8/assets/performance.png
--------------------------------------------------------------------------------
/bert/data-preparation-sentence-splitter.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "c6c38a85",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "b9ce6d15",
26 | "metadata": {},
27 | "source": [
28 | "## References\n",
29 | "\n",
30 | "* https://www.kaggle.com/rohitganji13/film-genre-classification-using-nlp\n",
31 | "* Internal (Carted) TFRecord utilities contributed by [Nilabhra Roy Chowdhury](https://www.linkedin.com/in/nilabhraroychowdhury/)"
32 | ]
33 | },
34 | {
35 | "cell_type": "markdown",
36 | "id": "0fee8005",
37 | "metadata": {},
38 | "source": [
39 | "## Setup"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "id": "a1849f47",
46 | "metadata": {},
47 | "outputs": [],
48 | "source": [
49 | "!pip install -U sentence-splitter tensorflow-hub tensorflow_text -q"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "id": "d36e7774",
56 | "metadata": {},
57 | "outputs": [],
58 | "source": [
59 | "!gdown --id 1CvkRnGC8b_-n1NcbwcwxcIq7SusmDMb5 -O train_data.txt\n",
60 | "!gdown --id 1h1evGF5NVi2p8RoWxl8xhpOod0ZN_-ky -O test_data_solution.txt "
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": null,
66 | "id": "65fc8c36",
67 | "metadata": {},
68 | "outputs": [],
69 | "source": [
70 | "import tensorflow as tf\n",
71 | "import tensorflow_text as text\n",
72 | "import tensorflow_hub as hub\n",
73 | "\n",
74 | "from sklearn.preprocessing import LabelEncoder\n",
75 | "from sklearn.model_selection import train_test_split\n",
76 | "from sentence_splitter import split_text_into_sentences\n",
77 | "from typing import List, Callable, Tuple, Dict\n",
78 | "import pandas as pd\n",
79 | "import numpy as np\n",
80 | "import random\n",
81 | "import tqdm\n",
82 | "\n",
83 | "SEED = 42\n",
84 | "tf.random.set_seed(SEED)\n",
85 | "np.random.seed(SEED)\n",
86 | "random.seed(SEED)"
87 | ]
88 | },
89 | {
90 | "cell_type": "markdown",
91 | "id": "fe67b35a",
92 | "metadata": {},
93 | "source": [
94 | "## Data loading\n",
95 | "\n",
96 | "Data comes from here: https://www.kaggle.com/hijest/genre-classification-dataset-imdb."
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": null,
102 | "id": "a39fc6ff",
103 | "metadata": {},
104 | "outputs": [],
105 | "source": [
106 | "train_df = pd.read_csv(\n",
107 | " \"train_data.txt\",\n",
108 | " engine=\"python\",\n",
109 | " sep=\" ::: \",\n",
110 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
111 | ")\n",
112 | "\n",
113 | "test_df = pd.read_csv(\n",
114 | " \"test_data_solution.txt\",\n",
115 | " engine=\"python\",\n",
116 | " sep=\" ::: \",\n",
117 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
118 | ")"
119 | ]
120 | },
121 | {
122 | "cell_type": "code",
123 | "execution_count": null,
124 | "id": "4c1b5c6d",
125 | "metadata": {},
126 | "outputs": [],
127 | "source": [
128 | "# Viewing training data\n",
129 | "train_df.head()"
130 | ]
131 | },
132 | {
133 | "cell_type": "markdown",
134 | "id": "d2754413",
135 | "metadata": {},
136 | "source": [
137 | "## Data splitting"
138 | ]
139 | },
140 | {
141 | "cell_type": "code",
142 | "execution_count": null,
143 | "id": "51e8d0d6",
144 | "metadata": {},
145 | "outputs": [],
146 | "source": [
147 | "# Split the data using train_test_split from sklearn\n",
148 | "train_shuffled = train_df.sample(frac=1.0)\n",
149 | "train_df, val_df = train_test_split(train_shuffled, test_size=0.1)\n",
150 | "\n",
151 | "print(f\"Number of training samples: {len(train_df)}.\")\n",
152 | "print(f\"Number of validation samples: {len(val_df)}.\")\n",
153 | "print(f\"Number of test examples: {len(test_df)}.\")"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": null,
159 | "id": "149c90e6",
160 | "metadata": {},
161 | "outputs": [],
162 | "source": [
163 | "le = LabelEncoder()\n",
164 | "le.fit(train_df[\"genre\"].values)\n",
165 | "\n",
166 | "train_df[\"genre\"] = le.transform(train_df[\"genre\"].values)\n",
167 | "val_df[\"genre\"] = le.transform(val_df[\"genre\"].values)\n",
168 | "test_df[\"genre\"] = le.transform(test_df[\"genre\"].values)"
169 | ]
170 | },
171 | {
172 | "cell_type": "markdown",
173 | "id": "3a2996d9",
174 | "metadata": {},
175 | "source": [
176 | "## Data preprocessing utilities"
177 | ]
178 | },
179 | {
180 | "cell_type": "code",
181 | "execution_count": null,
182 | "id": "13e44536",
183 | "metadata": {},
184 | "outputs": [],
185 | "source": [
186 | "def set_tokenizer(preprocessor_path: str) -> Callable:\n",
187 | " \"\"\"Decorator to set the desired tokenizer for a tokenizing\n",
188 | " function from a TensorFlow Hub URL.\n",
189 | "\n",
190 | " Arguments:\n",
191 | " preprocessor_path {str} -- URL of the TF-Hub preprocessor.\n",
192 | "\n",
193 | " Returns:\n",
194 | " Callable -- A function with the `tokenizer` attribute set.\n",
195 | " \"\"\"\n",
196 | "\n",
197 | " def decoration(func: Callable):\n",
198 | " # Loading the preprocessor from TF-Hub\n",
199 | " preprocessor = hub.load(preprocessor_path)\n",
200 | "\n",
201 | " # Setting an attribute called `tokenizer` to\n",
202 | " # the passed function\n",
203 | " func.tokenizer = preprocessor.tokenize\n",
204 | " return func\n",
205 | "\n",
206 | " return decoration"
207 | ]
208 | },
209 | {
210 | "cell_type": "code",
211 | "execution_count": null,
212 | "id": "f1e8a01f",
213 | "metadata": {},
214 | "outputs": [],
215 | "source": [
216 | "def _bytes_feature(bytes_input: bytes) -> tf.train.Feature:\n",
217 | " \"\"\"Encodes given data as a byte feature.\"\"\"\n",
218 | " bytes_list = tf.train.BytesList(value=[bytes_input])\n",
219 | " return tf.train.Feature(bytes_list=bytes_list)\n",
220 | "\n",
221 | "\n",
222 | "def _ints_feature(int_input: int) -> tf.train.Feature:\n",
223 | " \"\"\"Encoded given data as an integer feature.\"\"\"\n",
224 | " int64_list = tf.train.Int64List(value=int_input)\n",
225 | " return tf.train.Feature(int64_list=int64_list)\n",
226 | "\n",
227 | "\n",
228 | "def _ragged_feature(\n",
229 | " ragged_input: tf.RaggedTensor, name: str\n",
230 | ") -> Dict[str, tf.train.Feature]:\n",
231 | " \"\"\"Returns a dictionary to represent a single ragged tensor as int64 features.\"\"\"\n",
232 | " int64_components = {f\"{name}_values\": _ints_feature(ragged_input.flat_values)}\n",
233 | "\n",
234 | " # Collecting boundary informations for the ragged dimensions\n",
235 | " for i, d in enumerate(ragged_input.nested_row_splits):\n",
236 | " int64_components[f\"{name}_splits_{i}\"] = _ints_feature(d)\n",
237 | " return int64_components"
238 | ]
239 | },
240 | {
241 | "cell_type": "markdown",
242 | "id": "3ebdd96c",
243 | "metadata": {},
244 | "source": [
245 | "To know more about these utilities refer to the official guide [here](https://www.tensorflow.org/tutorials/load_data/tfrecord)."
246 | ]
247 | },
248 | {
249 | "cell_type": "code",
250 | "execution_count": null,
251 | "id": "7da6d30c",
252 | "metadata": {},
253 | "outputs": [],
254 | "source": [
255 | "@set_tokenizer(\n",
256 | " preprocessor_path=\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\"\n",
257 | ")\n",
258 | "def _tokenize_text(text: List[str]) -> Tuple[tf.RaggedTensor, List[int]]:\n",
259 | " \"\"\"Tokenizes a list of sentences.\n",
260 | " Args:\n",
261 | " text (List[str]): A list of sentences.\n",
262 | " Returns:\n",
263 | " Tuple[tf.RaggedTensor, List[int]]: Tokenized and indexed sentences, list containing\n",
264 | " the number of tokens per sentence.\n",
265 | " \"\"\"\n",
266 | " token_list = _tokenize_text.tokenizer(tf.constant(text))\n",
267 | " token_lens = [tokens.flat_values.shape[-1] for tokens in token_list]\n",
268 | " return token_list, token_lens\n",
269 | "\n",
270 | "\n",
271 | "def get_serialized_text_features(features):\n",
272 | " \"\"\"Serializes all the Ragged features.\"\"\"\n",
273 | " tokens = features[\"tokens\"]\n",
274 | " tokens = _ragged_feature(tokens, \"summary_sentences\")\n",
275 | "\n",
276 | " lens = features[\"lens\"]\n",
277 | " lens = tf.ragged.constant([lens])\n",
278 | " lens = _ragged_feature(lens, \"summary_sentence_lens\")\n",
279 | "\n",
280 | " return tokens, lens"
281 | ]
282 | },
283 | {
284 | "cell_type": "code",
285 | "execution_count": null,
286 | "id": "5f3c3925",
287 | "metadata": {},
288 | "outputs": [],
289 | "source": [
290 | "def create_example(row):\n",
291 | " \"\"\"Creates one TFRecord example.\"\"\"\n",
292 | " summary = row[\"summary\"]\n",
293 | " label = row[\"genre\"]\n",
294 | "\n",
295 | " description = bytes(summary, encoding=\"utf-8\")\n",
296 | " description_tokens, description_lens = _tokenize_text(\n",
297 | " split_text_into_sentences(summary, language=\"en\")\n",
298 | " )\n",
299 | " num_sentences = len(description_lens)\n",
300 | "\n",
301 | " features = {\n",
302 | " \"tokens\": description_tokens,\n",
303 | " \"lens\": description_lens,\n",
304 | " }\n",
305 | " text_tokens, text_lens = get_serialized_text_features(features)\n",
306 | "\n",
307 | " feature = {\n",
308 | " \"summary\": _bytes_feature(description),\n",
309 | " \"summary_num_sentences\": _ints_feature([num_sentences]),\n",
310 | " \"label\": _ints_feature([label]),\n",
311 | " }\n",
312 | "\n",
313 | " feature.update(text_tokens)\n",
314 | " feature.update(text_lens)\n",
315 | "\n",
316 | " feature = tf.train.Features(feature=feature)\n",
317 | " example = tf.train.Example(features=feature)\n",
318 | " return example\n",
319 | "\n",
320 | "\n",
321 | "def write_tfrecords(file_name, data):\n",
322 | " \"\"\"Serializes the data as string.\"\"\"\n",
323 | " with tf.io.TFRecordWriter(file_name) as writer:\n",
324 | " for i, row in data.iterrows():\n",
325 | " example = create_example(row)\n",
326 | " writer.write(example.SerializeToString())"
327 | ]
328 | },
329 | {
330 | "cell_type": "markdown",
331 | "id": "ed0a0aed",
332 | "metadata": {},
333 | "source": [
334 | "## Write to TFRecords"
335 | ]
336 | },
337 | {
338 | "cell_type": "code",
339 | "execution_count": null,
340 | "id": "347762b1",
341 | "metadata": {},
342 | "outputs": [],
343 | "source": [
344 | "TFRECORDS_DIR = \"tfrecords-sentence-splitter\"\n",
345 | "tf.io.gfile.makedirs(TFRECORDS_DIR)"
346 | ]
347 | },
348 | {
349 | "cell_type": "code",
350 | "execution_count": null,
351 | "id": "5cf499c1",
352 | "metadata": {},
353 | "outputs": [],
354 | "source": [
355 | "def write_data(data, chunk_size, files_prefix):\n",
356 | " \"\"\"Serializes data as TFRecord shards.\"\"\"\n",
357 | " example_counter = 0\n",
358 | " chunk_count = 1\n",
359 | " for i in tqdm.tqdm(range(0, data.shape[0], chunk_size)):\n",
360 | " chunk = data.iloc[i : i + chunk_size, :]\n",
361 | " file_name = f\"{TFRECORDS_DIR}/{files_prefix}-{chunk_count:02d}.tfrecord\"\n",
362 | " write_tfrecords(file_name, chunk)\n",
363 | " example_counter += chunk.shape[0]\n",
364 | " chunk_count += 1\n",
365 | " return example_counter"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": null,
371 | "id": "d4250f64",
372 | "metadata": {},
373 | "outputs": [],
374 | "source": [
375 | "CHUNK_SIZE = 100"
376 | ]
377 | },
378 | {
379 | "cell_type": "code",
380 | "execution_count": null,
381 | "id": "17ec541e",
382 | "metadata": {},
383 | "outputs": [],
384 | "source": [
385 | "train_example_count = write_data(train_df, CHUNK_SIZE, \"train\")\n",
386 | "train_example_count"
387 | ]
388 | },
389 | {
390 | "cell_type": "code",
391 | "execution_count": null,
392 | "id": "4192fc15",
393 | "metadata": {},
394 | "outputs": [],
395 | "source": [
396 | "val_example_count = write_data(val_df, CHUNK_SIZE, \"val\")\n",
397 | "val_example_count"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": null,
403 | "id": "a6724a0e",
404 | "metadata": {},
405 | "outputs": [],
406 | "source": [
407 | "test_example_count = write_data(test_df, CHUNK_SIZE, \"test\")\n",
408 | "test_example_count"
409 | ]
410 | }
411 | ],
412 | "metadata": {
413 | "kernelspec": {
414 | "display_name": "Python 3 (ipykernel)",
415 | "language": "python",
416 | "name": "python3"
417 | },
418 | "language_info": {
419 | "codemirror_mode": {
420 | "name": "ipython",
421 | "version": 3
422 | },
423 | "file_extension": ".py",
424 | "mimetype": "text/x-python",
425 | "name": "python",
426 | "nbconvert_exporter": "python",
427 | "pygments_lexer": "ipython3",
428 | "version": "3.8.2"
429 | }
430 | },
431 | "nbformat": 4,
432 | "nbformat_minor": 5
433 | }
434 |
--------------------------------------------------------------------------------
/bert/data-preparation.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "73199a82",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "b9ce6d15",
26 | "metadata": {},
27 | "source": [
28 | "## References\n",
29 | "\n",
30 | "* https://www.kaggle.com/rohitganji13/film-genre-classification-using-nlp\n",
31 | "* Internal (Carted) TFRecord utilities contributed by [Nilabhra Roy Chowdhury](https://www.linkedin.com/in/nilabhraroychowdhury/)"
32 | ]
33 | },
34 | {
35 | "cell_type": "markdown",
36 | "id": "0fee8005",
37 | "metadata": {},
38 | "source": [
39 | "## Setup"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": null,
45 | "id": "ced81606",
46 | "metadata": {},
47 | "outputs": [],
48 | "source": [
49 | "!pip install -U sentence-splitter tensorflow-hub tensorflow_text -q"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "id": "8f4005bb",
56 | "metadata": {},
57 | "outputs": [],
58 | "source": [
59 | "!gdown --id 1CvkRnGC8b_-n1NcbwcwxcIq7SusmDMb5 -O train_data.txt\n",
60 | "!gdown --id 1h1evGF5NVi2p8RoWxl8xhpOod0ZN_-ky -O test_data_solution.txt "
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": 19,
66 | "id": "65fc8c36",
67 | "metadata": {},
68 | "outputs": [],
69 | "source": [
70 | "import tensorflow as tf\n",
71 | "import tensorflow_text as text\n",
72 | "import tensorflow_hub as hub\n",
73 | "\n",
74 | "from sklearn.preprocessing import LabelEncoder\n",
75 | "from sklearn.model_selection import train_test_split\n",
76 | "from typing import Callable, Tuple, Dict\n",
77 | "import pandas as pd\n",
78 | "import numpy as np\n",
79 | "import random\n",
80 | "import tqdm\n",
81 | "\n",
82 | "SEED = 42\n",
83 | "tf.random.set_seed(SEED)\n",
84 | "np.random.seed(SEED)\n",
85 | "random.seed(SEED)"
86 | ]
87 | },
88 | {
89 | "cell_type": "markdown",
90 | "id": "fe67b35a",
91 | "metadata": {},
92 | "source": [
93 | "## Data loading\n",
94 | "\n",
95 | "Data comes from here: https://www.kaggle.com/hijest/genre-classification-dataset-imdb."
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 20,
101 | "id": "a39fc6ff",
102 | "metadata": {},
103 | "outputs": [],
104 | "source": [
105 | "train_df = pd.read_csv(\n",
106 | " \"train_data.txt\",\n",
107 | " engine=\"python\",\n",
108 | " sep=\" ::: \",\n",
109 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
110 | ")\n",
111 | "\n",
112 | "test_df = pd.read_csv(\n",
113 | " \"test_data_solution.txt\",\n",
114 | " engine=\"python\",\n",
115 | " sep=\" ::: \",\n",
116 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
117 | ")"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": 21,
123 | "id": "4c1b5c6d",
124 | "metadata": {},
125 | "outputs": [
126 | {
127 | "data": {
128 | "text/html": [
129 | "\n",
130 | "\n",
143 | "
\n",
144 | " \n",
145 | " \n",
146 | " | \n",
147 | " id | \n",
148 | " movie | \n",
149 | " genre | \n",
150 | " summary | \n",
151 | "
\n",
152 | " \n",
153 | " \n",
154 | " \n",
155 | " 0 | \n",
156 | " 1 | \n",
157 | " Oscar et la dame rose (2009) | \n",
158 | " drama | \n",
159 | " Listening in to a conversation between his doc... | \n",
160 | "
\n",
161 | " \n",
162 | " 1 | \n",
163 | " 2 | \n",
164 | " Cupid (1997) | \n",
165 | " thriller | \n",
166 | " A brother and sister with a past incestuous re... | \n",
167 | "
\n",
168 | " \n",
169 | " 2 | \n",
170 | " 3 | \n",
171 | " Young, Wild and Wonderful (1980) | \n",
172 | " adult | \n",
173 | " As the bus empties the students for their fiel... | \n",
174 | "
\n",
175 | " \n",
176 | " 3 | \n",
177 | " 4 | \n",
178 | " The Secret Sin (1915) | \n",
179 | " drama | \n",
180 | " To help their unemployed father make ends meet... | \n",
181 | "
\n",
182 | " \n",
183 | " 4 | \n",
184 | " 5 | \n",
185 | " The Unrecovered (2007) | \n",
186 | " drama | \n",
187 | " The film's title refers not only to the un-rec... | \n",
188 | "
\n",
189 | " \n",
190 | "
\n",
191 | "
"
192 | ],
193 | "text/plain": [
194 | " id movie genre \\\n",
195 | "0 1 Oscar et la dame rose (2009) drama \n",
196 | "1 2 Cupid (1997) thriller \n",
197 | "2 3 Young, Wild and Wonderful (1980) adult \n",
198 | "3 4 The Secret Sin (1915) drama \n",
199 | "4 5 The Unrecovered (2007) drama \n",
200 | "\n",
201 | " summary \n",
202 | "0 Listening in to a conversation between his doc... \n",
203 | "1 A brother and sister with a past incestuous re... \n",
204 | "2 As the bus empties the students for their fiel... \n",
205 | "3 To help their unemployed father make ends meet... \n",
206 | "4 The film's title refers not only to the un-rec... "
207 | ]
208 | },
209 | "execution_count": 21,
210 | "metadata": {},
211 | "output_type": "execute_result"
212 | }
213 | ],
214 | "source": [
215 | "# Viewing training data\n",
216 | "train_df.head()"
217 | ]
218 | },
219 | {
220 | "cell_type": "markdown",
221 | "id": "d2754413",
222 | "metadata": {},
223 | "source": [
224 | "## Data splitting"
225 | ]
226 | },
227 | {
228 | "cell_type": "code",
229 | "execution_count": 22,
230 | "id": "51e8d0d6",
231 | "metadata": {},
232 | "outputs": [
233 | {
234 | "name": "stdout",
235 | "output_type": "stream",
236 | "text": [
237 | "Number of training samples: 48792.\n",
238 | "Number of validation samples: 5422.\n",
239 | "Number of test examples: 54200.\n"
240 | ]
241 | }
242 | ],
243 | "source": [
244 | "# Split the data using train_test_split from sklearn\n",
245 | "train_shuffled = train_df.sample(frac=1)\n",
246 | "train_df_new, val_df = train_test_split(train_shuffled, test_size=0.1)\n",
247 | "\n",
248 | "print(f\"Number of training samples: {len(train_df_new)}.\")\n",
249 | "print(f\"Number of validation samples: {len(val_df)}.\")\n",
250 | "print(f\"Number of test examples: {len(test_df)}.\")"
251 | ]
252 | },
253 | {
254 | "cell_type": "code",
255 | "execution_count": 23,
256 | "id": "149c90e6",
257 | "metadata": {},
258 | "outputs": [],
259 | "source": [
260 | "le = LabelEncoder()\n",
261 | "le.fit(train_df_new[\"genre\"].values) \n",
262 | "\n",
263 | "train_df_new[\"genre\"] = le.transform(train_df_new[\"genre\"].values)\n",
264 | "val_df[\"genre\"] = le.transform(val_df[\"genre\"].values)\n",
265 | "test_df[\"genre\"] = le.transform(test_df[\"genre\"].values)"
266 | ]
267 | },
268 | {
269 | "cell_type": "markdown",
270 | "id": "3a2996d9",
271 | "metadata": {},
272 | "source": [
273 | "## Data preprocessing utilities"
274 | ]
275 | },
276 | {
277 | "cell_type": "code",
278 | "execution_count": 24,
279 | "id": "13e44536",
280 | "metadata": {},
281 | "outputs": [],
282 | "source": [
283 | "def set_tokenizer(preprocessor_path: str) -> Callable:\n",
284 | " \"\"\" Decorator to set the desired tokenizer for a tokenizing\n",
285 | " function from a TensorFlow Hub URL.\n",
286 | " \n",
287 | " Arguments:\n",
288 | " preprocessor_path {str} -- URL of the TF-Hub preprocessor.\n",
289 | " \n",
290 | " Returns:\n",
291 | " Callable -- A function with the `tokenizer` attribute set.\n",
292 | " \"\"\"\n",
293 | "\n",
294 | " def decoration(func: Callable):\n",
295 | " # Loading the preprocessor from TF-Hub\n",
296 | " preprocessor = hub.load(preprocessor_path)\n",
297 | "\n",
298 | " # Setting an attribute called `tokenizer` to\n",
299 | " # the passed function\n",
300 | " func.tokenizer = preprocessor.tokenize\n",
301 | " return func\n",
302 | "\n",
303 | " return decoration"
304 | ]
305 | },
306 | {
307 | "cell_type": "code",
308 | "execution_count": 25,
309 | "id": "f1e8a01f",
310 | "metadata": {},
311 | "outputs": [],
312 | "source": [
313 | "def _bytes_feature(bytes_input: bytes) -> tf.train.Feature:\n",
314 | " \"\"\"Encodes given data as a byte feature.\"\"\"\n",
315 | " bytes_list = tf.train.BytesList(value=[bytes_input])\n",
316 | " return tf.train.Feature(bytes_list=bytes_list)\n",
317 | "\n",
318 | "\n",
319 | "def _ints_feature(int_input: int) -> tf.train.Feature:\n",
320 | " \"\"\"Encoded given data as an integer feature.\"\"\"\n",
321 | " int64_list = tf.train.Int64List(value=int_input)\n",
322 | " return tf.train.Feature(int64_list=int64_list)\n",
323 | "\n",
324 | "\n",
325 | "def _ragged_feature(\n",
326 | " ragged_input: tf.RaggedTensor, name: str\n",
327 | ") -> Dict[str, tf.train.Feature]:\n",
328 | " \"\"\"Returns a dictionary to represent a single ragged tensor as int64 features.\"\"\"\n",
329 | " int64_components = {f\"{name}_values\": _ints_feature(ragged_input.flat_values)}\n",
330 | " \n",
331 | " # Collecting boundary informations for the ragged dimensions\n",
332 | " for i, d in enumerate(ragged_input.nested_row_splits):\n",
333 | " int64_components[f\"{name}_splits_{i}\"] = _ints_feature(d)\n",
334 | " return int64_components"
335 | ]
336 | },
337 | {
338 | "cell_type": "markdown",
339 | "id": "3ebdd96c",
340 | "metadata": {},
341 | "source": [
342 | "To know more about these utilities refer to the official guide [here](https://www.tensorflow.org/tutorials/load_data/tfrecord)."
343 | ]
344 | },
345 | {
346 | "cell_type": "code",
347 | "execution_count": 26,
348 | "id": "7da6d30c",
349 | "metadata": {},
350 | "outputs": [],
351 | "source": [
352 | "@set_tokenizer(\n",
353 | " preprocessor_path=\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\"\n",
354 | ")\n",
355 | "def _tokenize_text(text: str) -> Tuple[tf.RaggedTensor, int]:\n",
356 | " \"\"\"Tokenizes text and returns text token and their length.\"\"\"\n",
357 | " toks = _tokenize_text.tokenizer(tf.constant([text]))\n",
358 | " num_tokens = toks.flat_values.shape[-1]\n",
359 | " return toks, num_tokens"
360 | ]
361 | },
362 | {
363 | "cell_type": "code",
364 | "execution_count": 27,
365 | "id": "61ac19cf",
366 | "metadata": {},
367 | "outputs": [],
368 | "source": [
369 | "preprocessor = hub.load(\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\")\n",
370 | "tokenizer = preprocessor.tokenize"
371 | ]
372 | },
373 | {
374 | "cell_type": "code",
375 | "execution_count": 28,
376 | "id": "ae71fdb7",
377 | "metadata": {},
378 | "outputs": [
379 | {
380 | "data": {
381 | "text/plain": [
382 | ""
383 | ]
384 | },
385 | "execution_count": 28,
386 | "metadata": {},
387 | "output_type": "execute_result"
388 | }
389 | ],
390 | "source": [
391 | "idx = np.random.choice(len(train_df_new))\n",
392 | "sample_text = train_df_new[\"summary\"][idx]\n",
393 | "tokens = tokenizer([sample_text])\n",
394 | "tokens"
395 | ]
396 | },
397 | {
398 | "cell_type": "code",
399 | "execution_count": 29,
400 | "id": "887737e8",
401 | "metadata": {},
402 | "outputs": [
403 | {
404 | "data": {
405 | "text/plain": [
406 | "'After Trishna marries her sweetheart, Dr. Aditya Bhargava, she finds out that he used to love Ishita Singhania, the only daughter of a multi-millionaire. She also finds out that her marriage to Aditya resulted in a major trauma for Ishita, who had to be institutionalized for sometime. Now Ishita has recovered, and someone is trying to kill Trishna, and the problem is that no one is willing to believe her.'"
407 | ]
408 | },
409 | "execution_count": 29,
410 | "metadata": {},
411 | "output_type": "execute_result"
412 | }
413 | ],
414 | "source": [
415 | "sample_text"
416 | ]
417 | },
418 | {
419 | "cell_type": "code",
420 | "execution_count": 32,
421 | "id": "5f3c3925",
422 | "metadata": {},
423 | "outputs": [],
424 | "source": [
425 | "def create_example(row):\n",
426 | " \"\"\"Creates one TFRecord example.\"\"\"\n",
427 | " summary = row[\"summary\"]\n",
428 | " label = row[\"genre\"]\n",
429 | "\n",
430 | " description = bytes(summary, encoding=\"utf-8\")\n",
431 | " description_tokens, description_len = _tokenize_text(summary)\n",
432 | "\n",
433 | " feature = {\n",
434 | " \"summary\": _bytes_feature(description),\n",
435 | " \"summary_tokens_len\": _ints_feature([description_len]),\n",
436 | " \"label\": _ints_feature([label]),\n",
437 | " }\n",
438 | " feature.update(_ragged_feature(description_tokens, \"summary_tokens\"))\n",
439 | " feature = tf.train.Features(feature=feature)\n",
440 | " example = tf.train.Example(features=feature)\n",
441 | " return example\n",
442 | "\n",
443 | "\n",
444 | "def write_tfrecords(file_name, data):\n",
445 | " \"\"\"Serializes the data as string.\"\"\"\n",
446 | " with tf.io.TFRecordWriter(file_name) as writer:\n",
447 | " for i, row in data.iterrows():\n",
448 | " example = create_example(row)\n",
449 | " writer.write(example.SerializeToString())"
450 | ]
451 | },
452 | {
453 | "cell_type": "markdown",
454 | "id": "ed0a0aed",
455 | "metadata": {},
456 | "source": [
457 | "## Write to TFRecords"
458 | ]
459 | },
460 | {
461 | "cell_type": "code",
462 | "execution_count": 33,
463 | "id": "347762b1",
464 | "metadata": {},
465 | "outputs": [],
466 | "source": [
467 | "TFRECORDS_DIR = \"tfrecords\"\n",
468 | "tf.io.gfile.makedirs(TFRECORDS_DIR)"
469 | ]
470 | },
471 | {
472 | "cell_type": "code",
473 | "execution_count": 34,
474 | "id": "5cf499c1",
475 | "metadata": {},
476 | "outputs": [],
477 | "source": [
478 | "def write_data(data, chunk_size, files_prefix):\n",
479 | " \"\"\"Serializes data as TFRecord shards.\"\"\"\n",
480 | " example_counter = 0\n",
481 | " chunk_count = 1\n",
482 | " for i in tqdm.tqdm(range(0, data.shape[0], chunk_size)):\n",
483 | " chunk = data.iloc[i : i + chunk_size, :]\n",
484 | " file_name = f\"{TFRECORDS_DIR}/{files_prefix}-{chunk_count:02d}.tfrecord\"\n",
485 | " write_tfrecords(file_name, chunk)\n",
486 | " example_counter += chunk.shape[0]\n",
487 | " chunk_count += 1\n",
488 | " return example_counter"
489 | ]
490 | },
491 | {
492 | "cell_type": "code",
493 | "execution_count": 35,
494 | "id": "d4250f64",
495 | "metadata": {},
496 | "outputs": [],
497 | "source": [
498 | "CHUNK_SIZE = 100"
499 | ]
500 | },
501 | {
502 | "cell_type": "code",
503 | "execution_count": 36,
504 | "id": "17ec541e",
505 | "metadata": {},
506 | "outputs": [
507 | {
508 | "name": "stderr",
509 | "output_type": "stream",
510 | "text": [
511 | "100%|██████████| 488/488 [23:59<00:00, 2.95s/it]\n"
512 | ]
513 | },
514 | {
515 | "data": {
516 | "text/plain": [
517 | "48792"
518 | ]
519 | },
520 | "execution_count": 36,
521 | "metadata": {},
522 | "output_type": "execute_result"
523 | }
524 | ],
525 | "source": [
526 | "train_example_count = write_data(train_df_new, CHUNK_SIZE, \"train\")\n",
527 | "train_example_count"
528 | ]
529 | },
530 | {
531 | "cell_type": "code",
532 | "execution_count": 37,
533 | "id": "4192fc15",
534 | "metadata": {},
535 | "outputs": [
536 | {
537 | "name": "stderr",
538 | "output_type": "stream",
539 | "text": [
540 | "100%|██████████| 55/55 [02:35<00:00, 2.83s/it]\n"
541 | ]
542 | },
543 | {
544 | "data": {
545 | "text/plain": [
546 | "5422"
547 | ]
548 | },
549 | "execution_count": 37,
550 | "metadata": {},
551 | "output_type": "execute_result"
552 | }
553 | ],
554 | "source": [
555 | "val_example_count = write_data(val_df, CHUNK_SIZE, \"val\")\n",
556 | "val_example_count"
557 | ]
558 | },
559 | {
560 | "cell_type": "code",
561 | "execution_count": 38,
562 | "id": "a6724a0e",
563 | "metadata": {},
564 | "outputs": [
565 | {
566 | "name": "stderr",
567 | "output_type": "stream",
568 | "text": [
569 | "100%|██████████| 542/542 [26:58<00:00, 2.99s/it]\n"
570 | ]
571 | },
572 | {
573 | "data": {
574 | "text/plain": [
575 | "54200"
576 | ]
577 | },
578 | "execution_count": 38,
579 | "metadata": {},
580 | "output_type": "execute_result"
581 | }
582 | ],
583 | "source": [
584 | "test_example_count = write_data(test_df, CHUNK_SIZE, \"test\")\n",
585 | "test_example_count"
586 | ]
587 | }
588 | ],
589 | "metadata": {
590 | "environment": {
591 | "name": "tf2-gpu.2-6.m81",
592 | "type": "gcloud",
593 | "uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-6:m81"
594 | },
595 | "kernelspec": {
596 | "display_name": "Python 3 (ipykernel)",
597 | "language": "python",
598 | "name": "python3"
599 | },
600 | "language_info": {
601 | "codemirror_mode": {
602 | "name": "ipython",
603 | "version": 3
604 | },
605 | "file_extension": ".py",
606 | "mimetype": "text/x-python",
607 | "name": "python",
608 | "nbconvert_exporter": "python",
609 | "pygments_lexer": "ipython3",
610 | "version": "3.8.2"
611 | }
612 | },
613 | "nbformat": 4,
614 | "nbformat_minor": 5
615 | }
616 |
--------------------------------------------------------------------------------
/bert/train-model-split-sentence.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "5abc76e6",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "f943bf42",
26 | "metadata": {},
27 | "source": [
28 | "## Imports"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": null,
34 | "id": "9014279e",
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "from typing import Callable, Dict\n",
39 | "import tensorflow_hub as hub\n",
40 | "import tensorflow_text\n",
41 | "import tensorflow as tf\n",
42 | "import numpy as np\n",
43 | "import wandb\n",
44 | "import random\n",
45 | "import time\n",
46 | "\n",
47 | "SEED = 42\n",
48 | "tf.random.set_seed(SEED)\n",
49 | "np.random.seed(SEED)\n",
50 | "random.seed(SEED)"
51 | ]
52 | },
53 | {
54 | "cell_type": "markdown",
55 | "id": "44377fcf",
56 | "metadata": {},
57 | "source": [
58 | "## Contants"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": null,
64 | "id": "3d42dd4b",
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "TFRECORDS_DIR = \"tfrecords-sentence-splitter\"\n",
69 | "BERT_MAX_SEQLEN = 512\n",
70 | "BERT_DIM = 768\n",
71 | "BATCH_SIZE = 64\n",
72 | "AUTO = tf.data.AUTOTUNE\n",
73 | "NUM_EPOCHS = 5\n",
74 | "NUM_RUNS = 10"
75 | ]
76 | },
77 | {
78 | "cell_type": "markdown",
79 | "id": "9126bde2",
80 | "metadata": {},
81 | "source": [
82 | "## TFRecord parsing utilities"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": null,
88 | "id": "d994d00e",
89 | "metadata": {},
90 | "outputs": [],
91 | "source": [
92 | "feature_descriptions = {\n",
93 | " \"summary\": tf.io.FixedLenFeature([], dtype=tf.string),\n",
94 | " \"summary_sentences\": tf.io.RaggedFeature(\n",
95 | " value_key=\"summary_sentences_values\",\n",
96 | " dtype=tf.int64,\n",
97 | " partitions=[\n",
98 | " tf.io.RaggedFeature.RowSplits(\"summary_sentences_splits_0\"),\n",
99 | " tf.io.RaggedFeature.RowSplits(\"summary_sentences_splits_1\"),\n",
100 | " ],\n",
101 | " ),\n",
102 | " \"summary_sentence_lens\": tf.io.RaggedFeature(\n",
103 | " value_key=\"summary_sentence_lens_values\",\n",
104 | " dtype=tf.int64,\n",
105 | " partitions=[\n",
106 | " tf.io.RaggedFeature.RowSplits(\"summary_sentence_lens_splits_0\"),\n",
107 | " ],\n",
108 | " ),\n",
109 | " \"summary_num_sentences\": tf.io.FixedLenFeature([], dtype=tf.int64),\n",
110 | " \"label\": tf.io.FixedLenFeature([1], dtype=tf.int64),\n",
111 | "}"
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": null,
117 | "id": "47a5de49",
118 | "metadata": {},
119 | "outputs": [],
120 | "source": [
121 | "def read_example(example):\n",
122 | " \"\"\"Parses a single TFRecord file.\"\"\"\n",
123 | " features = tf.io.parse_single_example(example, feature_descriptions)\n",
124 | "\n",
125 | " # Re-casting as int32 RaggedTensors\n",
126 | " features[\"summary_sentences\"] = tf.cast(\n",
127 | " features[\"summary_sentences\"].with_row_splits_dtype(tf.int64), tf.int32\n",
128 | " )\n",
129 | " features[\"summary_sentence_lens\"] = tf.cast(\n",
130 | " features[\"summary_sentence_lens\"].with_row_splits_dtype(tf.int64), tf.int32\n",
131 | " )\n",
132 | "\n",
133 | " return features"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "id": "ce6c4f39",
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "class ModelInputUtils:\n",
144 | " def __init__(\n",
145 | " self,\n",
146 | " bert_preprocessor_path: str = \"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\",\n",
147 | " encoder_max_seqlen: int = BERT_MAX_SEQLEN,\n",
148 | " dynamic_batching: bool = True,\n",
149 | " data_max_seq_len: int = 0,\n",
150 | " ):\n",
151 | " \"\"\"Initializes a BERT model input preprocessing utility class.\"\"\"\n",
152 | " self.bert_preprocessor_path = bert_preprocessor_path\n",
153 | " self.preprocessor_module = hub.load(bert_preprocessor_path)\n",
154 | " self.encoder_max_seqlen = encoder_max_seqlen\n",
155 | "\n",
156 | " max_seq_len = tf.minimum(data_max_seq_len + 2, encoder_max_seqlen)\n",
157 | " self.packer = hub.KerasLayer(\n",
158 | " self.preprocessor_module.bert_pack_inputs,\n",
159 | " arguments={\"seq_length\": max_seq_len},\n",
160 | " )\n",
161 | " self.dynamic_batching = tf.constant(dynamic_batching)\n",
162 | "\n",
163 | " def pack_inputs(self, batch_tokens: tf.Tensor) -> tf.Tensor:\n",
164 | " \"\"\"Prepares inputs for the BERT encoder\"\"\"\n",
165 | " return self.packer([batch_tokens])\n",
166 | "\n",
167 | " def init_packer_and_pack_inputs(\n",
168 | " self, batch_tokens: tf.Tensor, batch_token_lens: tf.Tensor\n",
169 | " ) -> tf.Tensor:\n",
170 | " \"\"\"Prepares inputs for the BERT encoder.\"\"\"\n",
171 | " max_token_len = tf.reduce_max(batch_token_lens)\n",
172 | " packer = hub.KerasLayer(\n",
173 | " self.preprocessor_module.bert_pack_inputs,\n",
174 | " arguments={\n",
175 | " \"seq_length\": tf.math.minimum(\n",
176 | " max_token_len + 2, self.encoder_max_seqlen\n",
177 | " )\n",
178 | " },\n",
179 | " )\n",
180 | " return packer([batch_tokens])\n",
181 | "\n",
182 | " def get_bert_inputs(self, batch, batch_size):\n",
183 | " \"\"\"Generates padded BERT inputs for a given batch of tokenied\n",
184 | " text features.\"\"\"\n",
185 | "\n",
186 | " # Unravelling a batch of RaggedTensors\n",
187 | " tokens = batch.pop(\"summary_sentences\").merge_dims(0, 1)\n",
188 | "\n",
189 | " # obtain the BERT inputs\n",
190 | " bert_inputs = tf.cond(\n",
191 | " self.dynamic_batching,\n",
192 | " lambda: self.init_packer_and_pack_inputs(\n",
193 | " tokens, batch.pop(\"summary_sentence_lens\").flat_values\n",
194 | " ),\n",
195 | " lambda: self.pack_inputs(tokens),\n",
196 | " )\n",
197 | "\n",
198 | " return bert_inputs\n",
199 | "\n",
200 | " def preprocess_batch(self, batch: Dict[str, tf.Tensor]):\n",
201 | " \"\"\"Applies batch level transformations to the data.\"\"\"\n",
202 | " batch_size = tf.shape(batch[\"label\"])[0]\n",
203 | "\n",
204 | " # generate padded BERT inputs for all the text features\n",
205 | " batch[\"bert_inputs\"] = self.get_bert_inputs(batch, batch_size)\n",
206 | "\n",
207 | " label = batch.pop(\"label\")\n",
208 | " return batch, label"
209 | ]
210 | },
211 | {
212 | "cell_type": "markdown",
213 | "id": "20240ca5",
214 | "metadata": {},
215 | "source": [
216 | "## Dataset preparation"
217 | ]
218 | },
219 | {
220 | "cell_type": "code",
221 | "execution_count": null,
222 | "id": "2287f59f",
223 | "metadata": {},
224 | "outputs": [],
225 | "source": [
226 | "def get_dataset(\n",
227 | " split: str, batch_size: int, batch_preprocessor: Callable, shuffle: bool\n",
228 | "):\n",
229 | " \"\"\"Prepares tf.data.Dataset objects from TFRecords.\"\"\"\n",
230 | "\n",
231 | " ds = tf.data.Dataset.list_files(f\"{TFRECORDS_DIR}/{split}-*.tfrecord\")\n",
232 | " ds = ds.interleave(\n",
233 | " tf.data.TFRecordDataset, cycle_length=AUTO, num_parallel_calls=AUTO\n",
234 | " )\n",
235 | "\n",
236 | " ds = ds.prefetch(AUTO)\n",
237 | " ds = ds.map(\n",
238 | " read_example, num_parallel_calls=tf.data.AUTOTUNE, deterministic=False\n",
239 | " ).cache()\n",
240 | " if shuffle:\n",
241 | " ds = ds.shuffle(batch_size * 10)\n",
242 | " ds = ds.batch(batch_size)\n",
243 | " ds = ds.map(batch_preprocessor, num_parallel_calls=AUTO)\n",
244 | " return ds"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "id": "ab367d67",
250 | "metadata": {},
251 | "source": [
252 | "## Model building"
253 | ]
254 | },
255 | {
256 | "cell_type": "code",
257 | "execution_count": null,
258 | "id": "4a1a330a",
259 | "metadata": {},
260 | "outputs": [],
261 | "source": [
262 | "def genre_classifier(\n",
263 | " proj_dim: int,\n",
264 | " num_labels: int,\n",
265 | "):\n",
266 | " \"\"\"Creates a simple classification model.\"\"\"\n",
267 | " inputs = tf.keras.Input(shape=(BERT_DIM,), dtype=tf.float32, name=\"cmlm_embeddings\")\n",
268 | "\n",
269 | " projections = tf.keras.layers.Dense(proj_dim, activation=\"relu\")(inputs)\n",
270 | " probs = tf.keras.layers.Dense(num_labels, activation=\"softmax\")(projections)\n",
271 | " return tf.keras.Model(inputs=inputs, outputs=probs)"
272 | ]
273 | },
274 | {
275 | "cell_type": "markdown",
276 | "id": "d34d7cc9",
277 | "metadata": {},
278 | "source": [
279 | "## Training routine"
280 | ]
281 | },
282 | {
283 | "cell_type": "code",
284 | "execution_count": null,
285 | "id": "e39b1660",
286 | "metadata": {},
287 | "outputs": [],
288 | "source": [
289 | "class GenreModelTrainer(tf.keras.Model):\n",
290 | " \"\"\"Encapsulates the core model training logic.\"\"\"\n",
291 | "\n",
292 | " def __init__(self, proj_dim, num_labels, encoder_path, train_encoder=False):\n",
293 | " super(GenreModelTrainer, self).__init__()\n",
294 | " self.predictor = genre_classifier(proj_dim, num_labels)\n",
295 | " self.sentence_encoder = hub.KerasLayer(encoder_path)\n",
296 | " self.sentence_encoder.trainable = train_encoder\n",
297 | "\n",
298 | " def contiguous_group_average_vectors(self, vectors, groups):\n",
299 | " \"\"\"Works iff sum(groups) == len(vectors)\n",
300 | " Example:\n",
301 | " Inputs: vectors: A dense 2D tensor of shape = (13, 3)\n",
302 | " groups : A dense 1D tensor with values [2, 5, 1, 4, 1]\n",
303 | " indicating that there are 5 groups.\n",
304 | " Objective: Compute a 5x3 matrix where the first row\n",
305 | " is the average of the rows 0-1 of `vectors`,\n",
306 | " the second row is the average of rows 2-6 of\n",
307 | " vectors, the third row is the row 7 of vectors,\n",
308 | " the fourth row is the average of rows 8-11 of\n",
309 | " vectors and the fifth and final row is the row\n",
310 | " 12 of vectors.\n",
311 | " Logic: A selection mask matrix is generated\n",
312 | " mask = [[1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
313 | " [0. 0. 1. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0.]\n",
314 | " [0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n",
315 | " [0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 0.]\n",
316 | " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]\n",
317 | " This mask is then multiplied with `vectors` to get a\n",
318 | " matrix of shape (5, 3) called `summed_vectors` where\n",
319 | " each row contains the group sums.\n",
320 | " `summed_vectors` is then devided by `groups` to\n",
321 | " obtain the averages.\n",
322 | " \"\"\"\n",
323 | " groups = tf.expand_dims(tf.cast(groups, dtype=tf.int32), axis=1)\n",
324 | " group_cumsum = tf.cumsum(groups)\n",
325 | "\n",
326 | " mask = tf.repeat(\n",
327 | " tf.expand_dims(tf.range(tf.shape(vectors)[0]), axis=0),\n",
328 | " repeats=tf.shape(groups)[0],\n",
329 | " axis=0,\n",
330 | " )\n",
331 | " mask = tf.cast(mask < group_cumsum, dtype=tf.float32)\n",
332 | "\n",
333 | " def complete_mask(mask):\n",
334 | " neg_mask = tf.concat(\n",
335 | " (tf.expand_dims(tf.ones_like(mask[0]), axis=0), 1 - mask[:-1]), axis=0\n",
336 | " )\n",
337 | " return mask * neg_mask\n",
338 | "\n",
339 | " mask = tf.cond(\n",
340 | " tf.greater(tf.shape(groups)[0], 1),\n",
341 | " true_fn=lambda: complete_mask(mask),\n",
342 | " false_fn=lambda: mask,\n",
343 | " )\n",
344 | "\n",
345 | " summed_vectors = tf.matmul(mask, vectors)\n",
346 | " averaged_vectors = summed_vectors / tf.cast(groups, dtype=tf.float32)\n",
347 | "\n",
348 | " return averaged_vectors\n",
349 | "\n",
350 | " def compute_text_embeddings(self, features):\n",
351 | " embeddings = self.sentence_encoder(features[\"bert_inputs\"])[\"pooled_output\"]\n",
352 | " embeddings = self.contiguous_group_average_vectors(\n",
353 | " embeddings, features[\"summary_num_sentences\"]\n",
354 | " )\n",
355 | "\n",
356 | " return embeddings\n",
357 | "\n",
358 | " def train_step(self, batch):\n",
359 | " # Unpack the features and the labels.\n",
360 | " features, labels = batch\n",
361 | "\n",
362 | " # Compute embeddings for the text features.\n",
363 | " embeddings = self.compute_text_embeddings(features)\n",
364 | "\n",
365 | " # Main loop.\n",
366 | " with tf.GradientTape() as tape:\n",
367 | " predictions = self.predictor(embeddings, training=True)\n",
368 | " loss = self.compiled_loss(labels, predictions)\n",
369 | "\n",
370 | " # Compute gradients and update the parameters.\n",
371 | " learnable_params = self.predictor.trainable_variables\n",
372 | " gradients = tape.gradient(loss, learnable_params)\n",
373 | "\n",
374 | " # Apply the gradients to the parameters.\n",
375 | " self.optimizer.apply_gradients(zip(gradients, learnable_params))\n",
376 | "\n",
377 | " # Report progress.\n",
378 | " self.compiled_metrics.update_state(labels, predictions)\n",
379 | " return {m.name: m.result() for m in self.metrics}\n",
380 | "\n",
381 | " def test_step(self, batch):\n",
382 | " # Unpack the features and the labels.\n",
383 | " features, labels = batch\n",
384 | "\n",
385 | " # Get the predictions.\n",
386 | " predictions = self.call(features)\n",
387 | "\n",
388 | " # Report progress.\n",
389 | " self.compiled_loss(labels, predictions)\n",
390 | " self.compiled_metrics.update_state(labels, predictions)\n",
391 | " return {m.name: m.result() for m in self.metrics}\n",
392 | "\n",
393 | " def call(self, features):\n",
394 | " embeddings = self.compute_text_embeddings(features)\n",
395 | " return self.predictor(embeddings, training=False)\n",
396 | "\n",
397 | " def predict_step(self, data):\n",
398 | " return self.call(data)\n",
399 | "\n",
400 | " def save_weights(self, filepath, overwrite=True, save_format=None, options=None):\n",
401 | " self.predictor.save_weights(\n",
402 | " filepath, overwrite=overwrite, save_format=save_format, options=options\n",
403 | " )\n",
404 | "\n",
405 | " def load_weights(self, filepath, by_name=False, skip_mismatch=False, options=None):\n",
406 | " self.predictor.load_weights(\n",
407 | " filepath, by_name=by_name, skip_mismatch=skip_mismatch, options=options\n",
408 | " )"
409 | ]
410 | },
411 | {
412 | "cell_type": "code",
413 | "execution_count": null,
414 | "id": "d0d9e34e",
415 | "metadata": {},
416 | "outputs": [],
417 | "source": [
418 | "def train(\n",
419 | " train_ds: tf.data.Dataset,\n",
420 | " valid_ds: tf.data.Dataset,\n",
421 | " test_ds: tf.data.Dataset,\n",
422 | " num_epochs: int,\n",
423 | " run_name: str,\n",
424 | " group_name: str,\n",
425 | "):\n",
426 | " tfhub_model_uri = (\n",
427 | " \"https://tfhub.dev/google/universal-sentence-encoder-cmlm/en-base/1\"\n",
428 | " )\n",
429 | " proj_dim = 128\n",
430 | " num_labels = 27\n",
431 | "\n",
432 | " wandb.init(\n",
433 | " project=\"batching-experiments\",\n",
434 | " entity=\"carted\",\n",
435 | " name=run_name,\n",
436 | " group=group_name,\n",
437 | " )\n",
438 | "\n",
439 | " trainer = GenreModelTrainer(proj_dim, num_labels, tfhub_model_uri, False)\n",
440 | " trainer.compile(\n",
441 | " optimizer=\"adam\",\n",
442 | " loss=\"sparse_categorical_crossentropy\",\n",
443 | " metrics=\"accuracy\",\n",
444 | " run_eagerly=True\n",
445 | " )\n",
446 | " start = time.time()\n",
447 | " trainer.fit(\n",
448 | " train_ds,\n",
449 | " epochs=num_epochs,\n",
450 | " validation_data=valid_ds,\n",
451 | " callbacks=[wandb.keras.WandbCallback()],\n",
452 | " )\n",
453 | " end = time.time()\n",
454 | " wandb.log({\"model_training_time (seconds)\": end - start})\n",
455 | "\n",
456 | " loss, acc = trainer.evaluate(test_ds)\n",
457 | " wandb.log({\"test_loss\": loss})\n",
458 | " wandb.log({\"test_acc\": acc})\n",
459 | "\n",
460 | " wandb.finish()"
461 | ]
462 | },
463 | {
464 | "cell_type": "markdown",
465 | "id": "24ab9c7d",
466 | "metadata": {},
467 | "source": [
468 | "## Training with fixed batch length"
469 | ]
470 | },
471 | {
472 | "cell_type": "code",
473 | "execution_count": null,
474 | "id": "6da308ed",
475 | "metadata": {},
476 | "outputs": [],
477 | "source": [
478 | "# Find the longest sequence in the training set\n",
479 | "ds = tf.data.Dataset.list_files(f\"{TFRECORDS_DIR}/train-*.tfrecord\")\n",
480 | "ds = tf.data.TFRecordDataset(ds).map(read_example)\n",
481 | "max_seq_len = tf.cast(\n",
482 | " tf.reduce_max(\n",
483 | " [tf.reduce_max(datum[\"summary_sentence_lens\"].flat_values) for datum in ds]\n",
484 | " ),\n",
485 | " tf.int32,\n",
486 | ")\n",
487 | "print(f\"Longest token sequence in the training split: {max_seq_len.numpy()}\")"
488 | ]
489 | },
490 | {
491 | "cell_type": "code",
492 | "execution_count": null,
493 | "id": "41eacf86",
494 | "metadata": {},
495 | "outputs": [],
496 | "source": [
497 | "input_utility = ModelInputUtils(dynamic_batching=False, data_max_seq_len=max_seq_len)"
498 | ]
499 | },
500 | {
501 | "cell_type": "code",
502 | "execution_count": null,
503 | "id": "350ec5a7",
504 | "metadata": {},
505 | "outputs": [],
506 | "source": [
507 | "train_ds = get_dataset(\n",
508 | " split=\"train\",\n",
509 | " batch_size=BATCH_SIZE,\n",
510 | " batch_preprocessor=input_utility.preprocess_batch,\n",
511 | " shuffle=True,\n",
512 | ")\n",
513 | "valid_ds = get_dataset(\n",
514 | " split=\"val\",\n",
515 | " batch_size=BATCH_SIZE,\n",
516 | " batch_preprocessor=input_utility.preprocess_batch,\n",
517 | " shuffle=False,\n",
518 | ")\n",
519 | "test_ds = get_dataset(\n",
520 | " split=\"test\",\n",
521 | " batch_size=BATCH_SIZE,\n",
522 | " batch_preprocessor=input_utility.preprocess_batch,\n",
523 | " shuffle=False,\n",
524 | ")"
525 | ]
526 | },
527 | {
528 | "cell_type": "code",
529 | "execution_count": null,
530 | "id": "fedb0ac2",
531 | "metadata": {},
532 | "outputs": [],
533 | "source": [
534 | "group_name = \"split-sentences-fixed-length-batching\"\n",
535 | "\n",
536 | "for i in range(NUM_RUNS):\n",
537 | " run_name = f\"cmlm-fixed-length-run:{i + 1}\"\n",
538 | " train(train_ds, valid_ds, test_ds, NUM_EPOCHS, run_name, group_name)"
539 | ]
540 | },
541 | {
542 | "cell_type": "markdown",
543 | "id": "15867b5f",
544 | "metadata": {},
545 | "source": [
546 | "## Training with variable batch length"
547 | ]
548 | },
549 | {
550 | "cell_type": "code",
551 | "execution_count": null,
552 | "id": "da8ff8ab",
553 | "metadata": {},
554 | "outputs": [],
555 | "source": [
556 | "input_utility = ModelInputUtils(dynamic_batching=True)"
557 | ]
558 | },
559 | {
560 | "cell_type": "code",
561 | "execution_count": null,
562 | "id": "2588588e",
563 | "metadata": {},
564 | "outputs": [],
565 | "source": [
566 | "train_ds = get_dataset(\n",
567 | " split=\"train\",\n",
568 | " batch_size=BATCH_SIZE,\n",
569 | " batch_preprocessor=input_utility.preprocess_batch,\n",
570 | " shuffle=True,\n",
571 | ")\n",
572 | "valid_ds = get_dataset(\n",
573 | " split=\"val\",\n",
574 | " batch_size=BATCH_SIZE,\n",
575 | " batch_preprocessor=input_utility.preprocess_batch,\n",
576 | " shuffle=False,\n",
577 | ")\n",
578 | "test_ds = get_dataset(\n",
579 | " split=\"test\",\n",
580 | " batch_size=BATCH_SIZE,\n",
581 | " batch_preprocessor=input_utility.preprocess_batch,\n",
582 | " shuffle=False,\n",
583 | ")"
584 | ]
585 | },
586 | {
587 | "cell_type": "code",
588 | "execution_count": null,
589 | "id": "57e79a0c",
590 | "metadata": {},
591 | "outputs": [],
592 | "source": [
593 | "group_name = \"split-sentences-variable-length-batching\"\n",
594 | "\n",
595 | "for i in range(NUM_RUNS):\n",
596 | " run_name = f\"cmlm-variable-length-run:{i + 1}\"\n",
597 | " train(train_ds, valid_ds, test_ds, NUM_EPOCHS, run_name, group_name)"
598 | ]
599 | }
600 | ],
601 | "metadata": {
602 | "environment": {
603 | "kernel": "conda-env-var-len-text-py",
604 | "name": "tf2-gpu.2-6.m84",
605 | "type": "gcloud",
606 | "uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-6:m84"
607 | },
608 | "interpreter": {
609 | "hash": "20d99275fbeb957608cf5adaee64ff23d07ebc4078dd173ca4cbf341a3a79b45"
610 | },
611 | "kernelspec": {
612 | "display_name": "Python 3 (ipykernel)",
613 | "language": "python",
614 | "name": "python3"
615 | },
616 | "language_info": {
617 | "codemirror_mode": {
618 | "name": "ipython",
619 | "version": 3
620 | },
621 | "file_extension": ".py",
622 | "mimetype": "text/x-python",
623 | "name": "python",
624 | "nbconvert_exporter": "python",
625 | "pygments_lexer": "ipython3",
626 | "version": "3.8.2"
627 | }
628 | },
629 | "nbformat": 4,
630 | "nbformat_minor": 5
631 | }
632 |
--------------------------------------------------------------------------------
/bert/train-vanilla-bert.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "dc92a22e",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "f943bf42",
26 | "metadata": {},
27 | "source": [
28 | "## Imports"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": 1,
34 | "id": "9014279e",
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "from typing import Callable, List, Dict\n",
39 | "import tensorflow_hub as hub\n",
40 | "import tensorflow_text\n",
41 | "import tensorflow as tf\n",
42 | "import wandb\n",
43 | "\n",
44 | "import numpy as np\n",
45 | "import random\n",
46 | "import time\n",
47 | "\n",
48 | "SEED = 42\n",
49 | "tf.random.set_seed(SEED)\n",
50 | "np.random.seed(SEED)\n",
51 | "random.seed(SEED)"
52 | ]
53 | },
54 | {
55 | "cell_type": "markdown",
56 | "id": "44377fcf",
57 | "metadata": {},
58 | "source": [
59 | "## Contants"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": 2,
65 | "id": "3d42dd4b",
66 | "metadata": {},
67 | "outputs": [],
68 | "source": [
69 | "TFRECORDS_DIR = \"tfrecords\"\n",
70 | "BERT_MAX_SEQLEN = 512\n",
71 | "BATCH_SIZE = 64\n",
72 | "AUTO = tf.data.AUTOTUNE"
73 | ]
74 | },
75 | {
76 | "cell_type": "markdown",
77 | "id": "9126bde2",
78 | "metadata": {},
79 | "source": [
80 | "## TFRecord parsing utilities"
81 | ]
82 | },
83 | {
84 | "cell_type": "code",
85 | "execution_count": 7,
86 | "id": "4a40156c",
87 | "metadata": {},
88 | "outputs": [],
89 | "source": [
90 | "feature_descriptions = {\n",
91 | " \"summary\": tf.io.FixedLenFeature([], dtype=tf.string),\n",
92 | " \"summary_tokens\": tf.io.RaggedFeature(\n",
93 | " value_key=\"summary_tokens_values\",\n",
94 | " dtype=tf.int64,\n",
95 | " partitions=[\n",
96 | " tf.io.RaggedFeature.RowSplits(\"summary_tokens_splits_0\"),\n",
97 | " tf.io.RaggedFeature.RowSplits(\"summary_tokens_splits_1\"),\n",
98 | " ],\n",
99 | " ),\n",
100 | " \"summary_tokens_len\": tf.io.FixedLenFeature([1], dtype=tf.int64),\n",
101 | " \"label\": tf.io.FixedLenFeature([1], dtype=tf.int64),\n",
102 | "}"
103 | ]
104 | },
105 | {
106 | "cell_type": "code",
107 | "execution_count": 4,
108 | "id": "47a5de49",
109 | "metadata": {},
110 | "outputs": [],
111 | "source": [
112 | "def read_example(example):\n",
113 | " \"\"\"Parses a single TFRecord file.\"\"\"\n",
114 | " features = tf.io.parse_single_example(example, feature_descriptions)\n",
115 | " features[\"summary_tokens\"] = tf.cast(\n",
116 | " features[\"summary_tokens\"].with_row_splits_dtype(tf.int64), tf.int32\n",
117 | " )\n",
118 | " return features"
119 | ]
120 | },
121 | {
122 | "cell_type": "markdown",
123 | "id": "f73d2384",
124 | "metadata": {},
125 | "source": [
126 | "## Preprocessing function for fixed length batching."
127 | ]
128 | },
129 | {
130 | "cell_type": "code",
131 | "execution_count": 17,
132 | "id": "474df024",
133 | "metadata": {},
134 | "outputs": [
135 | {
136 | "name": "stdout",
137 | "output_type": "stream",
138 | "text": [
139 | "Longest token sequence in the training split: 2947\n"
140 | ]
141 | }
142 | ],
143 | "source": [
144 | "# Find the longest sequence in the training set\n",
145 | "ds = tf.data.Dataset.list_files(f\"{TFRECORDS_DIR}/train-*.tfrecord\")\n",
146 | "ds = tf.data.TFRecordDataset(ds).map(read_example)\n",
147 | "max_seq_len = tf.cast(\n",
148 | " tf.reduce_max([datum[\"summary_tokens_len\"] for datum in ds]), tf.int32\n",
149 | ")\n",
150 | "print(f\"Longest token sequence in the training split: {max_seq_len.numpy()}\")"
151 | ]
152 | },
153 | {
154 | "cell_type": "code",
155 | "execution_count": 9,
156 | "id": "f067d305",
157 | "metadata": {},
158 | "outputs": [],
159 | "source": [
160 | "preprocessor = hub.load(\n",
161 | " \"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\"\n",
162 | ")\n",
163 | "fixed_len_bert_packer = hub.KerasLayer(\n",
164 | " preprocessor.bert_pack_inputs,\n",
165 | " arguments={\"seq_length\": tf.minimum(max_seq_len + 2, BERT_MAX_SEQLEN)},\n",
166 | ")"
167 | ]
168 | },
169 | {
170 | "cell_type": "markdown",
171 | "id": "37448903",
172 | "metadata": {},
173 | "source": [
174 | "#### Note: We add 2 to the maximum length to account for the CLS and SEP tokens that would be added later by the encoder"
175 | ]
176 | },
177 | {
178 | "cell_type": "code",
179 | "execution_count": 10,
180 | "id": "6be99af7",
181 | "metadata": {},
182 | "outputs": [],
183 | "source": [
184 | "def preprocess_fixed_batch(batch):\n",
185 | " \"\"\"Batch processing utility.\"\"\"\n",
186 | "\n",
187 | " # Generating the inputs for the BERT model.\n",
188 | " bert_packed_text = fixed_len_bert_packer(\n",
189 | " [tf.squeeze(batch.pop(\"summary_tokens\"), axis=1)]\n",
190 | " )\n",
191 | "\n",
192 | " labels = batch.pop(\"label\")\n",
193 | " return bert_packed_text, labels"
194 | ]
195 | },
196 | {
197 | "cell_type": "markdown",
198 | "id": "94fa686e",
199 | "metadata": {},
200 | "source": [
201 | "## Preprocessing function for variable length batching using the BERT packer from TF Hub."
202 | ]
203 | },
204 | {
205 | "cell_type": "code",
206 | "execution_count": 11,
207 | "id": "74f3ed5f",
208 | "metadata": {},
209 | "outputs": [],
210 | "source": [
211 | "def set_text_preprocessor(preprocessor_path: str) -> Callable:\n",
212 | " \"\"\"Decorator to set the desired preprocessor for a\n",
213 | " function from a TensorFlow Hub URL.\n",
214 | "\n",
215 | " Arguments:\n",
216 | " preprocessor_path {str} -- URL of the TF-Hub preprocessor.\n",
217 | "\n",
218 | " Returns:\n",
219 | " Callable -- A function with the `preprocessor` attribute set.\n",
220 | " \"\"\"\n",
221 | "\n",
222 | " def decoration(func: Callable):\n",
223 | " # Loading the preprocessor from TF-Hub\n",
224 | " preprocessor = hub.load(preprocessor_path)\n",
225 | "\n",
226 | " # Setting an attribute called `preprocessor` to\n",
227 | " # the passed function\n",
228 | " func.preprocessor = preprocessor\n",
229 | " return func\n",
230 | "\n",
231 | " return decoration"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": 12,
237 | "id": "6a4379e1",
238 | "metadata": {},
239 | "outputs": [],
240 | "source": [
241 | "@set_text_preprocessor(\n",
242 | " preprocessor_path=\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\"\n",
243 | ")\n",
244 | "def preprocess_variable_batch_tfh(batch):\n",
245 | " \"\"\"Batch processing utility.\"\"\"\n",
246 | " text_tokens_max_len = tf.cast(\n",
247 | " tf.math.reduce_max(batch[\"summary_tokens_len\"]),\n",
248 | " dtype=tf.int32,\n",
249 | " )\n",
250 | "\n",
251 | " # Generating the inputs for the BERT model.\n",
252 | " bert_input_packer = hub.KerasLayer(\n",
253 | " preprocess_variable_batch_tfh.preprocessor.bert_pack_inputs,\n",
254 | " arguments={\"seq_length\": tf.minimum(text_tokens_max_len + 2, BERT_MAX_SEQLEN)},\n",
255 | " )\n",
256 | " bert_packed_text = bert_input_packer(\n",
257 | " [tf.squeeze(batch.pop(\"summary_tokens\"), axis=1)]\n",
258 | " )\n",
259 | "\n",
260 | " labels = batch.pop(\"label\")\n",
261 | " return bert_packed_text, labels"
262 | ]
263 | },
264 | {
265 | "cell_type": "markdown",
266 | "id": "bcb54e58",
267 | "metadata": {},
268 | "source": [
269 | "## Preprocessing function for variable length batching using a custom written BERT packer."
270 | ]
271 | },
272 | {
273 | "cell_type": "code",
274 | "execution_count": 13,
275 | "id": "b71aa7a7",
276 | "metadata": {},
277 | "outputs": [],
278 | "source": [
279 | "def prepare_bert_inputs(\n",
280 | " batch_tokens: tf.RaggedTensor,\n",
281 | " batch_lens: tf.Tensor,\n",
282 | " max_len: int = tf.constant(512),\n",
283 | ") -> Dict[str, tf.Tensor]:\n",
284 | " \"\"\"Pack the tokens w.r.t BERT inputs.\"\"\"\n",
285 | "\n",
286 | " # Remove the last ragged dimension\n",
287 | " batch_tokens = tf.RaggedTensor.from_row_lengths(\n",
288 | " batch_tokens.flat_values, batch_lens\n",
289 | " )\n",
290 | "\n",
291 | " # Calcuate batch size.\n",
292 | " batch_size = tf.shape(batch_lens)[0]\n",
293 | "\n",
294 | " # Define special token values (very specific to BERT).\n",
295 | " CLS = 101\n",
296 | " SEP = 102\n",
297 | " PAD = 0\n",
298 | "\n",
299 | " # Prepare the special tokens for concatenation.\n",
300 | " batch_cls = tf.repeat(tf.constant([[CLS]]), batch_size, axis=0)\n",
301 | " batch_cls = tf.RaggedTensor.from_tensor(batch_cls).with_row_splits_dtype(\n",
302 | " batch_tokens.row_splits.dtype\n",
303 | " )\n",
304 | " batch_sep = tf.repeat(tf.constant([[SEP]]), batch_size, axis=0)\n",
305 | " batch_sep = tf.RaggedTensor.from_tensor(batch_sep).with_row_splits_dtype(\n",
306 | " batch_tokens.row_splits.dtype\n",
307 | " )\n",
308 | "\n",
309 | " # Truncate the sequences that are shorter than max_len.\n",
310 | " max_batch_len = tf.minimum(tf.reduce_max(batch_lens) + 2, max_len)\n",
311 | " truncated_tokens = batch_tokens[:, : max_batch_len - 2]\n",
312 | "\n",
313 | " # Sandwich the truncated tokens in between the special tokens.\n",
314 | " prepared_tokens = tf.concat([batch_cls, truncated_tokens, batch_sep], axis=1)\n",
315 | "\n",
316 | " # Convert the tokens to a regular int32 tensor and pad the\n",
317 | " # shorter sequences with PAD.\n",
318 | " padded_tokens = prepared_tokens.to_tensor(PAD)\n",
319 | "\n",
320 | " # Create the segment id tensor.\n",
321 | " segment_ids = tf.zeros_like(padded_tokens)\n",
322 | "\n",
323 | " # Create the input mask\n",
324 | " mask = tf.sequence_mask(batch_lens + 2, max_batch_len, dtype=tf.int32)\n",
325 | "\n",
326 | " ret = {\n",
327 | " \"input_word_ids\": padded_tokens,\n",
328 | " \"input_type_ids\": segment_ids,\n",
329 | " \"input_mask\": mask,\n",
330 | " }\n",
331 | " return ret"
332 | ]
333 | },
334 | {
335 | "cell_type": "code",
336 | "execution_count": 14,
337 | "id": "5c39c36c",
338 | "metadata": {},
339 | "outputs": [],
340 | "source": [
341 | "def preprocess_variable_batch_cust(batch):\n",
342 | " \"\"\"Batch processing utility.\"\"\"\n",
343 | " text_token_lens = tf.cast(batch[\"summary_tokens_len\"], dtype=tf.int32)\n",
344 | "\n",
345 | " # Generating the inputs for the BERT model.\n",
346 | " bert_packed_text = prepare_bert_inputs(\n",
347 | " tf.squeeze(batch[\"summary_tokens\"], axis=1), tf.reshape(text_token_lens, (-1,))\n",
348 | " )\n",
349 | " labels = batch.pop(\"label\")\n",
350 | " return bert_packed_text, labels"
351 | ]
352 | },
353 | {
354 | "cell_type": "markdown",
355 | "id": "20240ca5",
356 | "metadata": {},
357 | "source": [
358 | "## Dataset preparation"
359 | ]
360 | },
361 | {
362 | "cell_type": "code",
363 | "execution_count": 15,
364 | "id": "2287f59f",
365 | "metadata": {},
366 | "outputs": [],
367 | "source": [
368 | "def get_dataset(\n",
369 | " split: str, batch_size: int, batch_preprocessor: Callable, shuffle: bool\n",
370 | "):\n",
371 | " \"\"\"Prepares tf.data.Dataset objects from TFRecords.\"\"\"\n",
372 | " ds = tf.data.Dataset.list_files(f\"{TFRECORDS_DIR}/{split}-*.tfrecord\")\n",
373 | " ds = (\n",
374 | " ds.interleave(\n",
375 | " tf.data.TFRecordDataset,\n",
376 | " cycle_length=AUTO,\n",
377 | " num_parallel_calls=AUTO,\n",
378 | " )\n",
379 | " .map(read_example, num_parallel_calls=AUTO, deterministic=False)\n",
380 | " .cache()\n",
381 | " )\n",
382 | " if shuffle:\n",
383 | " ds = ds.shuffle(batch_size * 10)\n",
384 | " ds = (\n",
385 | " ds.batch(batch_size)\n",
386 | " .map(batch_preprocessor, num_parallel_calls=AUTO)\n",
387 | " .prefetch(AUTO)\n",
388 | " )\n",
389 | " return ds"
390 | ]
391 | },
392 | {
393 | "cell_type": "markdown",
394 | "id": "4e2aca18",
395 | "metadata": {},
396 | "source": [
397 | "## Model Building"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": 16,
403 | "id": "816f420b",
404 | "metadata": {},
405 | "outputs": [],
406 | "source": [
407 | "def genre_classifier(\n",
408 | " encoder_path: str,\n",
409 | " input_features: List[str],\n",
410 | " train_encoder: bool,\n",
411 | " proj_dim: int,\n",
412 | " num_labels: int,\n",
413 | "):\n",
414 | " \"\"\"Creates a simple classification model.\"\"\"\n",
415 | " text_encoder = hub.KerasLayer(encoder_path)\n",
416 | " text_encoder.trainable = train_encoder\n",
417 | "\n",
418 | " inputs = {\n",
419 | " feature_name: tf.keras.Input(shape=(None,), dtype=tf.int32, name=feature_name)\n",
420 | " for feature_name in input_features\n",
421 | " }\n",
422 | "\n",
423 | " text_encodings = text_encoder(inputs)\n",
424 | " projections = tf.keras.layers.Dense(proj_dim, activation=\"relu\")(\n",
425 | " text_encodings[\"pooled_output\"]\n",
426 | " )\n",
427 | " probs = tf.keras.layers.Dense(num_labels, activation=\"softmax\")(projections)\n",
428 | " return tf.keras.Model(inputs=inputs, outputs=probs)"
429 | ]
430 | },
431 | {
432 | "cell_type": "markdown",
433 | "id": "dbc4f9d1",
434 | "metadata": {},
435 | "source": [
436 | "## Training routine"
437 | ]
438 | },
439 | {
440 | "cell_type": "code",
441 | "execution_count": null,
442 | "id": "6b5831bb",
443 | "metadata": {},
444 | "outputs": [],
445 | "source": [
446 | "def train(\n",
447 | " train_ds: tf.data.Dataset,\n",
448 | " valid_ds: tf.data.Dataset,\n",
449 | " test_ds: tf.data.Dataset,\n",
450 | " num_epochs: int,\n",
451 | " run_name: str,\n",
452 | " group_name: str,\n",
453 | "):\n",
454 | " tfhub_model_uri = \"https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4\"\n",
455 | " bert_inputs = [\"input_word_ids\", \"input_type_ids\", \"input_mask\"]\n",
456 | " proj_dim = 128\n",
457 | " num_labels = 27\n",
458 | "\n",
459 | " wandb.init(\n",
460 | " project=\"batching-experiments\",\n",
461 | " entity=\"carted\",\n",
462 | " name=run_name,\n",
463 | " group=group_name,\n",
464 | " )\n",
465 | "\n",
466 | " model = genre_classifier(tfhub_model_uri, bert_inputs, False, proj_dim, num_labels)\n",
467 | " model.compile(\n",
468 | " optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=\"accuracy\"\n",
469 | " )\n",
470 | " start = time.time()\n",
471 | " model.fit(\n",
472 | " train_ds,\n",
473 | " epochs=num_epochs,\n",
474 | " validation_data=valid_ds,\n",
475 | " callbacks=[wandb.keras.WandbCallback()],\n",
476 | " )\n",
477 | " end = time.time()\n",
478 | " wandb.log({\"model_training_time (seconds)\": end - start})\n",
479 | "\n",
480 | " loss, acc = model.evaluate(test_ds)\n",
481 | " wandb.log({\"test_loss\": loss})\n",
482 | " wandb.log({\"test_acc\": acc})\n",
483 | "\n",
484 | " wandb.finish()"
485 | ]
486 | },
487 | {
488 | "cell_type": "markdown",
489 | "id": "ae1a95b2",
490 | "metadata": {},
491 | "source": [
492 | "## Experiment parameters"
493 | ]
494 | },
495 | {
496 | "cell_type": "code",
497 | "execution_count": null,
498 | "id": "590de87d",
499 | "metadata": {},
500 | "outputs": [],
501 | "source": [
502 | "NUM_RUNS = 10\n",
503 | "NUM_EPOCHS = 5"
504 | ]
505 | },
506 | {
507 | "cell_type": "markdown",
508 | "id": "5efb5d2b-4ff7-41ae-bdba-6559623d4b47",
509 | "metadata": {},
510 | "source": [
511 | "## Training with fixed batch length"
512 | ]
513 | },
514 | {
515 | "cell_type": "code",
516 | "execution_count": null,
517 | "id": "04d9ffd9-6446-4987-ac52-2c33a157238f",
518 | "metadata": {},
519 | "outputs": [],
520 | "source": [
521 | "train_ds = get_dataset(\"train\", BATCH_SIZE, preprocess_fixed_batch, True)\n",
522 | "valid_ds = get_dataset(\"val\", BATCH_SIZE, preprocess_fixed_batch, False)\n",
523 | "test_ds = get_dataset(\"test\", BATCH_SIZE, preprocess_fixed_batch, False)"
524 | ]
525 | },
526 | {
527 | "cell_type": "code",
528 | "execution_count": null,
529 | "id": "5d624092-1341-43f6-ab16-48642473bc32",
530 | "metadata": {},
531 | "outputs": [],
532 | "source": [
533 | "group_name = \"fixed-length-batching\"\n",
534 | "\n",
535 | "for i in range(NUM_RUNS):\n",
536 | " run_name = f\"fixed-length-run:{i + 1}\"\n",
537 | " train(train_ds, valid_ds, test_ds, NUM_EPOCHS, run_name, group_name)"
538 | ]
539 | },
540 | {
541 | "cell_type": "markdown",
542 | "id": "79bcc099-fd26-4167-b4f5-2200bda269e3",
543 | "metadata": {},
544 | "source": [
545 | "## Training with variable batch length"
546 | ]
547 | },
548 | {
549 | "cell_type": "markdown",
550 | "id": "79b251cd",
551 | "metadata": {},
552 | "source": [
553 | "### Using TF Hub's BERT packer"
554 | ]
555 | },
556 | {
557 | "cell_type": "code",
558 | "execution_count": null,
559 | "id": "e2a87002-e162-4e05-ad96-4b5af895f68a",
560 | "metadata": {},
561 | "outputs": [],
562 | "source": [
563 | "train_ds = get_dataset(\"train\", BATCH_SIZE, preprocess_variable_batch_tfh, True)\n",
564 | "valid_ds = get_dataset(\"val\", BATCH_SIZE, preprocess_variable_batch_tfh, False)\n",
565 | "test_ds = get_dataset(\"test\", BATCH_SIZE, preprocess_variable_batch_tfh, False)"
566 | ]
567 | },
568 | {
569 | "cell_type": "code",
570 | "execution_count": null,
571 | "id": "89894dea-1e54-4fb1-b377-1387c1196ca9",
572 | "metadata": {},
573 | "outputs": [],
574 | "source": [
575 | "group_name = \"variable-length-batching-tfh\"\n",
576 | "\n",
577 | "for i in range(NUM_RUNS):\n",
578 | " run_name = f\"variable-length-run-tfh:{i + 1}\"\n",
579 | " train(train_ds, valid_ds, test_ds, NUM_EPOCHS, run_name, group_name)"
580 | ]
581 | },
582 | {
583 | "cell_type": "markdown",
584 | "id": "db6cb256",
585 | "metadata": {},
586 | "source": [
587 | "### Using custom BERT packer"
588 | ]
589 | },
590 | {
591 | "cell_type": "code",
592 | "execution_count": null,
593 | "id": "51d23cfa",
594 | "metadata": {},
595 | "outputs": [],
596 | "source": [
597 | "train_ds = get_dataset(\"train\", BATCH_SIZE, preprocess_variable_batch_cust, True)\n",
598 | "valid_ds = get_dataset(\"val\", BATCH_SIZE, preprocess_variable_batch_cust, False)\n",
599 | "test_ds = get_dataset(\"test\", BATCH_SIZE, preprocess_variable_batch_cust, False)"
600 | ]
601 | },
602 | {
603 | "cell_type": "code",
604 | "execution_count": null,
605 | "id": "38f27946",
606 | "metadata": {},
607 | "outputs": [],
608 | "source": [
609 | "group_name = \"variable-length-batching-cust\"\n",
610 | "\n",
611 | "for i in range(NUM_RUNS):\n",
612 | " run_name = f\"variable-length-run-cust:{i + 1}\"\n",
613 | " train(train_ds, valid_ds, test_ds, NUM_EPOCHS, run_name, group_name)"
614 | ]
615 | }
616 | ],
617 | "metadata": {
618 | "environment": {
619 | "kernel": "python3",
620 | "name": "tf2-gpu.2-6.m84",
621 | "type": "gcloud",
622 | "uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-6:m84"
623 | },
624 | "interpreter": {
625 | "hash": "20d99275fbeb957608cf5adaee64ff23d07ebc4078dd173ca4cbf341a3a79b45"
626 | },
627 | "kernelspec": {
628 | "display_name": "Python 3 (ipykernel)",
629 | "language": "python",
630 | "name": "python3"
631 | },
632 | "language_info": {
633 | "codemirror_mode": {
634 | "name": "ipython",
635 | "version": 3
636 | },
637 | "file_extension": ".py",
638 | "mimetype": "text/x-python",
639 | "name": "python",
640 | "nbconvert_exporter": "python",
641 | "pygments_lexer": "ipython3",
642 | "version": "3.8.2"
643 | }
644 | },
645 | "nbformat": 4,
646 | "nbformat_minor": 5
647 | }
648 |
--------------------------------------------------------------------------------
/bigram-tfidf-shallow-mlp.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "8e49e081",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "7fe6f857",
26 | "metadata": {},
27 | "source": [
28 | "## Training a Shallow Text Classifier with TFIDF Preprocessing"
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "id": "a68e9e42",
34 | "metadata": {},
35 | "source": [
36 | ""
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "id": "775707b1",
49 | "metadata": {
50 | "id": "775707b1"
51 | },
52 | "source": [
53 | "## Setup"
54 | ]
55 | },
56 | {
57 | "cell_type": "code",
58 | "execution_count": 1,
59 | "id": "bbf62c31",
60 | "metadata": {
61 | "colab": {
62 | "base_uri": "https://localhost:8080/"
63 | },
64 | "id": "bbf62c31",
65 | "outputId": "510773bd-f630-42d2-ea44-d0f260096944"
66 | },
67 | "outputs": [
68 | {
69 | "name": "stdout",
70 | "output_type": "stream",
71 | "text": [
72 | "Downloading...\n",
73 | "From: https://drive.google.com/uc?id=1CvkRnGC8b_-n1NcbwcwxcIq7SusmDMb5\n",
74 | "To: /content/train_data.txt\n",
75 | "100% 35.4M/35.4M [00:00<00:00, 165MB/s] \n",
76 | "Downloading...\n",
77 | "From: https://drive.google.com/uc?id=1h1evGF5NVi2p8RoWxl8xhpOod0ZN_-ky\n",
78 | "To: /content/test_data_solution.txt\n",
79 | "100% 35.4M/35.4M [00:00<00:00, 165MB/s] \n"
80 | ]
81 | }
82 | ],
83 | "source": [
84 | "!gdown --id 1CvkRnGC8b_-n1NcbwcwxcIq7SusmDMb5 -O train_data.txt\n",
85 | "!gdown --id 1h1evGF5NVi2p8RoWxl8xhpOod0ZN_-ky -O test_data_solution.txt "
86 | ]
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": 1,
91 | "id": "9010888d",
92 | "metadata": {
93 | "id": "9010888d"
94 | },
95 | "outputs": [],
96 | "source": [
97 | "from tensorflow import keras\n",
98 | "import tensorflow as tf\n",
99 | "\n",
100 | "from sklearn.model_selection import train_test_split\n",
101 | "import pandas as pd\n",
102 | "import numpy as np\n",
103 | "import random\n",
104 | "import tqdm\n",
105 | "\n",
106 | "SEED = 42\n",
107 | "tf.random.set_seed(SEED)\n",
108 | "np.random.seed(SEED)\n",
109 | "random.seed(SEED)"
110 | ]
111 | },
112 | {
113 | "cell_type": "markdown",
114 | "id": "718dc6e4",
115 | "metadata": {
116 | "id": "718dc6e4"
117 | },
118 | "source": [
119 | "## Data loading"
120 | ]
121 | },
122 | {
123 | "cell_type": "code",
124 | "execution_count": 2,
125 | "id": "10f48e4f",
126 | "metadata": {
127 | "id": "10f48e4f"
128 | },
129 | "outputs": [],
130 | "source": [
131 | "train_df = pd.read_csv(\n",
132 | " \"train_data.txt\",\n",
133 | " engine=\"python\",\n",
134 | " sep=\" ::: \",\n",
135 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
136 | ")\n",
137 | "\n",
138 | "test_df = pd.read_csv(\n",
139 | " \"test_data_solution.txt\",\n",
140 | " engine=\"python\",\n",
141 | " sep=\" ::: \",\n",
142 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
143 | ")"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "id": "b51a143a",
149 | "metadata": {
150 | "id": "b51a143a"
151 | },
152 | "source": [
153 | "## Data splitting"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "execution_count": 3,
159 | "id": "e10abec9",
160 | "metadata": {
161 | "colab": {
162 | "base_uri": "https://localhost:8080/"
163 | },
164 | "id": "e10abec9",
165 | "outputId": "9309a99d-5da6-466c-e1cb-e987e57a867f"
166 | },
167 | "outputs": [
168 | {
169 | "name": "stdout",
170 | "output_type": "stream",
171 | "text": [
172 | "Number of training samples: 48792.\n",
173 | "Number of validation samples: 5422.\n",
174 | "Number of test examples: 54200.\n"
175 | ]
176 | }
177 | ],
178 | "source": [
179 | "# Split the data using train_test_split from sklearn\n",
180 | "train_shuffled = train_df.sample(frac=1)\n",
181 | "train_df_new, val_df = train_test_split(train_shuffled, test_size=0.1)\n",
182 | "\n",
183 | "print(f\"Number of training samples: {len(train_df_new)}.\")\n",
184 | "print(f\"Number of validation samples: {len(val_df)}.\")\n",
185 | "print(f\"Number of test examples: {len(test_df)}.\")"
186 | ]
187 | },
188 | {
189 | "cell_type": "markdown",
190 | "id": "0d2f49e2",
191 | "metadata": {
192 | "id": "0d2f49e2"
193 | },
194 | "source": [
195 | "## Data preprocessing"
196 | ]
197 | },
198 | {
199 | "cell_type": "code",
200 | "execution_count": 4,
201 | "id": "BC9z4bNaCmMb",
202 | "metadata": {
203 | "colab": {
204 | "base_uri": "https://localhost:8080/"
205 | },
206 | "id": "BC9z4bNaCmMb",
207 | "outputId": "c4d3a066-b007-42d0-ca52-dda1dc12ae7b"
208 | },
209 | "outputs": [
210 | {
211 | "data": {
212 | "text/plain": [
213 | "1829"
214 | ]
215 | },
216 | "execution_count": 4,
217 | "metadata": {},
218 | "output_type": "execute_result"
219 | }
220 | ],
221 | "source": [
222 | "train_df_new[\"total_words\"] = train_df_new[\"summary\"].apply(lambda x: len(x.split()))\n",
223 | "max_seqlen = train_df_new[\"total_words\"].max()\n",
224 | "max_seqlen"
225 | ]
226 | },
227 | {
228 | "cell_type": "code",
229 | "execution_count": 5,
230 | "id": "583d5ba9",
231 | "metadata": {
232 | "colab": {
233 | "base_uri": "https://localhost:8080/"
234 | },
235 | "id": "583d5ba9",
236 | "outputId": "7d07fb54-c6a2-46c7-f951-402b0047da1d"
237 | },
238 | "outputs": [
239 | {
240 | "data": {
241 | "text/plain": [
242 | "['[UNK]',\n",
243 | " 'short',\n",
244 | " 'sci-fi',\n",
245 | " 'documentary',\n",
246 | " 'drama',\n",
247 | " 'thriller',\n",
248 | " 'comedy',\n",
249 | " 'adult',\n",
250 | " 'romance',\n",
251 | " 'adventure',\n",
252 | " 'western',\n",
253 | " 'family',\n",
254 | " 'talk-show',\n",
255 | " 'news',\n",
256 | " 'horror',\n",
257 | " 'history',\n",
258 | " 'music',\n",
259 | " 'sport',\n",
260 | " 'war',\n",
261 | " 'animation',\n",
262 | " 'game-show',\n",
263 | " 'action',\n",
264 | " 'crime',\n",
265 | " 'reality-tv',\n",
266 | " 'mystery',\n",
267 | " 'musical',\n",
268 | " 'fantasy',\n",
269 | " 'biography']"
270 | ]
271 | },
272 | "execution_count": 5,
273 | "metadata": {},
274 | "output_type": "execute_result"
275 | }
276 | ],
277 | "source": [
278 | "text_vectorizer = keras.layers.TextVectorization(max_tokens=max_seqlen, ngrams=2, output_mode=\"tf_idf\")\n",
279 | "with tf.device(\"/CPU:0\"):\n",
280 | " text_vectorizer.adapt(train_df_new[\"summary\"])\n",
281 | "\n",
282 | "label_encoder = keras.layers.StringLookup(vocabulary=train_df_new[\"genre\"].unique())\n",
283 | "label_encoder.get_vocabulary()"
284 | ]
285 | },
286 | {
287 | "cell_type": "code",
288 | "execution_count": 6,
289 | "id": "66ca175b",
290 | "metadata": {
291 | "id": "66ca175b"
292 | },
293 | "outputs": [],
294 | "source": [
295 | "batch_size = 64\n",
296 | "auto = tf.data.AUTOTUNE\n",
297 | "\n",
298 | "\n",
299 | "def prepare_dataset(dataframe):\n",
300 | " dataset = tf.data.Dataset.from_tensor_slices(\n",
301 | " (dataframe[\"summary\"], dataframe[\"genre\"])\n",
302 | " )\n",
303 | " dataset = dataset.batch(batch_size)\n",
304 | " dataset = dataset.map(\n",
305 | " lambda summaries, genres: (text_vectorizer(summaries), label_encoder(genres)),\n",
306 | " num_parallel_calls=auto,\n",
307 | " ).cache()\n",
308 | " return dataset.prefetch(auto)"
309 | ]
310 | },
311 | {
312 | "cell_type": "code",
313 | "execution_count": 7,
314 | "id": "6528c33a",
315 | "metadata": {
316 | "colab": {
317 | "base_uri": "https://localhost:8080/"
318 | },
319 | "id": "6528c33a",
320 | "outputId": "94898329-cfd8-408d-badf-8d724fd8d0ea"
321 | },
322 | "outputs": [
323 | {
324 | "name": "stdout",
325 | "output_type": "stream",
326 | "text": [
327 | "(64, 1829) (64,)\n"
328 | ]
329 | }
330 | ],
331 | "source": [
332 | "training_dataset = prepare_dataset(train_df_new)\n",
333 | "validation_dataset = prepare_dataset(val_df)\n",
334 | "test_dataset = prepare_dataset(test_df)\n",
335 | "\n",
336 | "\n",
337 | "for sequences, labels in training_dataset.take(1):\n",
338 | " print(sequences.shape, labels.shape)"
339 | ]
340 | },
341 | {
342 | "cell_type": "markdown",
343 | "id": "zgLE_iKQAd7C",
344 | "metadata": {
345 | "id": "zgLE_iKQAd7C"
346 | },
347 | "source": [
348 | "## Model utilities"
349 | ]
350 | },
351 | {
352 | "cell_type": "code",
353 | "execution_count": 8,
354 | "id": "869d3da1",
355 | "metadata": {
356 | "id": "869d3da1"
357 | },
358 | "outputs": [],
359 | "source": [
360 | "def make_model():\n",
361 | " shallow_mlp_model = keras.Sequential(\n",
362 | " [\n",
363 | " keras.layers.Dense(512, activation=\"relu\"),\n",
364 | " keras.layers.Dense(256, activation=\"relu\"),\n",
365 | " keras.layers.Dense(label_encoder.vocabulary_size(), activation=\"softmax\"),\n",
366 | " ]\n",
367 | " )\n",
368 | " return shallow_mlp_model"
369 | ]
370 | },
371 | {
372 | "cell_type": "markdown",
373 | "id": "Zw10Mxd0AfRv",
374 | "metadata": {
375 | "id": "Zw10Mxd0AfRv"
376 | },
377 | "source": [
378 | "## Training and evaluation"
379 | ]
380 | },
381 | {
382 | "cell_type": "code",
383 | "execution_count": 9,
384 | "id": "63f6039d",
385 | "metadata": {
386 | "colab": {
387 | "base_uri": "https://localhost:8080/"
388 | },
389 | "id": "63f6039d",
390 | "outputId": "3352b60b-4c15-4e9f-ccd8-4d8489a814c3"
391 | },
392 | "outputs": [
393 | {
394 | "name": "stdout",
395 | "output_type": "stream",
396 | "text": [
397 | "Epoch 1/60\n",
398 | "763/763 [==============================] - 3s 3ms/step - loss: 2.1269 - accuracy: 0.4803 - val_loss: 1.6482 - val_accuracy: 0.5378\n",
399 | "Epoch 2/60\n",
400 | "763/763 [==============================] - 2s 2ms/step - loss: 1.4933 - accuracy: 0.5595 - val_loss: 1.5942 - val_accuracy: 0.5397\n",
401 | "Epoch 3/60\n",
402 | "763/763 [==============================] - 2s 2ms/step - loss: 1.2850 - accuracy: 0.6037 - val_loss: 1.6945 - val_accuracy: 0.5284\n",
403 | "Epoch 4/60\n",
404 | "763/763 [==============================] - 2s 2ms/step - loss: 1.1200 - accuracy: 0.6457 - val_loss: 1.7306 - val_accuracy: 0.5330\n",
405 | "Epoch 5/60\n",
406 | "763/763 [==============================] - 2s 2ms/step - loss: 0.9507 - accuracy: 0.6941 - val_loss: 1.8665 - val_accuracy: 0.5059\n",
407 | "Epoch 6/60\n",
408 | "763/763 [==============================] - 2s 2ms/step - loss: 0.8176 - accuracy: 0.7357 - val_loss: 2.1472 - val_accuracy: 0.4921\n",
409 | "Epoch 7/60\n",
410 | "763/763 [==============================] - 2s 2ms/step - loss: 0.7085 - accuracy: 0.7665 - val_loss: 2.5042 - val_accuracy: 0.5033\n",
411 | "Epoch 8/60\n",
412 | "763/763 [==============================] - 2s 2ms/step - loss: 0.5982 - accuracy: 0.8028 - val_loss: 2.4998 - val_accuracy: 0.4875\n",
413 | "Epoch 9/60\n",
414 | "763/763 [==============================] - 2s 2ms/step - loss: 0.5017 - accuracy: 0.8324 - val_loss: 2.5644 - val_accuracy: 0.4734\n",
415 | "Epoch 10/60\n",
416 | "763/763 [==============================] - 2s 2ms/step - loss: 0.4258 - accuracy: 0.8585 - val_loss: 3.0435 - val_accuracy: 0.4576\n",
417 | "Epoch 11/60\n",
418 | "763/763 [==============================] - 2s 2ms/step - loss: 0.3781 - accuracy: 0.8763 - val_loss: 3.1685 - val_accuracy: 0.4941\n",
419 | "Epoch 12/60\n",
420 | "763/763 [==============================] - 2s 2ms/step - loss: 0.3177 - accuracy: 0.8942 - val_loss: 3.5111 - val_accuracy: 0.4941\n",
421 | "Epoch 13/60\n",
422 | "763/763 [==============================] - 2s 2ms/step - loss: 0.2762 - accuracy: 0.9099 - val_loss: 3.6547 - val_accuracy: 0.4769\n",
423 | "Epoch 14/60\n",
424 | "763/763 [==============================] - 2s 2ms/step - loss: 0.2394 - accuracy: 0.9228 - val_loss: 3.9069 - val_accuracy: 0.4769\n",
425 | "Epoch 15/60\n",
426 | "763/763 [==============================] - 2s 3ms/step - loss: 0.2040 - accuracy: 0.9331 - val_loss: 4.0917 - val_accuracy: 0.4915\n",
427 | "Epoch 16/60\n",
428 | "763/763 [==============================] - 2s 3ms/step - loss: 0.1834 - accuracy: 0.9417 - val_loss: 4.2465 - val_accuracy: 0.4808\n",
429 | "Epoch 17/60\n",
430 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1504 - accuracy: 0.9518 - val_loss: 4.6064 - val_accuracy: 0.4840\n",
431 | "Epoch 18/60\n",
432 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1472 - accuracy: 0.9525 - val_loss: 4.7535 - val_accuracy: 0.4801\n",
433 | "Epoch 19/60\n",
434 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1627 - accuracy: 0.9494 - val_loss: 4.8439 - val_accuracy: 0.4906\n",
435 | "Epoch 20/60\n",
436 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1534 - accuracy: 0.9515 - val_loss: 5.3002 - val_accuracy: 0.4860\n",
437 | "Epoch 21/60\n",
438 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1522 - accuracy: 0.9517 - val_loss: 5.1882 - val_accuracy: 0.4882\n",
439 | "Epoch 22/60\n",
440 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1332 - accuracy: 0.9570 - val_loss: 5.3140 - val_accuracy: 0.4793\n",
441 | "Epoch 23/60\n",
442 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1226 - accuracy: 0.9621 - val_loss: 5.5203 - val_accuracy: 0.4661\n",
443 | "Epoch 24/60\n",
444 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1351 - accuracy: 0.9587 - val_loss: 5.7630 - val_accuracy: 0.4611\n",
445 | "Epoch 25/60\n",
446 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1202 - accuracy: 0.9622 - val_loss: 5.5442 - val_accuracy: 0.4650\n",
447 | "Epoch 26/60\n",
448 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1051 - accuracy: 0.9672 - val_loss: 6.1580 - val_accuracy: 0.4919\n",
449 | "Epoch 27/60\n",
450 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1149 - accuracy: 0.9647 - val_loss: 6.3746 - val_accuracy: 0.4659\n",
451 | "Epoch 28/60\n",
452 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1096 - accuracy: 0.9668 - val_loss: 6.5307 - val_accuracy: 0.4696\n",
453 | "Epoch 29/60\n",
454 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1075 - accuracy: 0.9663 - val_loss: 6.6217 - val_accuracy: 0.4860\n",
455 | "Epoch 30/60\n",
456 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1009 - accuracy: 0.9689 - val_loss: 6.4920 - val_accuracy: 0.4768\n",
457 | "Epoch 31/60\n",
458 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1069 - accuracy: 0.9678 - val_loss: 6.4422 - val_accuracy: 0.4959\n",
459 | "Epoch 32/60\n",
460 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0999 - accuracy: 0.9702 - val_loss: 6.8128 - val_accuracy: 0.4653\n",
461 | "Epoch 33/60\n",
462 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0985 - accuracy: 0.9708 - val_loss: 6.6713 - val_accuracy: 0.4675\n",
463 | "Epoch 34/60\n",
464 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0885 - accuracy: 0.9734 - val_loss: 6.9721 - val_accuracy: 0.4685\n",
465 | "Epoch 35/60\n",
466 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0867 - accuracy: 0.9735 - val_loss: 6.9272 - val_accuracy: 0.4917\n",
467 | "Epoch 36/60\n",
468 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0956 - accuracy: 0.9722 - val_loss: 7.1589 - val_accuracy: 0.4956\n",
469 | "Epoch 37/60\n",
470 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0845 - accuracy: 0.9752 - val_loss: 7.2681 - val_accuracy: 0.4958\n",
471 | "Epoch 38/60\n",
472 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0897 - accuracy: 0.9743 - val_loss: 7.3087 - val_accuracy: 0.4917\n",
473 | "Epoch 39/60\n",
474 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0962 - accuracy: 0.9726 - val_loss: 7.4859 - val_accuracy: 0.4932\n",
475 | "Epoch 40/60\n",
476 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0811 - accuracy: 0.9766 - val_loss: 7.0348 - val_accuracy: 0.4823\n",
477 | "Epoch 41/60\n",
478 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0790 - accuracy: 0.9762 - val_loss: 7.2561 - val_accuracy: 0.4849\n",
479 | "Epoch 42/60\n",
480 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0984 - accuracy: 0.9730 - val_loss: 7.4048 - val_accuracy: 0.4875\n",
481 | "Epoch 43/60\n",
482 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0875 - accuracy: 0.9752 - val_loss: 7.2045 - val_accuracy: 0.4908\n",
483 | "Epoch 44/60\n",
484 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0657 - accuracy: 0.9800 - val_loss: 7.5468 - val_accuracy: 0.4889\n",
485 | "Epoch 45/60\n",
486 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0759 - accuracy: 0.9778 - val_loss: 7.4829 - val_accuracy: 0.4817\n",
487 | "Epoch 46/60\n",
488 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0750 - accuracy: 0.9792 - val_loss: 7.7399 - val_accuracy: 0.4762\n",
489 | "Epoch 47/60\n",
490 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0851 - accuracy: 0.9769 - val_loss: 7.4293 - val_accuracy: 0.4757\n",
491 | "Epoch 48/60\n",
492 | "763/763 [==============================] - 2s 2ms/step - loss: 0.1009 - accuracy: 0.9732 - val_loss: 8.0313 - val_accuracy: 0.4803\n",
493 | "Epoch 49/60\n",
494 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0819 - accuracy: 0.9773 - val_loss: 8.2462 - val_accuracy: 0.4847\n",
495 | "Epoch 50/60\n",
496 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0838 - accuracy: 0.9771 - val_loss: 8.1154 - val_accuracy: 0.4900\n",
497 | "Epoch 51/60\n",
498 | "763/763 [==============================] - 2s 3ms/step - loss: 0.0667 - accuracy: 0.9809 - val_loss: 8.3821 - val_accuracy: 0.4692\n",
499 | "Epoch 52/60\n",
500 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0739 - accuracy: 0.9790 - val_loss: 8.2407 - val_accuracy: 0.4854\n",
501 | "Epoch 53/60\n",
502 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0713 - accuracy: 0.9811 - val_loss: 8.0732 - val_accuracy: 0.4766\n",
503 | "Epoch 54/60\n",
504 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0681 - accuracy: 0.9813 - val_loss: 8.5076 - val_accuracy: 0.4849\n",
505 | "Epoch 55/60\n",
506 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0750 - accuracy: 0.9796 - val_loss: 8.4956 - val_accuracy: 0.4869\n",
507 | "Epoch 56/60\n",
508 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0761 - accuracy: 0.9799 - val_loss: 8.7340 - val_accuracy: 0.4757\n",
509 | "Epoch 57/60\n",
510 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0657 - accuracy: 0.9822 - val_loss: 8.7144 - val_accuracy: 0.4899\n",
511 | "Epoch 58/60\n",
512 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0654 - accuracy: 0.9820 - val_loss: 8.6923 - val_accuracy: 0.4819\n",
513 | "Epoch 59/60\n",
514 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0693 - accuracy: 0.9809 - val_loss: 8.9453 - val_accuracy: 0.4782\n",
515 | "Epoch 60/60\n",
516 | "763/763 [==============================] - 2s 2ms/step - loss: 0.0796 - accuracy: 0.9800 - val_loss: 8.7961 - val_accuracy: 0.4755\n",
517 | "847/847 [==============================] - 2s 2ms/step - loss: 9.1531 - accuracy: 0.4710\n",
518 | "Top-1 accuracy on the test set: 47.1%.\n"
519 | ]
520 | }
521 | ],
522 | "source": [
523 | "epochs = 60\n",
524 | "\n",
525 | "shallow_mlp_model = make_model()\n",
526 | "shallow_mlp_model.compile(\n",
527 | " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
528 | ")\n",
529 | "\n",
530 | "history = shallow_mlp_model.fit(\n",
531 | " training_dataset, validation_data=validation_dataset, epochs=epochs\n",
532 | ")\n",
533 | "\n",
534 | "_, accuracy = shallow_mlp_model.evaluate(test_dataset)\n",
535 | "print(f\"Top-1 accuracy on the test set: {round(accuracy * 100, 2)}%.\")"
536 | ]
537 | }
538 | ],
539 | "metadata": {
540 | "accelerator": "GPU",
541 | "colab": {
542 | "collapsed_sections": [],
543 | "machine_shape": "hm",
544 | "name": "bigram-tfidf-shallow-mlp.ipynb",
545 | "provenance": []
546 | },
547 | "kernelspec": {
548 | "display_name": "Python 3 (ipykernel)",
549 | "language": "python",
550 | "name": "python3"
551 | },
552 | "language_info": {
553 | "codemirror_mode": {
554 | "name": "ipython",
555 | "version": 3
556 | },
557 | "file_extension": ".py",
558 | "mimetype": "text/x-python",
559 | "name": "python",
560 | "nbconvert_exporter": "python",
561 | "pygments_lexer": "ipython3",
562 | "version": "3.8.2"
563 | }
564 | },
565 | "nbformat": 4,
566 | "nbformat_minor": 5
567 | }
568 |
--------------------------------------------------------------------------------
/smart-batching-shallow-mlp.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "dad1d7a9",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
11 | "# you may not use this file except in compliance with the License.\n",
12 | "# You may obtain a copy of the License at\n",
13 | "#\n",
14 | "# https://www.apache.org/licenses/LICENSE-2.0\n",
15 | "#\n",
16 | "# Unless required by applicable law or agreed to in writing, software\n",
17 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
18 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
19 | "# See the License for the specific language governing permissions and\n",
20 | "# limitations under the License."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "id": "55c92abb",
26 | "metadata": {},
27 | "source": [
28 | "## Training a Shallow Text Classifier with Dynamic Batching"
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "id": "77bad680",
34 | "metadata": {},
35 | "source": [
36 | ""
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "id": "2f21500c",
49 | "metadata": {},
50 | "source": [
51 | "## Setup"
52 | ]
53 | },
54 | {
55 | "cell_type": "code",
56 | "execution_count": null,
57 | "id": "12118063",
58 | "metadata": {},
59 | "outputs": [],
60 | "source": [
61 | "!pip install -q wandb"
62 | ]
63 | },
64 | {
65 | "cell_type": "code",
66 | "execution_count": null,
67 | "id": "2e682fb9",
68 | "metadata": {},
69 | "outputs": [],
70 | "source": [
71 | "!gdown --id 1CvkRnGC8b_-n1NcbwcwxcIq7SusmDMb5 -O train_data.txt\n",
72 | "!gdown --id 1h1evGF5NVi2p8RoWxl8xhpOod0ZN_-ky -O test_data_solution.txt "
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "id": "05df71d4",
79 | "metadata": {},
80 | "outputs": [],
81 | "source": [
82 | "from tensorflow import keras\n",
83 | "import tensorflow as tf\n",
84 | "\n",
85 | "from sklearn.model_selection import train_test_split\n",
86 | "import pandas as pd\n",
87 | "import numpy as np\n",
88 | "import random\n",
89 | "import tqdm\n",
90 | "import time\n",
91 | "import wandb"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "id": "461512bf",
97 | "metadata": {},
98 | "source": [
99 | "## Constants"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "id": "835b78ff",
106 | "metadata": {},
107 | "outputs": [],
108 | "source": [
109 | "AUTO = tf.data.AUTOTUNE\n",
110 | "BATCH_SIZE = 128\n",
111 | "EPOCHS = 60\n",
112 | "NUM_TRIALS = 5\n",
113 | "LR_DECAY_PATIENCE = 5\n",
114 | "\n",
115 | "VAL_SPLIT = 0.1\n",
116 | "SPLIT_SEED = 42"
117 | ]
118 | },
119 | {
120 | "cell_type": "markdown",
121 | "id": "69af80da",
122 | "metadata": {},
123 | "source": [
124 | "## Data loading"
125 | ]
126 | },
127 | {
128 | "cell_type": "code",
129 | "execution_count": null,
130 | "id": "91cb7d09",
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "train_df = pd.read_csv(\n",
135 | " \"train_data.txt\",\n",
136 | " engine=\"python\",\n",
137 | " sep=\" ::: \",\n",
138 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
139 | ")\n",
140 | "\n",
141 | "test_df = pd.read_csv(\n",
142 | " \"test_data_solution.txt\",\n",
143 | " engine=\"python\",\n",
144 | " sep=\" ::: \",\n",
145 | " names=[\"id\", \"movie\", \"genre\", \"summary\"],\n",
146 | ")"
147 | ]
148 | },
149 | {
150 | "cell_type": "code",
151 | "execution_count": null,
152 | "id": "505d63df",
153 | "metadata": {},
154 | "outputs": [],
155 | "source": [
156 | "# Viewing training data\n",
157 | "train_df.head()"
158 | ]
159 | },
160 | {
161 | "cell_type": "markdown",
162 | "id": "d2cddd72",
163 | "metadata": {},
164 | "source": [
165 | "## Data splitting"
166 | ]
167 | },
168 | {
169 | "cell_type": "code",
170 | "execution_count": null,
171 | "id": "23ba7b1f",
172 | "metadata": {},
173 | "outputs": [],
174 | "source": [
175 | "# Split the data using train_test_split from sklearn\n",
176 | "train_shuffled = train_df.sample(frac=1)\n",
177 | "train_df_new, val_df = train_test_split(\n",
178 | " train_shuffled, test_size=VAL_SPLIT, random_state=SPLIT_SEED\n",
179 | ")\n",
180 | "\n",
181 | "print(f\"Number of training samples: {len(train_df_new)}.\")\n",
182 | "print(f\"Number of validation samples: {len(val_df)}.\")\n",
183 | "print(f\"Number of test examples: {len(test_df)}.\")"
184 | ]
185 | },
186 | {
187 | "cell_type": "markdown",
188 | "id": "3c94be56",
189 | "metadata": {},
190 | "source": [
191 | "## Data preprocessing"
192 | ]
193 | },
194 | {
195 | "cell_type": "code",
196 | "execution_count": null,
197 | "id": "0ff3c7cd",
198 | "metadata": {},
199 | "outputs": [],
200 | "source": [
201 | "text_vectorizer = keras.layers.TextVectorization()\n",
202 | "text_vectorizer.adapt(train_df_new[\"summary\"])"
203 | ]
204 | },
205 | {
206 | "cell_type": "code",
207 | "execution_count": null,
208 | "id": "fed20b13",
209 | "metadata": {},
210 | "outputs": [],
211 | "source": [
212 | "for i in train_df_new.index.tolist()[:10]:\n",
213 | " print(text_vectorizer(train_df_new[\"summary\"][i]).shape)"
214 | ]
215 | },
216 | {
217 | "cell_type": "code",
218 | "execution_count": null,
219 | "id": "e205a3f7",
220 | "metadata": {},
221 | "outputs": [],
222 | "source": [
223 | "train_df_new[\"total_words\"] = train_df_new[\"summary\"].str.split().str.len()\n",
224 | "max_seqlen = int(train_df_new[\"total_words\"].max())\n",
225 | "max_seqlen"
226 | ]
227 | },
228 | {
229 | "cell_type": "code",
230 | "execution_count": null,
231 | "id": "a4ca6593",
232 | "metadata": {},
233 | "outputs": [],
234 | "source": [
235 | "label_encoder = keras.layers.StringLookup(vocabulary=train_df_new[\"genre\"].unique())\n",
236 | "label_encoder.get_vocabulary()"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": null,
242 | "id": "bb377606",
243 | "metadata": {},
244 | "outputs": [],
245 | "source": [
246 | "def preprocess_single_row(summary, label):\n",
247 | " summary = text_vectorizer(summary)\n",
248 | " label = label_encoder(label)\n",
249 | " return summary, label\n",
250 | "\n",
251 | "\n",
252 | "def prepare_dataset(dataframe):\n",
253 | " dataset = tf.data.Dataset.from_tensor_slices(\n",
254 | " (dataframe[\"summary\"].values, dataframe[\"genre\"].values)\n",
255 | " )\n",
256 | " dataset = dataset.map(preprocess_single_row, num_parallel_calls=AUTO)\n",
257 | " dataset = dataset.padded_batch(BATCH_SIZE)\n",
258 | " return dataset.prefetch(AUTO)"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": null,
264 | "id": "e248539b",
265 | "metadata": {},
266 | "outputs": [],
267 | "source": [
268 | "training_dataset = prepare_dataset(train_df_new)\n",
269 | "validation_dataset = prepare_dataset(val_df)\n",
270 | "test_dataset = prepare_dataset(test_df)\n",
271 | "\n",
272 | "\n",
273 | "for sample_batch in training_dataset.take(10):\n",
274 | " print(sample_batch[0].shape)\n",
275 | " print(sample_batch[1].shape)"
276 | ]
277 | },
278 | {
279 | "cell_type": "markdown",
280 | "id": "e8f1078f",
281 | "metadata": {},
282 | "source": [
283 | "## Model utilities"
284 | ]
285 | },
286 | {
287 | "cell_type": "code",
288 | "execution_count": null,
289 | "id": "613e6281",
290 | "metadata": {},
291 | "outputs": [],
292 | "source": [
293 | "def make_model(use_gru=False):\n",
294 | " inputs = keras.Input(shape=(None,), dtype=\"int64\")\n",
295 | " x = keras.layers.Embedding(\n",
296 | " input_dim=text_vectorizer.vocabulary_size(),\n",
297 | " output_dim=16,\n",
298 | " )(inputs)\n",
299 | " \n",
300 | " if use_gru:\n",
301 | " x = keras.layers.Bidirectional(keras.layers.GRU(8))(x)\n",
302 | " else:\n",
303 | " x = keras.layers.GlobalAveragePooling1D()(x)\n",
304 | " x = keras.layers.Dense(512, activation=\"relu\")(x)\n",
305 | " x = keras.layers.Dense(256, activation=\"relu\")(x)\n",
306 | " outputs = keras.layers.Dense(label_encoder.vocabulary_size(), activation=\"softmax\")(\n",
307 | " x\n",
308 | " )\n",
309 | " shallow_mlp_model = keras.Model(inputs, outputs)\n",
310 | " return shallow_mlp_model"
311 | ]
312 | },
313 | {
314 | "cell_type": "code",
315 | "execution_count": null,
316 | "id": "4e7e213e",
317 | "metadata": {},
318 | "outputs": [],
319 | "source": [
320 | "make_model().summary()"
321 | ]
322 | },
323 | {
324 | "cell_type": "markdown",
325 | "id": "ab791680",
326 | "metadata": {},
327 | "source": [
328 | "## Training and evaluation with smart batching"
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": null,
334 | "id": "8c1c4b1b",
335 | "metadata": {},
336 | "outputs": [],
337 | "source": [
338 | "for i in range(NUM_TRIALS):\n",
339 | " wandb.init(\n",
340 | " project=\"smart-batching-simpler-models\",\n",
341 | " entity=\"carted\",\n",
342 | " name=f\"smart-batching-run-{i}\",\n",
343 | " )\n",
344 | " shallow_mlp_model = make_model()\n",
345 | " shallow_mlp_model.compile(\n",
346 | " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
347 | " )\n",
348 | " callbacks = [\n",
349 | " keras.callbacks.ReduceLROnPlateau(patience=LR_DECAY_PATIENCE),\n",
350 | " wandb.keras.WandbCallback(),\n",
351 | " ]\n",
352 | "\n",
353 | " start_time = time.time()\n",
354 | " history = shallow_mlp_model.fit(\n",
355 | " training_dataset,\n",
356 | " validation_data=validation_dataset,\n",
357 | " epochs=EPOCHS,\n",
358 | " callbacks=callbacks,\n",
359 | " )\n",
360 | " end_time = time.time()\n",
361 | " print(f\"Model took {(end_time - start_time):.2f} seconds to train.\")\n",
362 | " wandb.log({\"model_training_time_secs\": end_time - start_time})\n",
363 | "\n",
364 | " _, accuracy = shallow_mlp_model.evaluate(test_dataset)\n",
365 | " print(f\"Top-1 accuracy on the test set: {(accuracy * 100):0.2f}%.\")\n",
366 | " wandb.log({\"top_1_accuracy_test_set\": accuracy})\n",
367 | "\n",
368 | " wandb.finish()"
369 | ]
370 | },
371 | {
372 | "cell_type": "markdown",
373 | "id": "6e9f380f",
374 | "metadata": {},
375 | "source": [
376 | "### With GRU"
377 | ]
378 | },
379 | {
380 | "cell_type": "code",
381 | "execution_count": null,
382 | "id": "248ee5ac",
383 | "metadata": {},
384 | "outputs": [],
385 | "source": [
386 | "for i in range(NUM_TRIALS):\n",
387 | " wandb.init(\n",
388 | " project=\"smart-batching-simpler-models\",\n",
389 | " entity=\"carted\",\n",
390 | " name=f\"smart-batching-with-gru-run-{i}\",\n",
391 | " )\n",
392 | " shallow_mlp_model = make_model(use_gru=True)\n",
393 | " shallow_mlp_model.compile(\n",
394 | " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
395 | " )\n",
396 | " callbacks = [\n",
397 | " keras.callbacks.ReduceLROnPlateau(patience=LR_DECAY_PATIENCE),\n",
398 | " wandb.keras.WandbCallback(),\n",
399 | " ]\n",
400 | "\n",
401 | " start_time = time.time()\n",
402 | " history = shallow_mlp_model.fit(\n",
403 | " training_dataset,\n",
404 | " validation_data=validation_dataset,\n",
405 | " epochs=EPOCHS,\n",
406 | " callbacks=callbacks,\n",
407 | " )\n",
408 | " end_time = time.time()\n",
409 | " print(f\"Model took {(end_time - start_time):.2f} seconds to train.\")\n",
410 | " wandb.log({\"model_training_time_secs\": end_time - start_time})\n",
411 | "\n",
412 | " _, accuracy = shallow_mlp_model.evaluate(test_dataset)\n",
413 | " print(f\"Top-1 accuracy on the test set: {(accuracy * 100):0.2f}%.\")\n",
414 | " wandb.log({\"top_1_accuracy_test_set\": accuracy})\n",
415 | "\n",
416 | " wandb.finish()"
417 | ]
418 | },
419 | {
420 | "cell_type": "markdown",
421 | "id": "dac55d30",
422 | "metadata": {},
423 | "source": [
424 | "## Training and evaluation with fixed-length padding"
425 | ]
426 | },
427 | {
428 | "cell_type": "code",
429 | "execution_count": null,
430 | "id": "8a11e7bc",
431 | "metadata": {},
432 | "outputs": [],
433 | "source": [
434 | "text_vectorizer = keras.layers.TextVectorization(output_sequence_length=max_seqlen)\n",
435 | "text_vectorizer.adapt(train_df_new[\"summary\"])\n",
436 | "\n",
437 | "\n",
438 | "def preprocess_fixed_length(summary, label):\n",
439 | " summary = text_vectorizer(summary)\n",
440 | " label = label_encoder(label)\n",
441 | " return summary, label\n",
442 | "\n",
443 | "\n",
444 | "def prepare_dataset_fixed_length(dataframe):\n",
445 | " dataset = tf.data.Dataset.from_tensor_slices(\n",
446 | " (dataframe[\"summary\"].values, dataframe[\"genre\"].values)\n",
447 | " )\n",
448 | " dataset = dataset.map(preprocess_fixed_length, num_parallel_calls=AUTO)\n",
449 | " dataset = dataset.batch(BATCH_SIZE)\n",
450 | " return dataset.prefetch(AUTO)"
451 | ]
452 | },
453 | {
454 | "cell_type": "code",
455 | "execution_count": null,
456 | "id": "c9d0070d",
457 | "metadata": {},
458 | "outputs": [],
459 | "source": [
460 | "training_dataset = prepare_dataset_fixed_length(train_df_new)\n",
461 | "validation_dataset = prepare_dataset_fixed_length(val_df)\n",
462 | "test_dataset = prepare_dataset_fixed_length(test_df)\n",
463 | "\n",
464 | "\n",
465 | "for sample_batch in training_dataset.take(10):\n",
466 | " print(sample_batch[0].shape)\n",
467 | " print(sample_batch[1].shape)"
468 | ]
469 | },
470 | {
471 | "cell_type": "code",
472 | "execution_count": null,
473 | "id": "affd25d2",
474 | "metadata": {},
475 | "outputs": [],
476 | "source": [
477 | "for i in range(NUM_TRIALS):\n",
478 | " wandb.init(\n",
479 | " project=\"smart-batching-simpler-models\",\n",
480 | " entity=\"carted\",\n",
481 | " name=f\"fixed-length-padding-run-{i}\",\n",
482 | " )\n",
483 | " shallow_mlp_model = make_model()\n",
484 | " shallow_mlp_model.compile(\n",
485 | " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
486 | " )\n",
487 | " callbacks = [\n",
488 | " keras.callbacks.ReduceLROnPlateau(patience=LR_DECAY_PATIENCE),\n",
489 | " wandb.keras.WandbCallback(),\n",
490 | " ]\n",
491 | "\n",
492 | " start_time = time.time()\n",
493 | " history = shallow_mlp_model.fit(\n",
494 | " training_dataset,\n",
495 | " validation_data=validation_dataset,\n",
496 | " epochs=EPOCHS,\n",
497 | " callbacks=callbacks,\n",
498 | " )\n",
499 | " end_time = time.time()\n",
500 | " print(f\"Model took {(end_time - start_time):.2f} seconds to train.\")\n",
501 | " wandb.log({\"model_training_time_secs\": end_time - start_time})\n",
502 | "\n",
503 | " _, accuracy = shallow_mlp_model.evaluate(test_dataset)\n",
504 | " print(f\"Top-1 accuracy on the test set: {(accuracy * 100):0.2f}%.\")\n",
505 | " wandb.log({\"top_1_accuracy_test_set\": accuracy})\n",
506 | "\n",
507 | " wandb.finish()"
508 | ]
509 | },
510 | {
511 | "cell_type": "markdown",
512 | "id": "3750dc29",
513 | "metadata": {},
514 | "source": [
515 | "### With GRU"
516 | ]
517 | },
518 | {
519 | "cell_type": "code",
520 | "execution_count": null,
521 | "id": "c9207b58",
522 | "metadata": {},
523 | "outputs": [],
524 | "source": [
525 | "for i in range(NUM_TRIALS):\n",
526 | " wandb.init(\n",
527 | " project=\"smart-batching-simpler-models\",\n",
528 | " entity=\"carted\",\n",
529 | " name=f\"fixed-length-padding-with-gru-run-{i}\",\n",
530 | " )\n",
531 | " shallow_mlp_model = make_model(use_gru=True)\n",
532 | " shallow_mlp_model.compile(\n",
533 | " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"]\n",
534 | " )\n",
535 | " callbacks = [\n",
536 | " keras.callbacks.ReduceLROnPlateau(patience=LR_DECAY_PATIENCE),\n",
537 | " wandb.keras.WandbCallback(),\n",
538 | " ]\n",
539 | "\n",
540 | " start_time = time.time()\n",
541 | " history = shallow_mlp_model.fit(\n",
542 | " training_dataset,\n",
543 | " validation_data=validation_dataset,\n",
544 | " epochs=EPOCHS,\n",
545 | " callbacks=callbacks,\n",
546 | " )\n",
547 | " end_time = time.time()\n",
548 | " print(f\"Model took {(end_time - start_time):.2f} seconds to train.\")\n",
549 | " wandb.log({\"model_training_time_secs\": end_time - start_time})\n",
550 | "\n",
551 | " _, accuracy = shallow_mlp_model.evaluate(test_dataset)\n",
552 | " print(f\"Top-1 accuracy on the test set: {(accuracy * 100):0.2f}%.\")\n",
553 | " wandb.log({\"top_1_accuracy_test_set\": accuracy})\n",
554 | "\n",
555 | " wandb.finish()"
556 | ]
557 | }
558 | ],
559 | "metadata": {
560 | "environment": {
561 | "name": "tf2-gpu.2-6.m81",
562 | "type": "gcloud",
563 | "uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-6:m81"
564 | },
565 | "kernelspec": {
566 | "display_name": "Python 3 (ipykernel)",
567 | "language": "python",
568 | "name": "python3"
569 | },
570 | "language_info": {
571 | "codemirror_mode": {
572 | "name": "ipython",
573 | "version": 3
574 | },
575 | "file_extension": ".py",
576 | "mimetype": "text/x-python",
577 | "name": "python",
578 | "nbconvert_exporter": "python",
579 | "pygments_lexer": "ipython3",
580 | "version": "3.8.2"
581 | }
582 | },
583 | "nbformat": 4,
584 | "nbformat_minor": 5
585 | }
586 |
--------------------------------------------------------------------------------