1 of 77

10-405/605/805�ML FROM LARGE DATASETS

2 of 77

A few reminders

  • Cheat sheet must be handwritten
    • not written on an ipad and printed
    • not photographically reduced
    • …
  • Wed exam is not cumulative

3 of 77

Study hints

  • I often
    • recap parts of a lecture I think are important
    • show HTML visualizations of the algorithms I think are important

4 of 77

The Evolution of Transformers: Summary

5 of 77

Questions

  • Why are deep MLPs interesting?
    • They are more expressive
  • Why are they hard to learn?
    • Vanishing gradients: gradients can get exponentially smaller with depth
    • Activation values need to stay in a narrow range or else sigmoid units get “stuck”

​

6 of 77

6

AI Stats 2010

RECAP

sigmoid units get “stuck”

7 of 77

7

AI Stats 2010

Histogram of gradients in a 5-layer network for an artificial image recognition task

RECAP

gradients vanish

8 of 77

Recap: Attention for “question answering”

Adding attention:

  • classify the hidden states h1, … hm of the answer according to relevance to the question
  • classifier is based on question representation oq and hidden state hi
    • score of hi is softmax of dot-product similarities of question oq to answer-token encoding hi
    • score ~= ”probability that answer token is useful”
  • when you pool answer tokens reps, weight by the classifier’s score

​

RECAP

9 of 77

Example: Machine Translation

2016

This model

  • encodes the source text
  • decodes to produce the target text while
    • using a soft alignment between the word to be generated and the encodings of the source words
    • alignment is based on attention

​

RECAP

10 of 77

Example: Machine Translation

2016

a(s,h) = alignment score

RECAP

11 of 77

TRANSFORMERS

12 of 77

Transformer checklist

  • ✅ Tokenization

​

  • ✅ Token embeddings / internal representations
  • ✅ Positional encoding

​

  • ✅ Attention
    • multihead
    • cross-attention (decoder to encoder)
    • causal masking

​

  • ✅ Skip connections
  • ✅ Layer normalization
  • ✅ FFN – 2-layer perceptron with reLU
  • ✅ Dropout
  • ✅ Encoder-decoder
  • ✅ Encoder-only (BERT)
  • ✅ Decoder-only (GPT)
  • ✅ Parameter-efficient fine tuning

​

  • ✅ Key-Value Caching (GPT)

​

13 of 77

BERT: An Encoder-Only Transformer

2019

The model also predicts if sentence B is the “next sentence” after sentence A in the original document.

Prediction was done based on the output embedding of a special [CLS] token that was prepended to the input text.

14 of 77

Initial vocabulary from UTF-8

Step 1: Find all tokens in the corpus and save their frequency.

Step 2: Break all the tokens into characters (the initial vocabulary)

ascii

 Latin alphabets, Greek, Hebrew, …,

mostly CJK

emojis …

All the bytes from UTF-8

15 of 77

16 of 77

Recap: Tokenization for Vision Transformers

17 of 77

Vision Transformers – Pros and Cons

  • ViTs have a weaker bias than CNNs and usually need more data to train
    • They don’t “know” that local-area features matter
  • Transformers are not the SoTA way of generating images
    • Although they often do quite well!
  • ViTs are excellent for multimodal vision/language models

18 of 77

Transformer checklist

  • ✅ Token embeddings / internal representations
  • ✅ Positional encoding
  • ✅ Attention
    • multihead, masking
    • cross-attention (decoder to encoder)
  • ✅ Skip connections
  • ✅ Layer normalization
  • ✅ FFN – 2-layer perceptron with reLU
  • ✅ Dropout
  • ✅ Encoder-decoder
  • ✅ Encoder-only (BERT)
  • ✅ Decoder-only (GPT)
  • ✅ Parameter-efficient fine tuning
  • ✅ Tokenization

19 of 77

20 of 77

LoRA (low rank adaptation) finetuning

Key ideas:

  • Don’t fine-tune everything, instead tune deltas that will be added to the (some) old weights
  • don’t learn a full d x d matrix of weights, instead learn a low-rank approximation

“full" finetuning

LoRA

finetuning

21 of 77

MF to adjust weights

cluster specific weight adjustment

n examples

0.1

0.9

0.8

0.1

..

..

​

​

