Cheat sheets › Chapter 11
Transformers and LLMs cheat sheet
The architecture behind modern language models. Every lesson in one page: the key idea, the pseudocode and the terms.
Attention
attention lets the word “it” look at every word in the sentence, all at once, and score how relevant each one is.
sentence = "The animal didn't cross because it was tired"
for the word "it":
score every word: how relevant is it to "it"?
turn the scores into weights that add up to 1 # softmax
new meaning of "it" = weighted mix of all the words
# "animal" gets most of the weightTerms: attention
Queries, keys and values
Each token makes three vectors: a query (red: what am I looking for?), a key (blue: what do I contain?) and a value (purple: what will I hand over?).
for each token:
query = what am I looking for?
key = what do I contain?
value = what will I hand over?
score(i, j) = query_i · key_j # a dot product
weights = softmax(scores)
output_i = sum of weights × valuesMulti-head attention
One attention calculation, called one attention head, tends to focus on one kind of relationship. This head links the pronoun “it” to the noun it refers to.
heads = 8 separate attention calculations each head has its own query, key and value weights head 1 might track: which noun a pronoun refers to head 2 might track: which verb goes with a subject head 3 might track: the word just before output = combine(all heads)
Terms: attention head
Positional encoding
“Dog bites man” is ordinary. “Man bites dog” is news. Same three words, different order, different meaning.
attention on its own sees a bag of words: order is lost "dog bites man" and "man bites dog" would look the same position_signal(p) = waves of different speeds, read at position p input(token) = embedding(word) + position_signal(position)
Terms: positional encoding
The transformer block
A transformer is built from identical blocks. Each block starts with attention (purple): every token gathers information from the others.
block(x):
x = x + attention(normalize(x)) # tokens share information
x = x + feed_forward(normalize(x)) # each token thinks on its own
return x
model = a stack of dozens of blocks
output = softmax over the vocabulary → the next tokenTerms: transformer
Pretraining
pretraining starts with an enormous collection of text: books, websites, articles and code, adding up to trillions of tokens.
text = a huge collection of books, articles and code
repeat over trillions of tokens:
hide the next token
model guesses it (a probability for every token)
loss = cross-entropy against the real next token
update the weights
# result: a model that has absorbed the patterns of languageTerms: pretraining
Fine-tuning and LoRA
After pretraining you have a model that knows a lot about language in general. Now you want it to do your task, in your style.
base = a pre-trained language model (billions of weights) freeze base adapter = two small matrices added beside some layers # LoRA train only the adapter on your own examples # a few million trainable weights instead of billions # swap adapters to switch between tasks
Terms: fine-tuning, lora
RLHF and preference tuning
A pretrained model can write many possible replies. Some are helpful, some ramble, some are wrong. For one prompt, generate two answers side by side.
prompt → the model writes two answers, A and B people pick the better one reward_model learns to predict those choices the model is trained to write answers the reward model scores highly # newer methods (like DPO) learn from the choices directly
Terms: reward model, rlhf
Embeddings and vector search
Run every document, photo or product description through an embedding model. Each becomes a point. Similar things cluster: beach photos here, city photos there, food over there.
for each document:
vector = embed(document) # meaning → numbers
store the vector in an index
query_vector = embed("beach sunset photos")
results = the stored vectors closest to query_vector
# smart indexes find neighbors among millions in millisecondsTerms: vector search
Retrieval-augmented generation
rag first runs a vector search over your documents to find the few passages most relevant to the question.
question = "How many holiday days do new staff get?" docs = vector_search(question, company_handbook) # retrieve prompt = docs + question # augment answer = model(prompt) # generate show the answer with links to the source documents
Terms: rag
Revise with flashcards and quizzes. Free practice for every lesson in this chapter.
Open in the app