Natural Language Processing with Deep Learning CS224N/Ling284 Anna Goldie Lecture 10: Pretraining Slides coauthored with John Hewitt Breaking (Transformer) News! AlphaCode (a pre-trained Transformer-based code generation model) achieved a top 54.3% rating on Codeforces programming competitions! [Li et al., 2022] More Breaking (Transformer) News! [Polu et al., 2022] Pre-Trained Transformer-Based theorem prover sets new state-of-the-art (41.2% vs. 29.3%) on a collection of challenging math Olympiad questions (miniF2F)! Lecture Plan 1. Quick review of Transformer model 2. Brief note on subword modeling 3. Motivating model pretraining from word embeddings 4. Model pretraining three ways 1. Decoders 2. Encoders 3. Encoder-Decoders 5. Very large models and in-context learning Reminders: Assignment 5 is out today! It covers Lecture 9 (Tuesday) and Lecture 10 (Today)! Hugging Face Transformers Tutorial Session on Friday 1:30-2:30pm (Thornton 102 and recorded)! 4 The Transformer Encoder-Decoder [Vaswani et al., 2017] Transformer Encoder Word Embeddings Position Representations + Transformer Encoder [input sequence] Transformer Decoder Word Embeddings Position Representations + Transformer Decoder [output sequence] [decoder attends to encoder states] Looking back at the whole model, zooming in on an Encoder block: [predictions!] 5 The Transformer Encoder-Decoder [Vaswani et al., 2017] Word Embeddings Position Representations + Transformer Encoder [input sequence] Transformer Decoder Word Embeddings Position Representations + Transformer Decoder [output sequence] [decoder attends to encoder states] Looking back at the whole model, zooming in on an Encoder block: [predictions!] Multi-Head Attention Residual + LayerNorm Feed-Forward Residual + LayerNorm 6 The Transformer Encoder-Decoder [Vaswani et al., 2017] Transformer Encoder Word Embeddings Position Representations + Transformer Encoder [input sequence] Word Embeddings Position Representations + Transformer Decoder [output sequence] Looking back at the whole model, zooming in on a Decoder block: [predictions!] Residual + LayerNorm Multi-Head Cross-Attention Masked Multi-Head Self-Attention Residual + LayerNorm Feed-Forward Residual + LayerNorm 7 Lecture Plan 1. Quick review of Transformer model 2. Brief note on subword modeling 3. Motivating model pretraining from word embeddings 4. Model pretraining three ways 1. Decoders 2. Encoders 3. Encoder-Decoders 5. Very large models and in-context learning 8 Word structure and subword models Let’s take a look at the assumptions we’ve made about a language’s vocabulary. We assume a fixed vocab of tens of thousands of words, built from the training set. All novel words seen at test time are mapped to a single UNK. word vocab mapping embedding hat à hat learn à learn taaaaasty à UNK laern à UNK Transformerify à UNK 9 Common words Variations misspellings novel items Word structure and subword models Finite vocabulary assumptions make even less sense in many languages. • Many languages exhibit complex morphology, or word structure. • The effect is more word types, each occurring fewer times. 10 Example: Swahili verbs can have hundreds of conjugations, each encoding a wide variety of information. (Tense, mood, definiteness, negation, information about the object, ++) Here’s a small fraction of the conjugations for ambia – to tell. [Wiktionary] The byte-pair encoding algorithm Subword modeling in NLP encompasses a wide range of methods for reasoning about structure below the word level. (Parts of words, characters, bytes.) • The dominant modern paradigm is to learn a vocabulary of parts of words (subword tokens). • At training and testing time, each word is split into a sequence of known subwords. Byte-pair encoding is a simple, effective strategy for defining a subword vocabulary. 1. Start with a vocabulary containing only characters and an “end-of-word” symbol. 2. Using a corpus of text, find the most common pair of adjacent characters “a,b”; add subword “ab” to the vocab. 3. Replace instances of the character pair with the new subword; repeat until desired vocab size. Originally used in NLP for machine translation; now a similar method (WordPiece) is used in pretrained models. 11 [Sennrich et al., 2016, Wu et al., 2016] Word structure and subword models Common words end up being a part of the subword vocabulary, while rarer words are split into (sometimes intuitive, sometimes not) components. In the worst case, words are split into as many subwords as they have characters. word vocab mapping embedding hat à hat learn à learn taaaaasty à taa## aaa## sty laern à la## ern Transformerify à Transformer## ify 12 Common words Variations misspellings novel items Outline 1. Quick review of Transformer models 2. Brief note on subword modeling 3. Motivating model pretraining from word embeddings 4. Model pretraining three ways 1. Decoders 2. Encoders 3. Encoder-Decoders 5. Very large models and in-context learning 13 Motivating word meaning and context Recall the adage we mentioned at the beginning of the course: “You shall know a word by the company it keeps” (J. R. Firth 1957: 11) This quote is a summary of distributional semantics, and motivated word2vec. But: “… the complete meaning of a word is always contextual, and no study of meaning apart from a complete context can be taken seriously.” (J. R. Firth 1935) Consider I record the record: the two instances of record mean different things. 14 [Thanks to Yoav Goldberg on Twitter for pointing out the 1935 Firth quote.] Where we were: pretrained word embeddings Circa 2017: • Start with pretrained word embeddings (no context!) • Learn how to incorporate context in an LSTM or Transformer while training on the task. Some issues to think about: • The training data we have for our downstream task (like question answering) must be sufficient to teach all contextual aspects of language. • Most of the parameters in our network are randomly initialized! 15 … the movie was … !𝒚 Not pretrained pretrained (word embeddings) [Recall, movie gets the same word embedding, no matter what sentence it shows up in] Where we’re going: pretraining whole models In modern NLP: • All (or almost all) parameters in NLP networks are initialized via pretraining. • Pretraining methods hide parts of the input from the model, and then train the model to reconstruct those parts. • This has been exceptionally effective at building strong: • representations of language • parameter initializations for strong NLP models. • probability distributions over language that we can sample from 16 … the movie was … !𝒚 Pretrained jointly [This model has learned how to represent entire sentences through pretraining] What can we learn from reconstructing the input? 17 Stanford University is located in __________, California. What can we learn from reconstructing the input? 18 I put ___ fork down on the table. What can we learn from reconstructing the input? 19 The woman walked across the street, checking for traffic over ___ shoulder. What can we learn from reconstructing the input? 20 I went to the ocean to see the fish, turtles, seals, and _____. What can we learn from reconstructing the input? 21 Overall, the value I got from the two hours watching it was the sum total of the popcorn and the drink. The movie was ___. What can we learn from reconstructing the input? 22 Iroh went into the kitchen to make some tea. Standing next to Iroh, Zuko pondered his destiny. Zuko left the ______. What can we learn from reconstructing the input? 23 I was thinking about the sequence that goes 1, 1, 2, 3, 5, 8, 13, 21, ____ Pretraining through language modeling [Dai and Le, 2015] Recall the language modeling task: • Model 𝑝! 𝑤" 𝑤#:"%#), the probability distribution over words given their past contexts. • There’s lots of data for this! (In English.) Pretraining through language modeling: • Train a neural network to perform language modeling on a large amount of text. • Save the network parameters. 24 Decoder (Transformer, LSTM, ++ ) Iroh goes to make tasty tea goes to make tasty tea END The Pretraining / Finetuning Paradigm Pretraining can improve NLP applications by serving as parameter initialization. 25 Decoder (Transformer, LSTM, ++ ) Iroh goes to make tasty tea goes to make tasty tea END Step 1: Pretrain (on language modeling) Lots of text; learn general things! Decoder (Transformer, LSTM, ++ ) J/L Step 2: Finetune (on your task) Not many labels; adapt to the task! … the movie was … Lecture Plan 1. A brief note on subword modeling 2. Motivating model pretraining from word embeddings 3. Model pretraining three ways 1. Decoders 2. Encoders 3. Encoder-Decoders 4. Very large models and in-context learning 26 Pretraining for three types of architectures The neural architecture influences the type of pretraining, and natural use cases. 27 Decoders • Language models! What we’ve seen so far. • Nice to generate from; can’t condition on future words • Examples: GPT-2, GPT-3, LaMDA Encoders • Gets bidirectional context – can condition on future! • Wait, how do we pretrain them? • Examples: BERT and its many variants, e.g. RoBERTa Encoder- Decoders • Good parts of decoders and encoders? • What’s the best way to pretrain them? • Examples: Transformer, T5, Meena Pretraining for three types of architectures The neural architecture influences the type of pretraining, and natural use cases. 28 Decoders • Language models! What we’ve seen so far. • Nice to generate from; can’t condition on future words • Examples: GPT-2, GPT-3, LaMDA Encoders • Gets bidirectional context – can condition on future! • Wait, how do we pretrain them? • Examples: BERT and its many variants, e.g. RoBERTa Encoder- Decoders • Good parts of decoders and encoders? • What’s the best way to pretrain them? • Examples: Transformer, T5, Meena ℎ!, … , ℎ" Pretraining decoders When using language model pretrained decoders, we can ignore that they were trained to model 𝑝 𝑤" 𝑤#:"%#). 29 We can finetune them by training a classifier on the last word’s hidden state. ℎ#, … , ℎ& = Decoder 𝑤#, … , 𝑤& 𝑦 ∼ 𝐴ℎ& + 𝑏 Where 𝐴 and 𝑏 are randomly initialized and specified by the downstream task. Gradients backpropagate through the whole network. J/L 𝑤!, … , 𝑤" Linear 𝐴, 𝑏 [Note how the linear layer hasn’t been pretrained and must be learned from scratch.] Pretraining decoders It’s natural to pretrain decoders as language models and then use them as generators, finetuning their 𝑝! 𝑤" 𝑤#:"%#)! 30 This is helpful in tasks where the output is a sequence with a vocabulary like that at pretraining time! • Dialogue (context=dialogue history) • Summarization (context=document) ℎ#, … , ℎ& = Decoder 𝑤#, … , 𝑤& 𝑤" ∼ 𝐴ℎ"%# + 𝑏 Where 𝐴, 𝑏 were pretrained in the language model! 𝑤' 𝑤( 𝑤) 𝑤* 𝑤+ [Note how the linear layer has been pretrained.] 𝐴, 𝑏 ℎ!, … , ℎ" 𝑤# 𝑤' 𝑤( 𝑤) 𝑤* Generative Pretrained Transformer (GPT) [Radford et al., 2018] 2018’s GPT was a big success in pretraining a decoder! • Transformer decoder with 12 layers. • 768-dimensional hidden states, 3072-dimensional feed-forward hidden layers. • Byte-pair encoding with 40,000 merges • Trained on BooksCorpus: over 7000 unique books. • Contains long spans of contiguous text, for learning long-distance dependencies. 31 [Devlin et al., 2018] Generative Pretrained Transformer (GPT) [Radford et al., 2018] How do we format inputs to our decoder for finetuning tasks? The linear classifier is applied to the representation of the [EXTRACT] token. Generative Pretrained Transformer (GPT) [Radford et al., 2018] GPT results on various natural language inference datasets. 33 Examining the Effect of Pretraining in GPT [Radford et al., 2018] As more layers are transferred, performance improves on RACE (a largescale reading comprehension dataset) and MultiNLI. Zero-shot performance of Transformer vs. LSTM as a function of the # of pre-training updates. We mentioned how pretrained decoders can be used in their capacities as language models. GPT-2, a larger version of GPT trained on more data, was shown to produce relatively convincing samples of natural language. Increasingly convincing generations (GPT2) [Radford et al., 2018] Pretraining for three types of architectures The neural architecture influences the type of pretraining, and natural use cases. 36 Decoders • Language models! What we’ve seen so far. • Nice to generate from; can’t condition on future words • Examples: GPT-2, GPT-3, LaMDA Encoders • Gets bidirectional context – can condition on future! • Wait, how do we pretrain them? • Examples: BERT and its many variants, e.g. RoBERTa Encoder- Decoders • Good parts of decoders and encoders? • What’s the best way to pretrain them? • Examples: Transformer, T5, Meena ℎ!, … , ℎ" Pretraining encoders: what pretraining objective to use? So far, we’ve looked at language model pretraining. But encoders get bidirectional context, so we can’t do language modeling! 37 Idea: replace some fraction of words in the input with a special [MASK] token; predict these words. Only add loss terms from words that are “masked out.” If 3𝑥 is the masked version of 𝑥, we’re learning 𝑝!(𝑥|3𝑥). Called Masked LM. I [M] to the [M] went store 𝐴, 𝑏 [Devlin et al., 2018] BERT: Bidirectional Encoder Representations from Transformers Devlin et al., 2018 proposed the “Masked LM” objective, open-sourced their model as the tensor2tensor library, and released the weights of their pretrained Transformer (BERT). 38 Some more details about Masked LM for BERT: • Predict a random 15% of (sub)word tokens. • Replace input word with [MASK] 80% of the time • Replace input word with a random token 10% of the time • Leave input word unchanged 10% of the time (but still predict it!) • Why? Doesn’t let the model get complacent and not build strong representations of non-masked words. (No masks are seen at fine-tuning time!) [Predict these!] I pizza to the [M] went store Transformer Encoder [Devlin et al., 2018] to [Masked][Replaced] [Not replaced] BERT: Bidirectional Encoder Representations from Transformers • Unified Architecture: As shown below, there are minimal differences between the pre-training architecture and the fine-tuned version for each downstream task. [Devlin et al., 2018] BERT: Bidirectional Encoder Representations from Transformers 40 • The pretraining input to BERT was two separate contiguous chunks of text: • BERT was trained to predict whether one chunk follows the other or is randomly sampled. • Later work has argued this “next sentence prediction” is not necessary. [Devlin et al., 2018, Liu et al., 2019] BERT: Bidirectional Encoder Representations from Transformers Details about BERT • Two models were released: • BERT-base: 12 layers, 768-dim hidden states, 12 attention heads, 110 million params. • BERT-large: 24 layers, 1024-dim hidden states, 16 attention heads, 340 million params. • Trained on: • BooksCorpus (800 million words) • English Wikipedia (2,500 million words) • Pretraining is expensive and impractical on a single GPU. • BERT was pretrained with 64 TPU chips for a total of 4 days. • (TPUs are special tensor operation acceleration hardware) • Finetuning is practical and common on a single GPU • “Pretrain once, finetune many times.” 41 [Devlin et al., 2018] BERT: Bidirectional Encoder Representations from Transformers BERT was massively popular and hugely versatile; finetuning BERT led to new state-ofthe-art results on a broad range of tasks. 42 • QQP: Quora Question Pairs (detect paraphrase questions) • QNLI: natural language inference over question answering data • SST-2: sentiment analysis • CoLA: corpus of linguistic acceptability (detect whether sentences are grammatical.) • STS-B: semantic textual similarity • MRPC: microsoft paraphrase corpus • RTE: a small natural language inference corpus [Devlin et al., 2018]Note that BERTBASE was chosen to have the same number of parameters as OpenAI GPT. Limitations of pretrained encoders Those results looked great! Why not used pretrained encoders for everything? 43 If your task involves generating sequences, consider using a pretrained decoder; BERT and other pretrained encoders don’t naturally lead to nice autoregressive (1-word-at-a-time) generation methods. Pretrained Encoder Iroh goes to [MASK] tasty tea make/brew/craft Pretrained Decoder Iroh goes to make tasty tea goes to make tasty tea END Extensions of BERT You’ll see a lot of BERT variants like RoBERTa, SpanBERT, +++ 44 Some generally accepted improvements to the BERT pretraining formula: • RoBERTa: mainly just train BERT for longer and remove next sentence prediction! • SpanBERT: masking contiguous spans of words makes a harder, more useful pretraining task [Liu et al., 2019; Joshi et al., 2020] BERT [MASK] irr## esi## sti## [MASK] good It’s SpanBERT bly It’ [MASK] good irr## esi## sti## bly [MASK][MASK][MASK] Extensions of BERT A takeaway from the RoBERTa paper: more compute, more data can improve pretraining even when not changing the underlying Transformer encoder. 45 [Liu et al., 2019; Joshi et al., 2020] Pretraining for three types of architectures The neural architecture influences the type of pretraining, and natural use cases. 46 Decoders • Language models! What we’ve seen so far. • Nice to generate from; can’t condition on future words • Examples: GPT-2, GPT-3, LaMDA Encoders • Gets bidirectional context – can condition on future! • Wait, how do we pretrain them? • Examples: BERT and its many variants, e.g. RoBERTa Encoder- Decoders • Good parts of decoders and encoders? • What’s the best way to pretrain them? • Examples: Transformer, T5, Meena Pretraining encoder-decoders: what pretraining objective to use? For encoder-decoders, we could do something like language modeling, but where a prefix of every input is provided to the encoder and is not predicted. 47 ℎ#, … , ℎ& = Encoder 𝑤#, … , 𝑤& ℎ&,#, … , ℎ' = 𝐷𝑒𝑐𝑜𝑑𝑒𝑟 𝑤#, … , 𝑤&, ℎ#, … , ℎ& 𝑦- ∼ 𝐴𝑤- + 𝑏, 𝑖 > 𝑇 The encoder portion benefits from bidirectional context; the decoder portion is used to train the whole model through language modeling. [Raffel et al., 2018] 𝑤B, … , 𝑤C 𝑤CDB, … , 𝑤EC 𝑤CDE, … , Pretraining encoder-decoders: what pretraining objective to use? What Raffel et al., 2018 found to work best was span corruption. Their model: T5. 48 Replace different-length spans from the input with unique placeholders; decode out the spans that were removed! This is implemented in text preprocessing: it’s still an objective that looks like language modeling at the decoder side. [Raffel et al., 2018] Pretraining encoder-decoders: what pretraining objective to use? Raffel et al., 2018 found encoder-decoders to work better than decoders for their tasks, and span corruption (denoising) to work better than language modeling. [Raffel et al., 2018] Pretraining encoder-decoders: what pretraining objective to use? A fascinating property of T5: it can be finetuned to answer a wide range of questions, retrieving knowledge from its parameters. NQ: Natural Questions WQ: WebQuestions TQA: Trivia QA All “open-domain” versions [Raffel et al., 2018] 220 million params 770 million params 3 billion params 11 billion params Outline 1. Prelude: A brief note on subword modeling 2. Motivating model pretraining from word embeddings 3. Model pretraining three ways 1. Decoders 2. Encoders 3. Encoder-Decoders 4. Very large models and in-context learning 51 GPT-3, In-context learning, and very large models So far, we’ve interacted with pretrained models in two ways: • Sample from the distributions they define (maybe providing a prompt) • Fine-tune them on a task we care about, and then take their predictions. Emergent behavior: Very large language models seem to perform some kind of learning without gradient steps simply from examples you provide within their contexts. GPT-3 is the canonical example of this. The largest T5 model had 11 billion parameters. GPT-3 has 175 billion parameters. 52 GPT-3, In-context learning, and very large models Very large language models seem to perform some kind of learning without gradient steps simply from examples you provide within their contexts. The in-context examples seem to specify the task to be performed, and the conditional distribution mocks performing the task to a certain extent. Input (prefix within a single Transformer decoder context): “ thanks -> merci hello -> bonjour mint -> menthe otter -> ” Output (conditional generations): loutre…” 53 GPT-3, In-context learning, and very large models Very large language models seem to perform some kind of learning without gradient steps simply from examples you provide within their contexts. 54 Parting remarks • We learned about GPT-X, BERT, T5 and other large pre-trained language models • Emergent in-context learning is not yet well-understood! • “Small” models like BERT have become general tools in a wide range of settings. • Many issues left to explore! • Bias, toxicity, and fairness (Guest Lecturer: Maarten Sap) • Retrieval Augmented Language Models + Knowledge (Guest Lecturer: Kelvin Guu) • Scaling Laws (Guest Lecturer: Jared Kaplan) • Assignment 5 out today! It covers material from Tuesday’s and today’s lectures. • Hugging Face Transformers Tutorial Session on Friday 1:30-2:30pm (Thornton 102 and recorded)! 55