​

​

​

​

​

​

​

​

…

…

xn

yn

a1

a2

..

…

am

b1

b2

…

…

bm

v11

…

​

​

​

…

…

​

​

​

​

​

​

​

​

​

vij

​

​

​

​

​

​

…

​

​

​

​

​

vnm

~

original data set

soft indicators for r clusters

A

B

ΔW

22 of 77

HYPERPARAMETER SEARCH

23 of 77

Recap: Hyperparameter Selection

24 of 77

Recap: Hyperparameter Selection

Common adaptive selection loop:

  • Build a model of f from past experiments
    • “Surrogate model”
  • Pick the next experiment to do based on the surrogate model
    • Experiment = learning task
  • Repeat…

A simple case:

​

  • a single discrete hyperparameter with k possible values
  • but f is random (e.g., there’s a seed for the ML algorithm)

​

Goal: find the best of the k values quickly

Explore the space intelligently

25 of 77

Recap: 5D Gaussian Processes�for Bayesian Optimization

Conditioned on a point

Conditioned on 4 points

What is Σ ?

Define covariance between xi and xj with a kernel, defined for all xi, xj

26 of 77

27 of 77

Gaussian Process Regression

Define covariance between xi and xj with a kernel, defined for all xi, xj

y1 is f(x), y2 is x

A = cov(Y1)

B = cov(Y1, Y2)

C = cov(Y2)

28 of 77

 

29 of 77

EMBARASSINGLY PARALLEL TRAINING

30 of 77

BTM: Key ideas

ELM = expert LM

ELMForest = group of ELMs

𝜃1, 𝜃2, …, 𝜃k

small GPT 𝜃

merged with parameter averaging

31 of 77

BTM: Training costs

32 of 77

2024

Branch and Train as in Branch-train-merge

Mix the expert LMs by

  • Making each FFN an expert for the corresponding MoE FFN layer
  • Parameter averaging all other parameters
  • Finetune everything (notice gates have new parameters)

33 of 77

BTX results

34 of 77

 

35 of 77

Experiments with task analogies

  • Objective: sentiment analysis on reviews from Yelp
  • Data available
    • unlabeled reviews from Yelp
    • sentiment data from Amazon reviews
    • unlabeled Amazon reviews
  • Approach: build task vectors for
    • 𝜏YelpLM: language modeling on Yelp
    • 𝜏AmazonLM: language modeling on Amazon
    • 𝜏AmazonSentiment: sentiment prediction on Amazon

​

    • Finally use

λ1𝜏AmazonSentiment + (λ2𝜏YelpLM — λ3𝜏AmazonLM)

​

​

​

​

​

36 of 77

Experiments with task analogies

Collect 200 images of kings, queens, women, men.

​

Fine-tune CLIP models on each category, using 1000 ImageNet classes as negative examples

(class name ”something”)

37 of 77

Experiment: adding different task vectors

  • weighted sum of task vectors for 2 vision tasks
  • show accuracy normalized by FT accuracy
      • and compared to zero-shot accuracy

Note the training for the subtasks is embarrassingly parallel

38 of 77

MAKING MODELS SMALLER

39 of 77

Model compression

  • Distillation
  • Quantization
  • Pruning
  • Key-Value Cache Management
    • …which is also pruning with eviction

40 of 77

Distillation

Typically we distill a model on lots and lots of data only labeled by the teacher (transfer set)

The simple case: teacher predictions are “hard” labels (e.g., training a generative LLM).

  1. Easy to add cross-entropy loss to a set of gold labels.
  2. Moderate temperatures seem to require less transfer data for same accuracy.

41 of 77

Recap: making a large model smaller

  • Quantization
  • Pruning
  • Key-Value Cache Management
    • …which is also pruning

simple quant rules

complex rules, learning

“32 bits everywhere”

“16 bits except for bias”

int8() except for outliers, defined as ….

SOTA optimizers for discrete or hybrid discrete/continuous spaces

42 of 77

Recap: making a large model smaller

  • Quantization
  • Pruning
  • Key-Value Cache Management
    • …which is also pruning

simple optimization

complex optimization

Wanda: greedy weight pruning

shortened Llama: greedy layer pruning + LoRA

Magnitude: greedy weight pruning alternating with gradients

