File size: 45,820 Bytes
fa73be6 37e7b34 7fb92b3 8f8e390 7fb92b3 bd572c4 7fb92b3 fa73be6 37e7b34 fa73be6 37e7b34 fa73be6 37e7b34 fa73be6 8f8e390 fa73be6 8f8e390 840c6e7 8f8e390 840c6e7 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 fa73be6 8f8e390 7fb92b3 8f8e390 7fb92b3 fa73be6 7fb92b3 37e7b34 7fb92b3 37e7b34 7fb92b3 fa73be6 7fb92b3 37e7b34 7fb92b3 92582fa 7fb92b3 92582fa 7fb92b3 37e7b34 7fb92b3 8f8e390 7fb92b3 8f8e390 6b8d575 37e7b34 7fb92b3 6b8d575 8f8e390 37e7b34 8f8e390 37e7b34 fa73be6 37e7b34 fa73be6 37e7b34 fa73be6 bd572c4 fa73be6 37e7b34 fa73be6 37e7b34 bd572c4 37e7b34 fa73be6 37e7b34 fa73be6 8f8e390 7fb92b3 840c6e7 6b8d575 840c6e7 8f8e390 37e7b34 8f8e390 7fb92b3 8f8e390 7fb92b3 37e7b34 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 fa73be6 8f8e390 37e7b34 8f8e390 fa73be6 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 7fb92b3 8f8e390 37e7b34 8f8e390 37e7b34 8f8e390 37e7b34 8f8e390 6b8d575 37e7b34 7fb92b3 8f8e390 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 |
from glob import glob
from itertools import zip_longest
import sqlite3
import psutil
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
IMAGE_WIDTHS = 900
PRE_TRAINED_DB = "data/pretrained.sqlite"
@st.cache_resource
def load_eval_data():
conn = sqlite3.connect(PRE_TRAINED_DB)
conn.row_factory = lambda c, r: {
col[0]: r[idx] for idx, col in enumerate(c.description)
}
df = pd.read_sql_query("SELECT * FROM pretrained", conn)
df.replace("None", np.nan, inplace=True)
df.rename(columns={"model": "name"}, inplace=True)
df = df.infer_objects()
int_columns = ["train_batch_size", "num_parameters"]
df[int_columns] = df[int_columns].astype("Int32")
plot_df = df[["name", "num_parameters", "summ_rouge1", "trans_en_nl_score"]]
plot_df[["num_parameters", "summ_rouge1", "trans_en_nl_score"]] = plot_df[
["num_parameters", "summ_rouge1", "trans_en_nl_score"]
].apply(pd.to_numeric)
plot_df["num params (M)"] = plot_df["num_parameters"].map(
lambda x: int(x / 10**6)
)
plot_df.dropna(subset=["summ_rouge1"], inplace=True)
plot_df.rename(
columns={"summ_rouge1": "summ Rouge1", "trans_en_nl_score": "en->nl Bleu"},
inplace=True,
)
for i, row in df.iterrows():
dirs = glob(
f"data/eval_summ_results/{row['id']}-{row['name']}/yhavinga_cnn_dailymail_dutch/eval_predictions*"
)
try:
file = dirs[-1] + "/generated.txt"
with open(file, "r") as f:
text = f.read().replace("<n>", " ")
except Exception:
text = "fine-tune failed, no data"
df.at[i, "summary"] = text
for i, row in df.iterrows():
dirs = glob(
f"data/eval_transl_results/{row['id']}-{row['name']}/yhavinga_ccmatrix/eval_predictions*"
)
try:
file = dirs[-1] + "/generated.txt"
with open(file, "r") as f:
text = f.read().replace("<n>", " ")
except Exception:
text = "fine-tune failed, no data"
df.at[i, "translation"] = text
# order df by the name column desc
df.sort_values(by="name", inplace=True, ascending=False)
return plot_df, df
def main():
st.set_page_config( # Alternate names: setup_page, page, layout
page_title="Pre-training Dutch T5 models", # String or None. Strings get appended with "β’ Streamlit".
layout="wide", # Can be "centered" or "wide". In the future also "dashboard", etc.
initial_sidebar_state="collapsed", # Can be "auto", "expanded", "collapsed"
page_icon="π", # String, anything supported by st.image, or None.
)
plot_df, df = load_eval_data()
with open("style.css") as f:
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
st.markdown("""# Dutch T5 models : UL2, T5, ByT5 and Long-T5 π³π±π§πͺ
TL;DR: Dutch NLP gets a boost with state-of-the-art T5 models trained on the largest Dutch corpus, mC4, and additional datasets.
See below for model lists and comparison.
During the [HuggingFace Flax/Jax community week](https://discuss.huggingface.co/t/open-to-the-community-community-week-using-jax-flax-for-nlp-cv/7104) in the summer of 2021,
I was granted access to Google's TPU Research Cloud (TRC),
a cloud-based platform for machine learning research and development that provides access to Google's
Tensor Processing Units (TPUs). My goal was to address the (then) shortage of T5 models for the Dutch language.
-- T5 is a state-of-the-art AI model architecture that can handle text as input and output,
making it an ideal tool for NLP tasks such as summarization, translation, and question-answering --
Since then, with extended access to the TRC, I have been able to train a variety of T5 models for Dutch.
Relevant papers are:
* **[Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683)** by *Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu*.
* **[ExT5: Towards Extreme Multi-Task Scaling for Transfer Learning](https://arxiv.org/abs/2111.10952)** by *Vamsi Aribandi, Yi Tay, Tal Schuster, Jinfeng Rao, Huaixiu Steven Zheng, Sanket Vaibhav Mehta, Honglei Zhuang, Vinh Q. Tran, Dara Bahri, Jianmo Ni, Jai Gupta, Kai Hui, Sebastian Ruder, Donald Metzler*.
* **[Scale Efficiently: Insights from Pre-training and Fine-tuning Transformers](https://arxiv.org/abs/2109.10686)** by *Yi Tay, Mostafa Dehghani, Jinfeng Rao, William Fedus, Samira Abnar, Hyung Won Chung, Sharan Narang, Dani Yogatama, Ashish Vaswani, Donald Metzler*.
* **[ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626)** by *Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel*
* **[LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916)** by *Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang*
* **[Scaling Up Models and Data with t5x and seqio](https://arxiv.org/abs/2203.17189)** by *Adam Roberts, Hyung Won Chung, Anselm Levskaya, Gaurav Mishra, James Bradbury, Daniel Andor, Sharan Narang, Brian Lester, Colin Gaffney, Afroz Mohiuddin, Curtis Hawthorne, Aitor Lewkowycz, Alex Salcianu, Marc van Zee, Jacob Austin, Sebastian Goodman, Livio Baldini Soares, Haitang Hu, Sasha Tsvyashchenko, Aakanksha Chowdhery, Jasmijn Bastings, Jannis Bulian, Xavier Garcia, Jianmo Ni, Andrew Chen, Kathleen Kenealy, Jonathan H. Clark, Stephan Lee, Dan Garrette, James Lee-Thorp, Colin Raffel, Noam Shazeer, Marvin Ritter, Maarten Bosma, Alexandre Passos, Jeremy Maitin-Shepard, Noah Fiedel, Mark Omernick, Brennan Saeta, Ryan Sepassi, Alexander Spiridonov, Joshua Newlan, Andrea Gesmundo*
* **[UL2: Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131)** by *Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Jason Wei, Xuezhi Wang, Hyung Won Chung, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Denny Zhou, Neil Houlsby, Donald Metzler*
Background on Google's TPU VM's and how to use the Huggingface transformers library to pre-train models can be found
at the following links
* https://discuss.huggingface.co/t/open-to-the-community-community-week-using-jax-flax-for-nlp-cv/7104
* https://github.com/huggingface/transformers/tree/main/examples/research_projects/jax-projects#talks
## Pre-training
### mC4 dataset
Together with the T5 model architecture and SeqIO, the T5 authors also created and released
the multilingual [mC4 dataset](https://huggingface.co./datasets/allenai/c4).
It was made available by AllenNLP on the HuggingFace Dataset hub.
Our team confirmed that the Dutch portion of the mC4 dataset was deduplicated,
and we cleaned the Dutch portion of the mC4 dataset using [code adapted](https://gitlab.com/yhavinga/c4nlpreproc) from the TensorFlow C4 dataset.
The resulting [mc4_nl_cleaned](https://huggingface.co./datasets/yhavinga/mc4_nl_cleaned) dataset on the HuggingFace hub
has configs for several sizes, and also configs for interleaved mixed Dutch and English
texts, e.g. [micro_en_nl](https://huggingface.co./datasets/yhavinga/mc4_nl_cleaned/viewer/micro_en_nl/train).
The `_en_nl` configs were added to accommodate multi-language pre-training
with the Huggingface pre-training script, that accepts only a single dataset as input.
The full, cleaned Dutch mC4 dataset is 151GB and remains (as of June 2022) the largest available Dutch
corpus on the HuggingFace Dataset hub.
### Additional books, Wikipedia and Dutch news articles datasets
The `t5_1_1` and `ul2` models have also been trained on Dutch books, the Dutch subset of Wikipedia (2022-03-20),
the English subset of Wikipedia (2022-03-01), and a subset of "mc4_nl_cleaned" containing only texts
from Dutch and Belgian newspapers. Mixing in the these datasets was done to bias the model towards
descriptions of events in the Netherlands and Belgium.
### Pre-Training Objectives
The T5 models are pre-trained using the [span corruption](https://arxiv.org/abs/1910.10683) denoising objective.
15% of the tokens in the text are masked, and each span
of masked tokens is replaced with a special token known as a sentinel token, where each span is assigned
its own sentinel token. The model is then trained to predict for each sentinel token the original text
that was replaced by the sentinel tokens.
The UL2 models are pre-trained with the [Mixture-of-Denoisers (MoD)](https://arxiv.org/abs/2205.05131) objective, that combines diverse pre-training
paradigms together. UL2 frames different objective functions for training language models as denoising tasks, where
the model has to recover missing sub-sequences of a given input. During pre-training it uses a novel mixture-of-denoisers
that samples from a varied set of such objectives, each with different configurations. UL2 is trained using a mixture of
three denoising tasks:
1. R-denoising (or regular span corruption), which emulates the standard T5 span corruption objective;
2. X-denoising (or extreme span corruption); and
3. S-denoising (or sequential PrefixLM).
### Pre-training software
#### Huggingface [run_t5_mlm_flax.py](https://github.com/huggingface/transformers/blob/main/examples/flax/language-modeling/run_t5_mlm_flax.py)
All models except `t5_1_1` and `ul2` were pre-trained using the Huggingface `run_t5_mlm_flax.py` script.
This script is a good fit if you want to get a grasp what's needed to pre-train a language model
with Flax and Jax, since all data preparation, model instantiation, loss function, and training loop are
contained in a single file.
#### Google's [T5X](https://github.com/google-research/t5x)
The Dutch `t5_1_1` and `ul2` models were pre-trained using T5X. This is a modular framework that can be used for
pre-training, fine-tuning, and evaluation of T5 models. Because of its modular and pluggable design,
by only supplying a few configuration and code files, it is possible to pre-train with your own definitions.
It is even possible to define custom neural network layers and architectures, though I did not do this and only
pre-trained the default T5 encoder-decoder architecture, and varied only the pre-training objective, and the
datasets used and mixed with SeqIO.
#### Conversion script from T5X to HF
The T5X models were converted to Huggingface Flax T5 format using a script that was adapted from the
[T5X checkpoint to HuggingFace Flax conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py).
This script was modified to cast weights to bf16, and to also convert to pytorch format.
For this conversion to be successful, the T5X model had to be saved with `use_gda=False` set in the GIN file.
""")
st.markdown(
"""## Evaluation
### Evaluation setup
Each pre-trained model was evaluated by fine-tuning on summarization and translation. The learning-rate was set to
a constant schedule after a small warmup of 32 steps.
Fine-tuning for evaluation was done on a limited set of 50K examples from the fine-tuning datasets.
| | Summarization | Translation |
|-----------------:|------------------|-------------------|
| Dataset | [CNN Dailymail Dutch](https://huggingface.co./datasets/yhavinga/cnn_dailymail_dutch) | [CCMatrix En->NL](https://huggingface.co./datasets/yhavinga/ccmatrix_en_nl) |
| #train samples | 50K | 50K |
| Optimizer | AdamW | AdamW |
| learning rate | 0.001 | 0.0005 |
| source length | 1024 | 128 |
| target length | 142 | 128 |
| #eval samples | 1000 | 1000 |
| WandB link | [eval_summ](https://wandb.ai/yepster/eval_dutch_cnndaily_202302_flax)|[eval_transl](https://wandb.ai/yepster/eval_dutch_ccmatrix_202302_flax) |
On the WandB links above you can also find generated texts for each model to compare.
### Evaluation results
The figure below shows the evaluation scores for most models, with summarization Rouge1 on the x-axis (higher is better),
and translation English to Dutch Bleu score on the y-axis (higher is better).
The point size is proportional to the model size.
UL2 models are blue,
t5_1_1 models orange,
Flan models red,
mT5 green and the other models black.
"""
)
col1, col2 = st.columns(2)
with col1:
ul2_enabled = st.checkbox(
"UL2 Dutch (and English) (trained with T5X)", value=True
)
t5_1_1_enabled = st.checkbox("t5_1_1 Dutch (trained with T5X)", value=True)
flan_enabled = st.checkbox("Flan T5 (google/flan-t5-*)", value=True)
mt5_enabled = st.checkbox("mt5 (google/mt5-*)", value=True)
long_t5_enabled = st.checkbox(
"Long T5 Dutch+English (trained with HuggingFace script)"
)
t5_v1_1_enabled = st.checkbox(
"T5 Dutch (and English) (trained with HuggingFace script)"
)
with col2:
small_enabled = st.checkbox("small model sizes")
base_enabled = st.checkbox("base model sizes")
large_enabled = st.checkbox("large model sizes")
_24_enabled = st.checkbox("small nl24 deep narrow sizes")
_36_enabled = st.checkbox("base nl36 deep narrow sizes")
_8l_enabled = st.checkbox("large nl8 shallow sizes")
_4xl_enabled = st.checkbox("xlarge nl4 shallow wide sizes")
plot_df = plot_df[
(plot_df["name"].str.contains("ul2") & ul2_enabled)
| (plot_df["name"].str.contains("flan") & flan_enabled)
| (plot_df["name"].str.contains("mt5") & mt5_enabled)
| (plot_df["name"].str.contains("long-t5") & long_t5_enabled)
| (plot_df["name"].str.contains("t5_1_1") & t5_1_1_enabled)
| (
(
plot_df["name"].str.startswith("t5")
& ~plot_df["name"].str.startswith("t5_1_1")
)
& t5_v1_1_enabled
)
| (
plot_df["name"].str.contains("base")
& base_enabled
& ~plot_df["name"].str.contains("36")
)
| (
plot_df["name"].str.contains("small")
& small_enabled
& ~plot_df["name"].str.contains("24")
)
| (
plot_df["name"].str.contains("large")
& large_enabled
& ~plot_df["name"].str.contains("8")
)
| (
(
plot_df["name"].str.contains("-36L")
| plot_df["name"].str.contains("nl36")
)
& _36_enabled
)
| (
(
plot_df["name"].str.contains("-24L")
| plot_df["name"].str.contains("nl24")
)
& _24_enabled
)
| (
(plot_df["name"].str.contains("-8l") | plot_df["name"].str.contains("nl8"))
& _8l_enabled
)
| (
(plot_df["name"].str.contains("-4L") | plot_df["name"].str.contains("nl4"))
& _4xl_enabled
)
]
color_dict = {"flan": "red", "ul2": "blue", "mt5": "green", "t5_1_1": "orange"}
colors = [
color_dict[name.split("-")[0].lower()]
if name.split("-")[0].lower() in color_dict.keys()
else "black"
for name in plot_df["name"]
]
fig = plt.figure(figsize=(15, 8))
sns.set_style("darkgrid")
ax = sns.scatterplot(
data=plot_df,
y="en->nl Bleu",
x="summ Rouge1",
size="num params (M)",
hue=colors,
linewidth=0.7,
)
for i, row in plot_df.iterrows():
ax.annotate(
row["name"],
(row["summ Rouge1"], row["en->nl Bleu"]),
xytext=(0, 7),
textcoords="offset points",
ha="center",
va="center",
rotation=0,
)
# Remove color legend
handles, labels = ax.get_legend_handles_labels()
size_legend_labels = ["num params (M)"] + labels[-4:]
size_legend_handles = handles[-5:]
ax.legend(handles=size_legend_handles, labels=size_legend_labels)
plt.tight_layout()
st.pyplot(fig)
st.markdown(
"""* The `UL2` pre-trained Dutch(English) models consistently outperform the `T5-*` Dutch(English) models.
* Flan models perform almost instantly well on the summarization task, with `flan-t5-small`
showing performance comparable to Dutch T5 base models.
* For the translation task from English to Dutch, the Dutch+English pre-trained models perform well. Also
`UL2 Dutch` pre-trained Dutch models are consistently better than their `Flan`, `T5 Dutch` and
`mT5` counterparts of the comparable size.
* Fine-tuning of `t5-v1.1-large-dutch-cased` failed with the hyperparameters that were fixed to the same value for the
evaluation of every model.
Since the `UL2` models are better across the board, I've disabled this model on the hub.
* The `long-t5` models show bad performance on both tasks.
I cannot explain this, especially for the translation task. With a sequence length of 128 input and output
tokens, the sliding attention window with radius length 127 of the `long-t5` models should be able to handle this.
I've retried the fine-tuning of these models with
`float32` instead of `bfloat16`, but the results were the same. Maybe this is normal behaviour for these models
targeted at dealing with longer sequence lengths.
"""
)
st.markdown("### Compare generated texts")
col1, col2 = st.columns(2)
with col1:
summ_model_left = st.selectbox(
"Choose left summarization model", df["name"], index=6
)
with col2:
summ_model_right = st.selectbox(
"Choose right summarization model", df["name"], index=33
)
@st.cache_resource
def get_row(model):
return df[df["name"] == model]
row_left = get_row(summ_model_left)
row_right = get_row(summ_model_right)
contents1 = row_left["summary"].values[0].split("\n")
contents2 = row_right["summary"].values[0].split("\n")
contents = list(zip_longest(contents1, contents2))[:5]
st.table(
pd.DataFrame(
contents,
columns=[summ_model_left, summ_model_right],
)
)
st.markdown("### Compare generated translations")
col1, col2 = st.columns(2)
with col1:
trans_model_left = st.selectbox("Choose left model", df["name"], index=3)
with col2:
trans_model_right = st.selectbox("Choose right model", df["name"], index=32)
@st.cache_resource
def get_row(model):
return df[df["name"] == model]
row_left = get_row(trans_model_left)
row_right = get_row(trans_model_right)
contents1 = row_left["translation"].values[0].split("\n")
contents2 = row_right["translation"].values[0].split("\n")
contents = list(zip_longest(contents1, contents2))[:15]
st.table(
pd.DataFrame(
contents,
columns=[trans_model_left, trans_model_right],
)
)
st.markdown(
"""## Miscellaneous remarks
* Use loss regularization when training with `bfloat16` for better results (more info below).
* Be cautious of the dropout rate in the config.json file, as besides learning rate it is probably the most important
hyperparameter.
If you are evaluating different pre-trained models, be sure to fine-tune with dropout set equal.
Check in a model's `config.json` what the dropout rate has been set to. Unless you
intend to run many epochs on the same data, its worth to try a training run without dropout.
The smaller models can probably always be trained without.
* Training with more layers is much slower than you'd expect from the increased model size.
It is also more difficult to get batch size and learning rate right. Below is a section
about finding the right hyperparameters for the base-36L training.
* For the translation task, I am not sure that a 'deep-narrow' model (e.g. base-nl36) is better than a normal model
of comparable size (e.g. `large`).
* PyCharm's remote debugging features are useful to inspect variables on either a TPU VM or your deep-learning rig.
* When increasing the batch size, increase the learning rate. bs * 2 -> lr * sqrt(2) is a good heuristic but mileage may
vary.
* Dataset quality is a key success factor. Do not expect a model to magically turn mediocre data into magic. This holds for
the pre-training data, fine-tuning and also evaluating.
* Good Bleu score does not necessarily mean fluent text. Evaluation loss on a large translation dataset might be
better suited for model comparison, if the models have a tokenizer of comparable size.
### Bfloat16 datatype requires loss regularization
When training models with `bfloat16` and without loss regularization (default in the HuggingFace pre-training script),
the training losses would plateau or diverge. The graph below displays the results of different attempts
to train [t5-small-24L-dutch-english](https://huggingface.co./yhavinga/t5-small-24L-dutch-english).
The legend indicates the optimizer, data type, learning rate, total batch size, and learning rate schedule used.
As you can see, all attempts to train with `bfloat16` failed.
"""
)
st.image("img/bfloat16_loss.png", width=IMAGE_WIDTHS)
st.markdown(
"""The solution was found when peeking at T5X and the T5 gin configs, where I noticed a `z_loss` parameter,
always set to 1e-4. This factor is used in the T5X [cross entropy loss](https://github.com/google-research/t5x/blob/a319e559b4f72bffab91821487382ef4c25dfcf4/t5x/losses.py#L26)
function, with the purpose to pull the weights towards zero.
I experimented with adding this regularization term in the HF pre-training script,
and the `bfloat16` training runs did not exhibit the problems illustrated above anymore.
The `z_loss` regularization term in the T5X loss function looks like L2 regularization.
(See e.g. Andrej Karpathy [explaining regularization loss](https://youtu.be/PaCmpygFfXo?t=6720)).
The Optax optimizer library (used in the HuggingFace script), mentions weight decay for AdaFactor (and AdamW)
but also mentions that L2 regularization does not work as expected with adaptive gradient
algorithms. It might be the case that setting a non-zero `weight_decay_rate` in the Optax Adafactor call
in the HuggingFace pre-training script is an alternative to adding the `z_loss` term, to solve the bfloat16 issues, but
I haven't tested this yet.
"""
)
st.markdown(
"""### Which optimizer and lr to use
During the Flax/Jax Community week in '21, our team quickly decided on using Adafactor with learning rate 5e-3.
I believed that a more optimal setting could be found with more time.
After conducting seven WandB sweeps with
Adafactor, AdamW and Distributed Shampoo (experimental PJIT version from Dall-E mini),
a better setting had not been found. The graph below shows the runs from all 7 sweeps combined.
-- (I apologize for the confusion in the legend; I was unable to display the optimizer in the legend
because the initial version of the training script had the optimizer as a boolean, which I later
changed to a string with the optimizer name.) --
All runs in the graph below that achieve a loss below 4 use **Adafactor**.
Peach-sweep-6 is represented by a dashed orange line and had a learning rate of **5e-3**.
"""
)
st.image("img/adafactor_vs_adam_pretrain.png", width=IMAGE_WIDTHS)
st.markdown(
"""While there probably is a setting that will allow Adam and Shampoo to also converge fast below loss 4.0, I was unable
to find it. In a recent tweet Lucas Nestler had more success with Shampoo (https://twitter.com/_clashluke/status/1535994026876252160)
so maybe I need to revisit the attempt with the latest upstream code bases.
Later, when pre-training with T5X, I found that its custom Adafactor implementation with the default settings of the T5X gin configs,
a learning rate of 0.001 and inverse square root learning rate decay, worked well.
"""
)
st.markdown(
"""### Optimizer and learning rate used for summarization
Finetuning summarization requires more memory than translation due to the longer sequence lengths involved.
I wondered if I could use Adafactor instead of Adam and ran
a sweep to test this. The sweep was configured with Hyperband, so not all training runs completed to the end.
"""
)
st.image("img/optim_lr_summarization.png", width=IMAGE_WIDTHS)
st.markdown(
"""The training losses are graphed below:
"""
)
st.image("img/training_losses_summarization_sweep.png", width=IMAGE_WIDTHS)
st.markdown(
"""
While the Adafactor run with learning rate 7e-4 came close to the Adam runs, the consistent stability of training with Adam
made me stick with Adam as optimizer for evaluation runs on the several models. For translation the results were similar, though in the end I needed to configure a lower learning rate for all
models to converge during fine-tuning.
"""
)
st.markdown(
"""### Pre-training with sequence length 512 or 1024
The models `t5-v1_1-base-dutch-english-cased` and `t5-v1_1-base-dutch-english-cased-1024` have the same model dimensions,
but are pre-trained with span corruption on different sequence lenghts, 512 and 1024 respectively.
The evaluation loss and accuracy of the models do not look too different. Since training of the 1024 sequence length model was
very slow and didn't converge, I stopped it early. The figure below shows the evaluation
loss and accuracy.
"""
)
st.image("img/t5v1_1eval_loss_and_accuracy.png", width=IMAGE_WIDTHS)
st.markdown(
"""The 512 sequence length model was trained for 10 epochs of the `small` nl+en config (186B tokens total) and the 1024
sequence length model about 2 epochs of the `large` nl+en config (100B tokens total). While I expected both models to
perform similarly on downstream tasks, the 1024 sequence length model has better scores for both
summarization and translation.
"""
)
st.markdown(
"""## Model lists
### UL2 Dutch English
These models have been trained with T5X on mc4_nl_cleaned, books, Wikipedia and news.
| | ul2-base-dutch-english | ul2-large-dutch-english | ul2-small-dutch-english |
|:---------------------|:-------------------------|:--------------------------|:--------------------------|
| model_type | t5 | t5 | t5 |
| _pipeline_tag | text2text-generation | text2text-generation | text2text-generation |
| d_model | 768 | 1024 | 512 |
| d_ff | 2048 | 2816 | 1024 |
| num_heads | 12 | 16 | 6 |
| d_kv | 64 | 64 | 64 |
| num_layers | 12 | 24 | 8 |
| num_decoder_layers | 12 | 24 | 8 |
| feed_forward_proj | gated-gelu | gated-gelu | gated-gelu |
| dense_act_fn | gelu_new | gelu_new | gelu_new |
| vocab_size | 32128 | 32128 | 32128 |
| tie_word_embeddings | 0 | 0 | 0 |
| torch_dtype | float32 | float32 | float32 |
| _gin_batch_size | 128 | 64 | 128 |
| _gin_z_loss | 0.0001 | 0.0001 | 0.0001 |
| _gin_t5_config_dtype | 'bfloat16' | 'bfloat16' | 'bfloat16' |
### UL2 Dutch
These models have been trained with T5X on mc4_nl_cleaned, books, Wikipedia and news.
| | ul2-base-dutch | ul2-base-nl36-dutch | ul2-large-dutch | ul2-small-dutch |
|:---------------------|:---------------------|:----------------------|:---------------------|:---------------------|
| model_type | t5 | t5 | t5 | t5 |
| _pipeline_tag | text2text-generation | text2text-generation | text2text-generation | text2text-generation |
| d_model | 768 | 768 | 1024 | 512 |
| d_ff | 2048 | 3072 | 2816 | 1024 |
| num_heads | 12 | 12 | 16 | 6 |
| d_kv | 64 | 64 | 64 | 64 |
| num_layers | 12 | 36 | 24 | 8 |
| num_decoder_layers | 12 | 36 | 24 | 8 |
| feed_forward_proj | gated-gelu | gated-gelu | gated-gelu | gated-gelu |
| dense_act_fn | gelu_new | gelu_new | gelu_new | gelu_new |
| vocab_size | 32128 | 32128 | 32128 | 32128 |
| tie_word_embeddings | 0 | 0 | 0 | 0 |
| torch_dtype | float32 | float32 | float32 | float32 |
| _gin_batch_size | 128 | 64 | 64 | 128 |
| _gin_z_loss | 0.0001 | 0.0001 | 0.0001 | 0.0001 |
| _gin_t5_config_dtype | 'bfloat16' | 'bfloat16' | 'bfloat16' | 'bfloat16' |
### T5 models Dutch and Dutch/English
These models have been trained with the HuggingFace π€ run_t5_mlm_flax.py script on mc4_nl_cleaned.
Most notable differences are the model sizes, activation function, and the dropout rate used during
pre-training. The T5-eff models are models that differ in their number of layers. The table will list
the several dimensions of these models.
| | [t5-base-dutch](https://huggingface.co./yhavinga/t5-base-dutch) | [t5-v1.1-base-dutch-uncased](https://huggingface.co./yhavinga/t5-v1.1-base-dutch-uncased) | [t5-v1.1-base-dutch-cased](https://huggingface.co./yhavinga/t5-v1.1-base-dutch-cased) | [t5-v1.1-large-dutch-cased](https://huggingface.co./yhavinga/t5-v1.1-large-dutch-cased) | [t5-v1_1-base-dutch-english-cased](https://huggingface.co./yhavinga/t5-v1_1-base-dutch-english-cased) | [t5-v1_1-base-dutch-english-cased-1024](https://huggingface.co./yhavinga/t5-v1_1-base-dutch-english-cased-1024) | [t5-small-24L-dutch-english](https://huggingface.co./yhavinga/t5-small-24L-dutch-english) | [t5-xl-4L-dutch-english-cased](https://huggingface.co./yhavinga/t5-xl-4L-dutch-english-cased) | [t5-base-36L-dutch-english-cased](https://huggingface.co./yhavinga/t5-base-36L-dutch-english-cased) | [t5-eff-xl-8l-dutch-english-cased](https://huggingface.co./yhavinga/t5-eff-xl-8l-dutch-english-cased) | [t5-eff-large-8l-dutch-english-cased](https://huggingface.co./yhavinga/t5-eff-large-8l-dutch-english-cased) |
|:------------------|:----------------|:-----------------------------|:---------------------------|:----------------------------|:-----------------------------------|:----------------------------------------|:-----------------------------|:-------------------------------|:----------------------------------|:-----------------------------------|:--------------------------------------|
| *type* | t5 | t5-v1.1 | t5-v1.1 | t5-v1.1 | t5-v1.1 | t5-v1.1 | t5 eff | t5 eff | t5 eff | t5 eff | t5 eff |
| *d_model* | 768 | 768 | 768 | 1024 | 768 | 768 | 512 | 2048 | 768 | 1024 | 1024 |
| *d_ff* | 3072 | 2048 | 2048 | 2816 | 2048 | 2048 | 1920 | 5120 | 2560 | 16384 | 4096 |
| *num_heads* | 12 | 12 | 12 | 16 | 12 | 12 | 8 | 32 | 12 | 32 | 16 |
| *d_kv* | 64 | 64 | 64 | 64 | 64 | 64 | 64 | 64 | 64 | 128 | 64 |
| *num_layers* | 12 | 12 | 12 | 24 | 12 | 12 | 24 | 4 | 36 | 8 | 8 |
| *num parameters* | 223M | 248M | 248M | 783M | 248M | 248M | 250M | 585M | 729M | 1241M | 335M |
| *feed_forward_proj* | relu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu | gated-gelu |
| *dropout* | 0.1 | 0.0 | 0.0 | 0.1 | 0.0 | 0.0 | 0.0 | 0.1 | 0.0 | 0.0 | 0.0 |
| *dataset* | mc4_nl_cleaned | mc4_nl_cleaned full | mc4_nl_cleaned full | mc4_nl_cleaned | mc4_nl_cleaned small_en_nl | mc4_nl_cleaned large_en_nl | mc4_nl_cleaned large_en_nl | mc4_nl_cleaned large_en_nl | mc4_nl_cleaned large_en_nl | mc4_nl_cleaned large_en_nl | mc4_nl_cleaned large_en_nl |
| *tr. seq len* | 512 | 1024 | 1024 | 512 | 512 | 1024 | 512 | 512 | 512 | 512 | 512 |
| *batch size* | 128 | 64 | 64 | 64 | 128 | 64 | 128 | 512 | 512 | 64 | 128 |
| *total steps* | 527500 | 1014525 | 1210154 | 1120k/2427498 | 2839630 | 1520k/3397024 | 851852 | 212963 | 212963 | 538k/1703705 | 851850 |
| *epochs* | 1 | 2 | 2 | 2 | 10 | 4 | 1 | 1 | 1 | 1 | 1 |
| *duration* | 2d9h | 5d5h | 6d6h | 8d13h | 11d18h | 9d1h | 4d10h | 6d1h | 17d15h | 4d 19h | 3d 23h |
| *optimizer* | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor | adafactor |
| *lr* | 0.005 | 0.005 | 0.005 | 0.005 | 0.005 | 0.005 | 0.005 | 0.005 | 0.009 | 0.005 | 0.005 |
| *warmup* | 10000.0 | 10000.0 | 10000.0 | 10000.0 | 10000.0 | 5000.0 | 20000.0 | 2500.0 | 1000.0 | 1500.0 | 1500.0 |
| *eval loss* | 1,38 | 1,20 | 0,96 | 1,07 | 1,11 | 1,13 | 1,18 | 1,27 | 1,05 | 1,3019 | 1,15 |
| *eval acc* | 0,70 | 0,73 | 0,78 | 0,76 | 0,75 | 0,74 | 0,74 | 0,72 | 0,76 | 0,71 | 0,74 |
### Fine-tuned translation models on ccmatrix
The models `t5-small-24L-dutch-english` and `t5-base-36L-dutch-english` have been fine-tuned for both language
directions on the first 25M samples from CCMatrix, giving a total of 50M training samples.
Evaluation is performed on out-of-sample CCMatrix and also on Tatoeba and Opus Books.
The `_bp` columns list the *brevity penalty* (the low score of the 128 seq len models on opus books may be because of the brevity penalty;
books tend to have longer sentences than 128 tokens). The `avg_bleu` score is the bleu score
averaged over all three evaluation datasets. The best scores displayed in bold for both translation directions.
| | [t5-base-36L-ccmatrix-multi](https://huggingface.co./yhavinga/t5-base-36L-ccmatrix-multi) | [t5-base-36L-ccmatrix-multi](https://huggingface.co./yhavinga/t5-base-36L-ccmatrix-multi) | [t5-small-24L-ccmatrix-multi](https://huggingface.co./yhavinga/t5-small-24L-ccmatrix-multi) | [t5-small-24L-ccmatrix-multi](https://huggingface.co./yhavinga/t5-small-24L-ccmatrix-multi) |
|:-----------------------|:-----------------------------|:-----------------------------|:------------------------------|:------------------------------|
| *source_lang* | en | nl | en | nl |
| *target_lang* | nl | en | nl | en |
| *source_prefix* | translate English to Dutch: | translate Dutch to English: | translate English to Dutch: | translate Dutch to English: |
| *ccmatrix_bleu* | **56.8** | 62.8 | 57.4 | **63.1** |
| *tatoeba_bleu* | **46.6** | **52.8** | 46.4 | 51.7 |
| *opus_books_bleu* | **13.5** | **24.9** | 12.9 | 23.4 |
| *ccmatrix_bp* | 0.95 | 0.96 | 0.95 | 0.96 |
| *tatoeba_bp* | 0.97 | 0.94 | 0.98 | 0.94 |
| *opus_books_bp* | 0.8 | 0.94 | 0.77 | 0.89 |
| *avg_bleu* | **38.96** | **46.86** | 38.92 | 46.06 |
| *max_source_length* | 128 | 128 | 128 | 128 |
| *max_target_length* | 128 | 128 | 128 | 128 |
| *adam_beta1* | 0.9 | 0.9 | 0.9 | 0.9 |
| *adam_beta2* | 0.997 | 0.997 | 0.997 | 0.997 |
| *weight_decay* | 0.05 | 0.05 | 0.002 | 0.002 |
| *lr* | 5e-05 | 5e-05 | 0.0005 | 0.0005 |
| *label_smoothing_factor* | 0.15 | 0.15 | 0.1 | 0.1 |
| *train_batch_size* | 128 | 128 | 128 | 128 |
| *warmup_steps* | 2000 | 2000 | 2000 | 2000 |
| *total steps* | 390625 | 390625 | 390625 | 390625 |
| *duration* | 4d 5h | 4d 5h | 3d 2h | 3d 2h |
| *num parameters* | 729M | 729M | 250M | 250M |
## Acknowledgements
This project was made possible by the exceptional computing resources provided by Google's
[TPU Research Cloud](https://sites.research.google/trc/).
The HuggingFace π€ ecosystem of datasets, hub, model architectures
and example scripts were an integral part of the training process, while Weights & Biases provided the ability
to track multiple training sessions and execute hyperparameter optimization with insightful visualizations.
I am grateful to the [https://huggingface.co./Finnish-NLP](Finnish-NLP) authors for their generosity in releasing the UL2 objective code and task
definitions, and to [Stephenn Fernandes](https://huggingface.co./StephennFernandes) for his support in getting me started with the T5X framework.
Lastly, I want to express my gratitude to Google for their openness and generosity in releasing T5X and related repositories.
Created by [Yeb Havinga](https://www.linkedin.com/in/yeb-havinga-86530825/).
Some of the sentences were reworded by ChatGPT.
"""
)
st.write(
f"""
---
*Memory: {memory.total / 10**9:.2f}GB, used: {memory.percent}%, available: {memory.available / 10**9:.2f}GB*
"""
)
if __name__ == "__main__":
memory = psutil.virtual_memory()
main()
|