1 of 43

Pretraining

Supervised finetuning Preference tuning

Transformers & Large Language Models

Slides from: Fall26 CME295, Stanford University,

Prof. Pawan Goyal, Prof. Saptarshi Ghosh’s lectures

2 of 43

Paradigm for LLM training

LLM training. Train LLM to understand language, then tune it for end task

1 Pretraining

2 "Tuning"

​

​

"Pretrained" model

Spam detection

model

Sentiment extraction

model

Translation

model

3 of 43

Pretraining overview

Goal. Learn pattern of language and code

My cute teddy bear is reading by the window, his tiny paws holding a book almost bigger than him. The afternoon light dances across his soft fur as he turns each page with great care…

English

class TeddyBear:

def init (self, name): self.name = name

​

def hug(self):

print(f"{self.name} gives a warm hug!")

​

TeddyBear("Fluffy").hug()...

teddy_bear.py

Multi-lingual

​

Mon ours en peluche est mon plus fidèle compagnon. Toujours assis sur mon lit, il m’attend patiemment, prêt à écouter mes secrets…

ﺖﺨﺗ ور ﻪﺸﯿﻤﻫ .ﺖﺴﻫ ﻦﻣ ﺖﺳود ﻦیﺮﺗﯽمﯿﻤﺻ ﻦﻣ یﺪﺗ سﺮﺧ ...هﺪﺑ شﻮﮔ ﻦﻣ یﺎﻫﻪﺼﻗ ﻪﺑ هﺮﺿﺎﺣ و ﻪتﺴﺸﻧ ﻦﻣ

…

package main

​

func main(){

println("Teddy bear hug!")

}

teddy_bear.go

4 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

A teddy bear is reading Persian poetry. Around him, the room is still: a warm lamp, a cup of tea gone cold, a notebook full of underlined metaphors, and a window looking out onto the evening [...]

5 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

[BOS]

​

A

​

teddy

​

bear

​

is

​

reading

​

​

​

​

​

​

​

​

​

​

​

Persian

​

poetry

​

.

​

Around

​

him

​

,

​

​

​

​

​

​

​

​

​

​

​

the

​

room

​

is

​

still

​

:

​

a

​

warm

​

​

lamp

​

​

,

​

​

a

​

​

cup

​

…

6 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

?

​

LLM

[BOS]

7 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

A

?

​

LLM

[BOS]

A

8 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

A

teddy

?

​

LLM

[BOS]

A

teddy

9 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

A

teddy

bear

?

​

LLM

[BOS]

A

teddy

bear

10 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

A

teddy

bear

is

?

​

LLM

[BOS]

A

teddy

bear

is

11 of 43

Pretraining is highly parallelizable via teacher forcing

Goal. Learn pattern of language and code

Objective function. Predict next token

Masked self-attention

​

LLM

[BOS]

A

teddy

bear

is

Input

Right figure from The Annotated Transformer, Harvard NLP, 2018.

12 of 43

Pretraining is highly parallelizable via teacher forcing

Goal. Learn pattern of language and code

Objective function. Predict next token

A

teddy

bear

is

reading

Ground truth

​

LLM

Prediction

[BOS]

A

teddy

bear

is

Input

13 of 43

Pretraining is highly parallelizable via teacher forcing

Goal. Learn pattern of language and code

Objective function. Predict next token

Target token

Past tokens

​

LLM

Predicted probability

Number of tokens

14 of 43

Making the loss less dependent on choice of tokenizer

Number of bytes

Conversion of

nats to bits

Goal. Learn pattern of language and code

Objective function. Predict next token

​

Number of tokens

Cross-Entropy

​

​

Bits Per Byte

15 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

Data mixtures.

  • Web-scraped (e.g. Common Crawl, Wikipedia)
  • Code (GitHub, StackOverflow)
  • Math, science

Teddy bear Wikipedia article and a GitHub repo. Screenshots taken on October 4, 2026.

16 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

Data mixtures (Unlabeled corpus of text, code)

Architectures

Encoder-Decoder

Decoder-only

Encoder-only

Teddy bear Wikipedia article and a GitHub repo. Screenshots taken on October 4, 2026.

17 of 43

Recap - Pretraining Encoders – Masked LM

18 of 43

Transfer Learning through Fine-tuning

  • Fine-tuning these pretrained encoders require
    • Addition of some “Task type” specific architectural changes
      • Task-Type:
        • single-sentence classification,
        • 2-sentence classification,
        • sequence-to-sequence classification
        • sequence generation.

​

    • Training data specific to the tasks

​

    • Task-type determines the objective: Mostly
      • Classification CE
      • Language Modeling Task CE

​

    • Fine-tune task-specific parameters

19 of 43

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)

20 of 43

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

21 of 43

Pairwise Sequence Classification

Text

Hypothesis

Judgement

An older and younger man smiling.