MiniTron: combine multiple approaches to pruning, distillation to pruned architectures

43 of 77

KEY VALUE CACHES

44 of 77

Recap: How to KV Cache

45 of 77

Recap: Transformers Are KV-Cache Optimized

46 of 77

Recap: Restricting attention with KV caching

  • KV caching is caching, until you start using KV cache management methods
    • Generally in key-value caching we restrict attention by evicting from the cache
  • This is a crucial method for long inputs
    • or outputs, e.g. reasoning models (O1,…)

​

  • Big question: what is the eviction policy?

​

47 of 77

Recap: Backstory in restricted attention

  • Key idea in ETC: split tokens into local and global
  • Attention is global-local, local-global, and local-local with locality constraints
  • Local-local attention is not a mask but a “gather”

​

48 of 77

Recap: “Heavy Hitters” in KV Caches

sparsity: fraction of cache with < 1% of max attention score

Attention is sparse

Heavy Hitter KV Cache Entries are Important

49 of 77

Recap: “Heavy Hitters” in KV Caches

  • Proposed method
    • Fix the cache size to K
    • Generate tokens i=1, …, …
      • Track score (cumulative attention) of each KV position
        • “local H2 statistic” – cumulative attention up to position i
      • When the cache is full, overwrite the token with lowest local H2 score
        • The “eviction policy”
    • Local H2 statistic is close to full oracle H2 statistic that looks at future tokens

50 of 77

Recap: “Heavy Hitters” in KV Caches

51 of 77

Recap: making a large model smaller

  • Quantization
  • Pruning
  • Key-Value Cache Management

simple optimization

complex optimization

+ start token

H2O: score by running accumulated attention

SnapKV: Adaptively pick specific weights based on observation window in prefilling

FastGen: Pick strategy per head and layer based on prefilling.

Score by recency (FIFO)

+ separator

Lots of detail but I tried to pick out “key ideas” for the papers

52 of 77

RAG AND CONTRASTIVE LEARNING

53 of 77

  • Access new information (not available during model pretraining)
  • Better access “long tail” information that is mentioned infrequently in pre-training documents
  • Needs strong retrieval

54 of 77

Recap: The Dense Passage Retriever (DPR)

  • Process several QA datasets to get triples:
    • (question, gold passage id, gold answer span)
  • Triples give positive question/passage examples (qi, pi) encoded in d=768 dimensions by pre-trained BERT
  • Q is mini-batch of B questions, P is B passages, S = QPT is (B x B) matrix of similarity scores
    • score is positive for qi, pj iff i=j
      • “in-batch negatives” trick
    • also add as additional hard negatives
      • 1-2 passages with high TFIDF score to q which do not contain the answer span

55 of 77

Recap: Contriever vs DPR

  • Same NT-Xent contrastive loss
  • One BERT encoder instead of two
  • Data augmentation tricks used
    • Independent cropping
    • Random token deletion
  • Negatives were from
    • in-batch negatives
    • momentum contrast (MoCo)
      • MoCo: dynamic dictionary queue and averaging last two models to find hard negatives

56 of 77

Recap: The OG RAG paper

returns top K docs

57 of 77

Encoder-only vs decoder-only Transformers to Retrieval

  • DPR, Contreiver, … are encoder-only models
    • based on BERT
  • Encoding documents for retrieval with decode—only models is trickier

58 of 77

Hypothetical Document Embedding (HyDE)

  • Details
    • prompt model (InstructGPT) to convert question q to a query document d

​

​

​

    • sample N documents d1, …, dN, by generation with temperature T
    • query vector for Contriever is average of embeddings for q and d1, …, dN

59 of 77

Decoder-only models as encoders?

2023

2025

PromptEOL

Echo embeddings

60 of 77

Recap: Fusion in Decoder (FiD)

  • In open-book QA, often
    • Questions q and answer a are short: k=O(10)
    • Passages are longer: m=O(100)
  • Retrieving and appending N passages:
    • Encoder = O(Nm + k)2
    • Decoder = O(k * (Nm + k))
  • Trick:
    • cross-encode q with each passage separately: O(N(k+m)2)
    • decode, attending to all: O(k * N(m + k))

​

O(N2 m2) ignoring k

O(N m)

O(N m2)

O(N m)

