1 of 78

Pretraining-Finetuning Paradigm�

Somak Aditya

Assistant Professor

Department of CSE, IIT Kharagpur

Slide Courtesy: Prof. Chris Manning, Prof. Li Fei Fei, Prof. Yunzhu Li, Prof. Ruohan Gao (Stanford Univ)

2 of 78

Pre-training

  • What is Pretraining?
  • Pretrained LSTMs: ELMo
  • Pretraining Transformers: BERT and Large Language Models

​

3 of 78

 

4 of 78

The idea of transfer learning

Examples of popular

pre-trained Language Models

What has made Transformers popular is that they can be combined with the idea of transfer learning.

  • Train model in one task T (where labelled data is abundant)
  • Use the trained model as a starting point for another task (where labels are scarce)

​

Transformers have become the go-to model for building large pretrained language models which can be adapted for several tasks

5 of 78

The pretraining revolution

Pretraining has had a major, tangible impact on how well NLP systems work

6 of 78

Standard Supervised Deep Learning

Labeling a sizeable dataset needs a lot of effort / time.

​

Every new learning problem needs labeling of a new dataset

+

+

text + labels

neural network starting from random weights

(not) spam

7 of 78

Why is this an issue

Randomly initialized

Word Vectors

The training data for our downstream task (like question answering) must be sufficient to teach all contextual aspects of language, and train millions of parameters.

Authors train Large Deep Neural Nets (CNNs) on the Object detection “train2017 set” and evaluate bounding box AP on the “val2017 set”,

  • initializing the model by random weights or “ImageNet” pre-training.
  • We explore different training schedules by varying the iterations at which the learning rate is reduced (where the accuracy leaps).
  • The model trained from random initialization needs more iterations to converge, but converges to a solution that is no worse than the finetuning counterpart.

8 of 78

Abundance of domain-specific NLP Applications

Very difficult to get sufficient labeled data for each task

9 of 78

NLP: The Standard Pipeline

Prof. Somak Aditya, IIT KGP, SSAI 25

Language Modeling

(Pre-training)

Downstream Tasks

(Fine-Tuning)

Raw (unlabeled) Text

Samples and Labels

(Opt: Instructions)

Advantage: Achieves SOTA

Does it with much less fewer

labels

Slide Courtesy: Prof. Mitesh Khapra, IITM

Next word prediction

(unsupervised)

Standard supervised tasks

Sequence labeling tasks

Random Weights (W)

 

 

 

10 of 78

Transfer Learning with Language Modeling

11 of 78

Self-supervised training algorithm

We just train them to predict the next word!

  1. Take a corpus of text
  2. At each time step t
    1. Ask the model to predict the next word (loss function?)
    2. Train the model using gradient descent to minimize the error in this prediction

​

"Self-supervised" because it just uses the next word as the label!

​

Prof. Somak Aditya, IIT KGP, SSAI 25

12 of 78

Intuition of language model training: loss

  •  

Prof. Somak Aditya, IIT KGP, SSAI 25

13 of 78

Other Pretraining Objectives

  • Causal Language Modeling (CLM)
    • Predict the next word given all previous words
  • Masked Language Modeling
    • Encoders in Transformer
    • Mask “some” words. Replace with [MASK] token. Predict actual word.
  • Next sentence prediction
    • Encoder, decoder
    • Predict next sentence word by word

Prof. Somak Aditya, IIT KGP, SSAI 25

14 of 78

What does a model learn from pretraining?

Some claim: Apparently everything

Empirically: Syntax, Syntactic dependencies, Semantics, (and some) commonsense knowledge

Prof. Somak Aditya, IIT KGP, SSAI 25

To a Limited

extent

15 of 78

What the model does NOT learn from pretraining…

Prof. Somak Aditya, IIT KGP, SSAI 25

And many more types of reasoning ….

16 of 78

Big idea

  • Text contains enormous amounts of knowledge
  • Pretraining on lots of text with all that knowledge is what gives language models their ability to do so much

​

Prof. Somak Aditya, IIT KGP, SSAI 25

Slide Courtesy: Stanford NLP Course

17 of 78

Pretraining Corpus: LLMs are mainly trained on the web

  • Common crawl, snapshots of the entire web produced by the non- profit Common Crawl with billions of pages
  • Colossal Clean Crawled Corpus (C4; Raffel et al. 2020), 156 billion tokens of English, filtered
  • What's in it?
    • Mostly patent text documents, Wikipedia, and news sites

​

Prof. Somak Aditya, IIT KGP, SSAI 25

Slide Courtesy: Stanford NLP Course

18 of 78

The Pile: a pretraining corpus

Prof. Somak Aditya, IIT KGP, SSAI 25

academics web

books

dialog

Slide Courtesy: Stanford NLP Course

19 of 78

Filtering for quality and safety

Quality is subjective

  • Many LLMs attempt to match Wikipedia, books, particular websites
  • Need to remove boilerplate, adult content
  • Deduplication at many levels (URLs, documents, even lines) Safety also subjective
  • Toxicity detection is important, although that has mixed results
  • Can mistakenly flag data written in dialects like African American English