The older man is not smiling

Contradiction

An older and younger man smiling.

Two men are laughing at the cats playing on the floor.

Neutral

An older and younger man smiling.

An older man is smiling.

Entailment

22 of 43

Pair-wise Sequence Classification

23 of 43

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.

24 of 43

POS Tagging

These parameters need to be trained during fine-tuning

25 of 43

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.

26 of 43

Generative Pretrained Transformer (GPT)

Vocabulary larger than BERT

27 of 43

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

28 of 43

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)

29 of 43

GPT-2: Summarization

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

30 of 43

Pretraining overview

Goal. Learn pattern of language and code

Objective function. Predict next token

Data mixtures.

  • Web-scraped (e.g. Common Crawl, Wikipedia)
  • Code (GitHub, StackOverflow)
  • Math, science

​

Size. Approx. trillions of tokens (example: GLM-5 pretrained on ~30T tokens)

31 of 43

Pretraining

Supervised finetuning Preference tuning

Transformers & Large Language Models

32 of 43

Supervised finetuning

SFT = Supervised FineTuning

Idea. Change the model behavior by tuning its weights

​

Strategy.

  • Collect pairs of input/outputs with desired behavior (aka SFT data)
  • Train using next word prediction objective given the input

33 of 43

Supervised finetuning

SFT = Supervised FineTuning

Idea. Change the model behavior by tuning its weights

​

Strategy.

● Collect pairs of input/outputs with desired behavior (aka SFT data)

● Train using next word prediction objective given the input

Special case. SFT on instruction-following data: "Instruction tuning"

34 of 43

Instruction tuning overview

Goal. "Graduate" the model to being a helpful assistant.

Story writing

​

Write a short story about a teddy bear who likes to read poetry.

Once upon a time, a bear, Teddy, stumbled upon verses from Attar. The bear became so captivated with the rhythm of the poem's sentences that he got filled with happiness.

Lists generation

​

List three fun activities a teddy bear might do on a rainy day.

Sure!

  1. Read poetry with friends.
  2. Be cute.
  3. Hug its owner tightly.

Poem creation

​

Create a poem about my cute teddy bear.

Soft and cuddly, full of charm, Always keeps me safe from harm, With button eyes and fur so neat, My teddy bear is oh so sweet.

Explanation

​

Explain why a teddy bear is a great friend.

A teddy bear is a great friend because it provides comfort and companionship. Its soft fur and cuddly nature is perfect for hugs. Teddy bears are always there in both happy and sad moments.

35 of 43

Finetuning to Instruction Finetuning

There are 100s of tasks.

Do we finetune 100 times?

No.

Perform instruction-finetuning on many

Generalize to arbitrary tasks from

Instruction

Positive Examples

Negative Examples

Input

Predict output (same training setup)

Goal: from Instance to Task-level Generalization

36 of 43

Instruction Finetuning (60 to 1600)

Train on a mixture of crowdsource instruction, input and label.

Data:

    • Input and label from existing tasks.
    • Add crowdsourced instruction to describe tasks

Natural Instructions, Mishra et al. 2022 (61 tasks)

Generalize to 1600+ tasks. Crowdsourced initiative to add tasks in a Github repo.

Add simple tasks as well with simpler instructions like longest palindrome substring etc.

37 of 43

Instruction tuning overview

Goal. "Graduate" the model to being a helpful assistant.

Objective function. Predict next token given the input.

Do

X

.

Sure

...

​

LLM

​

​

​

[BOS] Do X

.

​

Sure

38 of 43

Instruction tuning overview

Goal. "Graduate" the model to being a helpful assistant.

​

LLM

Objective function. Predict next token given the input.

​

Input prompt

Target token

Past tokens

Predicted probability

Number of tokens

39 of 43

Instruction tuning overview

Goal. "Graduate" the model to being a helpful assistant

​

Objective function. Predict next token given the input.

​

Data mixtures. Can be both human-written and synthetic data.

  • Assistant dialogs
  • Synthetic instructions
  • Maths, reasoning, code
  • Safety alignment
  • ...

40 of 43

Instruction tuning overview

Goal. "Graduate" the model to being a helpful assistant

​

Objective function. Predict next token given the input.

​

Data mixtures. Can be both human-written and synthetic data.

Size. Thousands to millions of examples.

41 of 43

Behavior

Can I put my teddy bear in the washer?

Pretrained + instruction tuned LLM

No, it might get damaged. Try hand washing instead.

42 of 43

Challenges

  • Very high-quality data needed

​

  • Sensitive to prompt distribution

​

  • Generalization

​

  • Difficult to evaluate

​

  • Computationally expensive

43 of 43

Challenges

  • Very high-quality data needed

​

  • Sensitive to prompt distribution

​

  • Generalization

​

  • Difficult to evaluate

​

  • Computationally expensive