quadratic in N 🡪 linear in N

can afford to retrieve more docs

we lose cross-attention between tokens in different passages

61 of 77

Recap: FiD Optimized (FiDO)

2023

62 of 77

Recap: Fusion in Decoder (FiD)

FLOP analysis: Encoder is 6x as expensive as decoder!

…but at inference time decoding is slowest. Why?

What’s the fix?

Predicted by counting FLOPS for all the matmuls and assuming nt << ns and nt << d

  • nt tokens in decoder output
  • ns tokens in all encoder input

Predicted by memory/FLOPs:

Multilayer perceptron

self-attention

cross-attention

63 of 77

Recap: Fusion in Decoder Optimized (FiDO)

  • Speeding up performance:
    • Layer sparse attention (LSA): perform cross attention only on every K-th layer (K=6)
      • Load fewer key-value entries from encoder on avg
    • Multi-query attention (MQ)
      • Creates fewer key-value entries
  • Compensate for performance loss:
    • Scale the decoder up!
      • Use T5-XL decoder with T5-Base encoder, etc

Decoder

Encoder

Decoder

64 of 77

Recap: Fusion in Decoder Optimized (FiDO)

65 of 77

Recap: LUMEN: FiD with caching

The first N-K layers of the FiD encoder

The last K layers of the FiD encoder

FiD decoder

Passages are encoded and stored off-line for every document

66 of 77

Main ideas in FiD and extensions

  • In encoder
    • cross-encoder q+p1, q+p2, … separately
      • restricting cross-attention
  • In decoder
    • attend to everything as you generate
  • Extensions
    • FiDO: optimize performance to avoid decoder bottlenecks
    • LUMEN: pre-compute encoder outputs
    • GLIMMER: add reranking

FlashAttention (2023) and FlexAttention (2024)—also improve decoder bottlenecks

Parallel Context Windows (PCW) - 2023

TurboRAG, Blockwise Sparse Attention - 2024

Dynamic Blockwise Sparse Attention - 2025

Analog for decoder-only LLMs

67 of 77

2023

  • Context tokens: retrieved document(s) for RAG, in-context examples, …
  • Task tokens: question for RAG, test input for ICL, …
    • I believe output tokens are also task tokens

​

Key idea: cross-attend within a context window, and cross-attend between task tokens and all context windows.

Very similar to FiD

  • if question/answer are task tokens
  • no post-training used

68 of 77

2025

Key idea: same as Block-Attention except

  • experiments are on ICL instead of RAG
  • cache the independently-produced KV pairs of the documents
  • evaluate addition of KV pairs computed for retrieved documents
    • retrieve ICL examples with BM25
  • avoid fine-tuning
    • clever use of StreamingLLM trick of “attention sink”
    • don’t mess with position encodings

69 of 77

SCALABLE EVALUATION

70 of 77

Small preferences or weak guesses can be amplified in a network

71 of 77

PPI: Statistically Unbiased AI Judges

  • One solution: build an AI system to perform evaluation!
  • … but is this a good idea?

​

Arguments for:

  • much more data can be collected faster
  • my project is late / over budget
  • human labels are noisy
  • LLM-as-judge biases seem to be minor

​

​

  • A small amount of human-labeled data can be used to correct for biases in a judge/autorater
  • statistical inference 🡺 prediction-powered inference

72 of 77

Bayesian PPI

Difference estimate

(old)

Bayesian version

73 of 77

A practical problem with autoraters

ML models tend to hedge too much—put more weight in the middle of the distribution

Solution: split the data by autorater score and use two difference estimates

mean y - f

mean y - f

74 of 77

Bayesian PPI: QA evals

C I width

human labels: 3k AR labels

75 of 77

Background: Power Tuning for Difference Estimates

Difference estimate

(old)

Generalization (PPI++)

works for any λ, there is a good heuristic for setting it using cov of SN and Sn

λ=1 gives PPI

λ=0 gives classical statistic

76 of 77

PPI++ is robust to bad autoraters

a good autorater: FP/FN = 10%/8%

a bad autorater: FP/FN = 25%/25%

77 of 77

Final messages

  • Exam 2 is similar to exam 1
    • Different content (not cumulative)
    • Similar mix of multichoice, true false, short answer questions
  • Good luck!