​

Prof. Somak Aditya, IIT KGP, SSAI 25

Slide Courtesy: Stanford NLP Course

20 of 78

The Pretraining / Finetuning Paradigm

20

Pretraining can improve NLP applications by serving as parameter initialization.

(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!

Step 2: Finetune (on your task)

Not many labels; adapt to the task!

(Transformer, LSTM, ++ )

☺/☹

… the movie was …

21 of 78

Pre-trained LSTMs: ELMo

22 of 78

Pretrained LSTMs: ELMo

Pre-trained 2-layer LSTMs, both forward and backward, over a large corpus

The LSTM hidden states that we get (for different words) after the pre-training represents world knowledge. Use these hidden state vectors for new tasks.

23 of 78

ELMo: Training a LM (2-layer LSTM)

24 of 78

A bidirectional LM

Predicting the next word

Predicting the previous word

The two LSTMs are trained independently

25 of 78

ElMo: Obtaining the final embeddings

Combining the two pre-trained LSTMs to get a pre-trained embedding for a word (which will be used for the downstream task). Used the representations of a word at different layers.

26 of 78

ELMo: Weighting of layers

Which layer to give more weightage to?

This depends on the particular downstream task

27 of 78

Using ELMo for a task (sequence tagging; NER)

Say, we are training a bi-RNN for sequence tagging / NER task.

Embeddings from the pre-trained ELMo are appended to the hidden states of the bi-RNN.

Pre-trained ELMo embeddings are frozen. The loss is used to update only the parameters of the smaller bi-RNN.

28 of 78

ELMo: Results

Possibly the first paper that showed large improvements over multiple tasks, using the same model.

Previous SOTA for different tasks were different models.

Demonstrated the power of knowledge transfer using pre-trained Language Models.

29 of 78

ElMo - How does the pretraining help with efficient fine-tuning?

X-axis: amount of training data Y-axis: performance

​

Using the pre-trained model is especially better when the amount of training data is small.

30 of 78

Pre-training

Part 2

Slides mostly borrowed from materials by Jay Alammar, Pawan Goyal, the Stanford NLP course materials and other online resources

31 of 78

Using Transformers for Pretraining

32 of 78

Pretraining for three types of architectures

33 of 78

The pre-training task

  • Pre-training tasks should be such that no human labeling required

​

  • Common pre-training tasks:
    • Predict the next word
    • Mask certain words and predict these masked words from the other words
    • There are sentence-level pre-training tasks also (discussed later)

​

  • The pre-training task is decided depending on the model architecture (e.g., encoder or decoder)

34 of 78

Choice of the Pre-training Task

  • map sequences of input embeddings (x1, ..., xn)
  • to sequences of output embeddings of the same length (a1, ... ,an),
  • where the output vectors have been contextualized using information from the entire input sequence.

Allowed in both encoder & decoder

A word attends only to previous words

Allowed in encoder only

Each word can attend to all words in the sequence

35 of 78

  • Pretraining the Transformer encoder: BERT

​

​

  • Fine-tuning BERT for various paradigms

36 of 78

Pretraining Encoders

Final objective – get good contextual representations of a given sequence of words / tokens

Allowed in both encoder & decoder

Allowed in encoder only;

Predicting the next word is NOT a good pre-training task for encoders, since we cannot use the words coming afterwards

37 of 78

Solution: Use Masks

Input to the Transformer

Task – predict the masked words

​

Loss is computed over the masked words, and then backpropagated.

38 of 78

Which words should the model predict?

  • A real text that will be encoded won’t have any mask
  • If the encoder always sees inputs where some words are masked, it will learn to predict / represent a word only when it is masked; such a model won’t be able to deal with real inputs which won’t have masks

​

  • Solution:
    • Along with the masked words, make the model learn to predict some non-masked words too
    • Compute loss over the masked words, as well as over some of the non-masked words

​

  • So that the model learns good representations of all words, irrespective of masks

39 of 78

BERT: Bidirectional Encoder Representations from Transformers

This loss, used in BERT, is popularly called “Masked LM” loss.

40 of 78

BERT: another view

Compute loss at certain positions based on the actual word at those positions.

Standard Cross Entropy Loss, after Softmax to get a probability distribution on the whole vocabulary.

41 of 78

Next Sentence Prediction

Along with the “Masked LM” loss, BERT used another loss

Given 2 sentences the model predicts if they are a real pair of adjacent sentences from the training corpus or a pair of unrelated sentences.

BERT introduces two special tokens

  • [CLS] is prepended to the input sentence pair,
  • [SEP] is placed between the sentences, and also after second sentence

[CLS] words of sentence1 [SEP] words of sentence2 [SEP]

And two more special embeddings

  • [1st segment] and [2nd segment]

[1st segment] embedding added to all words of sentence1 [2nd segment] embedding added to all words of sentence2

 

42 of 78

BERT: Next Sentence Prediction

Two-class classification based on the final representation of the [CLS] token: continuation or not

Since we are using bi-directional attention, [CLS] will attend to all words in the sequence even though it is at the start.

43 of 78

BERT: Next Sentence Prediction

44 of 78

More Details about BERT

Vocabulary of around 31K words

45 of 78

Contextual Embeddings to represent words

We get from BERT:

​

Contextual representation of each word in the sequence

​

A single contextual representation of the whole sequence - the final representation of [CLS]

46 of 78

Static vs Contextual Embeddings

Static embeddings represent word types (dictionary entries)

Contextual embeddings represent word instances (one for each time the word occurs in any context/sentence)

47 of 78

Using BERT to create contextualized word embedding

Most commonly, we use the representation from the last encoder layer.

But there have been other experiments too.

48 of 78

Using BERT to create contextualized word embedding

We tried something similar with ElMO (pre-trained LSTMs)

49 of 78

Using BERT (already pre-trained) for different tasks

Sentence-level tasks

50 of 78

Using BERT (already pre-trained) for different tasks

Word-level tasks

51 of 78

Transfer Learning through Fine-tuning

52 of 78

Fine Tuning for Sequence Classification

Classifier head can be a fully connected layer (the classification layer) followed by softmax over the set of classes (to get probability of each class)

If 5 classes and 768-dimensional BERT, the number of additional parameters is of the order of 5 x 768 .. much smaller than the number of pre-trained parameters

53 of 78

Fine Tuning for Sequence Classification

These parameters are updated during fine-tuning, using task-specific training data

Pre-trained weights; Frozen or a small subset can be updated

54 of 78

Pairwise Sequence Classification

55 of 78

Pair-wise Sequence Classification

56 of 78

Sequence Labeling (e.g., NER, POS tagging)

We want to label each token.

Do not use the [CLS] embedding; rather, attach a predictor

head to the representation of individual tokens.

57 of 78

POS Tagging

These parameters need to be trained during fine-tuning

58 of 78

GPTs: Pretraining Decoders

59 of 78

  • Pretraining the Transformer Decoder: GPT
  • Fine-tuning GPT for various NLP tasks
  • GPT series: Zero-shot and In-context Learning

60 of 78

Pretraining Decoders

It’s natural to pretrain decoders as language models

Causal self-attention : a token attends to only the past / previous tokens.

Pre-training task: next word / token prediction

​

Teacher forcing used during pre-training. Loss computed w.r.t. ground truth next-token and back-propagated.

61 of 78

Generative Pretrained Transformer (GPT)

Vocabulary larger than BERT

62 of 78

Comparison of GPT series

Multiple versions of GPT-2 were released. See next slide

Image Source: “Large Language Models: A Deep Dive”

63 of 78

Pretrained Decoders

64 of 78

GPT: Transformer-Decoder

65 of 78

GPT-2: Quick Summary

During inference (once the model has been pre-trained):

​

Start with the <start> token.

​

Decoders use self-attention over previous words. Linear layer + softmax gives a probability distribution over the vocabulary. Use any sampling strategy to select the next word (e.g., greedy or beam search).

​

Feed the chosen word as input to generate the next word …

Until some stopping criterion is satisfied.

66 of 78

GPT-2: Quick Summary

67 of 78

GPT-2: Quick Summary

The 2nd word can attend to the word generated previously

68 of 78

How to use Pretrained Decoder-only models?

We will feed the input tokens (context) as the first few tokens, say w1, w2, w3.

​

The subsequent output tokens will attend to the input tokens as well as previous output tokens (using causal / masked self-attention).

​

Input and output tokens are part of the same sequence in decoder-only models.

Decoder-only model can generate sequences using much lesser parameters than Encoder-Decoder models

69 of 78

Fine-tune GPT-2 for Machine Translation

Convert each training data-point to a sequence using a special token <to-fr>

Use the sequences to fine-tune GPT-2 (next token prediction task)

70 of 78

GPT-2: Summarization

In these examples, we are using a decoder-only architecture for sequence-to-sequence tasks

71 of 78

GPT: Beyond Language Modeling

Probabilistic framework: generate token probabilities

​

Classification problem can also be expressed in a probabilistic framework – generate one token (label) for a given input

72 of 78

How to format inputs?

The [EXTRACT] token attends to all input tokens

​

Its application is similar to the [CLS] token of BERT

73 of 78

GPT: How to format inputs?

  • Structured inputs are converted into sequences of tokens for fine-tuning different tasks

​

  • The pre-trained model processes these sequences of tokens, and generates further tokens

​

  • A linear layer with a softmax layer can be implemented over the predicted token(s).

74 of 78

GPT-2: Zero shot and in-context: Beginning

Claim: no fine-tuning needed for tasks

75 of 78

GPT-2

Zero-shot task performance of GPT-2 as a function of model size on many NLP tasks

​

Zero-shot performance improves as model size increases.

76 of 78

Cultural Moment: GPT-3

77 of 78

In-context learning: Terminology

Frozen LM: parameters are NOT updated at all

Prompt engineering

78 of 78

Prompting as the standard interface for GPT-3

Example shown for a sentiment classification task

​

Additional processing may be needed to map the token(s) generated by the LM to a class label