NLP, Transformers & LLMs: Introduction
A computer receives text as a string of characters. Everything people want from text needs more than that: whether a review is positive, which words in a contract are company names, which help page answers a customer's question, what the next sentence of an email should be. Natural language processing (NLP) is the engineering that turns character strings into numbers a model can learn from, and the model's numbers back into labels, spans, rankings or new text.
Every NLP system, from a 1990s spam filter to a chat model with billions of parameters, follows the same pipeline. What changed over three decades is mostly the middle: how text becomes vectors, and which model reads them.
What a bag of words cannot see
The classic pipeline counts words. That is cheap, transparent and often good enough: TF-IDF with a linear model is still the first baseline to beat on any text classification task. But counting throws away order. The example builds count vectors for two pairs of sentences that mean different things, first with single words, then with single words plus pairs of neighbouring words (bigrams).
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
sentences = ["the dog bit the man", "the man bit the dog", "the man was not happy, the film was good",
"the man was happy, the film was not good"]
for ngram in [(1, 1), (1, 2)]:
vec = CountVectorizer(ngram_range=ngram).fit(sentences)
X = vec.transform(sentences).toarray()
print(f"n-grams {ngram}: {X.shape[1]} features")
print(" 'dog bit man' vs 'man bit dog' identical:", bool((X[0] == X[1]).all()))
print(" 'not happy ... good' vs 'happy ... not good' identical:", bool((X[2] == X[3]).all()))
print("bigrams that differ in pair 2:", [f for f, a, b in zip(vec.get_feature_names_out(), X[2], X[3]) if a != b])n-grams (1, 1): 9 features
'dog bit man' vs 'man bit dog' identical: True
'not happy ... good' vs 'happy ... not good' identical: True
n-grams (1, 2): 23 features
'dog bit man' vs 'man bit dog' identical: False
'not happy ... good' vs 'happy ... not good' identical: False
bigrams that differ in pair 2: ['not good', 'not happy', 'was good', 'was happy']
With single words, "the dog bit the man" and "the man bit the dog" get the same vector, and so do the two film sentences, although one praises the film and the other does not. Bigrams separate them (the features "not good" and "not happy" now differ), at the price of 23 features instead of 9 for four short sentences. Each step of the course's history is a better answer to this problem: n-grams capture a little local order, recurrent networks read the whole sequence, and transformers let every token look at every other token through attention.
Words that change meaning
The second limit is that one word gets one vector. "Bank" next to a river and "bank" next to a loan are the same column in a count matrix and the same row in a word-embedding table. A transformer computes a fresh vector for each token in its context. The recorded example below runs a small pretrained BERT (2 layers, 128 numbers per token) on three sentences and compares the vectors it produces for "bank". It also shows how two real tokenizers cut the same sentence into pieces.
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()
text = "Unbelievably, the bank by the riverbank refused my loan."
bert_tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
gpt_tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
print("BERT WordPiece:", bert_tok.tokenize(text))
print("GPT-2 byte BPE:", gpt_tok.tokenize(text))
bert = AutoModel.from_pretrained("google/bert_uncased_L-2_H-128_A-2").eval()
def vector_of(word, sentence):
enc = bert_tok(sentence, return_tensors="pt")
with torch.no_grad():
h = bert(**enc).last_hidden_state[0] # (tokens, 128)
i = enc.input_ids[0].tolist().index(bert_tok.convert_tokens_to_ids(word))
return h[i]
cos = torch.nn.functional.cosine_similarity
river1 = vector_of("bank", "we sat on the bank of the river and watched the water")
river2 = vector_of("bank", "the boat drifted towards the muddy bank of the stream")
money = vector_of("bank", "she opened an account at the bank to save money")
static = bert.embeddings.word_embeddings.weight[bert_tok.convert_tokens_to_ids("bank")]
print(f"river vs river: {cos(river1, river2, dim=0):.3f}")
print(f"river vs money: {cos(river1, money, dim=0):.3f}")
print("input embedding row is the same in every sentence:", static.shape[0], "numbers")BERT WordPiece: ['un', '##bel', '##ie', '##va', '##bly', ',', 'the', 'bank', 'by', 'the', 'river', '##bank', 'refused', 'my', 'loan', '.']
GPT-2 byte BPE: ['Un', 'bel', 'iev', 'ably', ',', 'Ġthe', 'Ġbank', 'Ġby', 'Ġthe', 'Ġriver', 'bank', 'Ġrefused', 'Ġmy', 'Ġloan', '.']
river vs river: 0.941
river vs money: 0.852
input embedding row is the same in every sentence: 128 numbers
Two things to read here. The tokenizers disagree: BERT's WordPiece lower-cases and marks word-internal pieces with ##, GPT-2's byte-level BPE keeps the case and marks a leading space with Ġ; neither has "unbelievably" as one token, and both split "riverbank". The Tokenizers section builds both kinds from scratch. And the contextual vectors of the two river "bank"s are closer to each other (cosine 0.941) than to the money "bank" (0.852), although all three start from the same 128-number input row. This BERT is tiny, so the gap is modest; larger models separate word senses much more clearly. Inside a Pretrained BERT takes such a model apart.
How the course is organised
| Section | You build | Main tools |
|---|---|---|
| Text Processing | normalisation, word tokenisation, stemming and lemmatisation, bag of words, TF-IDF, text classifiers, BM25 search | NumPy, scikit-learn, NLTK |
| Embeddings and Sequence Models | PPMI and SVD word vectors, n-gram language models and perplexity, LSTM and CNN classifiers, a named-entity tagger | NumPy, scikit-learn, PyTorch |
| Tokenizers | BPE from scratch, WordPiece and Unigram, the Hugging Face tokenizers with special tokens and offsets | Python, Transformers |
| Transformers for Language | cross-attention, RoPE and ALiBi, the encoder, decoder and encoder-decoder families, a look inside BERT and GPT, the KV cache | NumPy, Transformers |
| Pretraining | causal, masked and span-corruption objectives, a tiny GPT pretrained on your own tokenizer, scaling laws and data deduplication | NumPy, SciPy, PyTorch |
| Fine-Tuning Encoders | BERT for classification and NER, dense retrieval with sentence embeddings | Transformers, sentence-transformers |
| Adapting LLMs | supervised fine-tuning with loss masking, instruction tuning and chat templates, reward models and DPO, LoRA and QLoRA for LLMs | NumPy, PyTorch, PEFT |
| Retrieval-Augmented Generation | a RAG pipeline with citations and its evaluation | NumPy, sentence-transformers |
| Efficient Inference and Deployment | int8 and int4 quantization, speculative decoding, LLM evaluation metrics, serving and monitoring | NumPy, PyTorch, Pydantic |
The Mini Project ties the course together on a small help-centre corpus that several lessons share: keyword search, dense retrieval, a fine-tuned classifier and a grounded answer with citations, measured at each step.
What you need, and what is linked instead of repeated
This is an advanced course. It assumes:
- Deep learning in PyTorch: the training loop, embeddings, RNNs and LSTMs, and attention and the transformer block, which Deep Learning builds from scratch (Attention from Scratch, Building a Transformer Block, Training a Tiny Character Transformer). This course uses those pieces and goes on to language-specific questions; it does not rebuild them.
- Using LLMs: prompting, APIs, sampling and a first RAG app, from Generative AI & LLMs. Here you learn how such models are trained, adapted, compressed and evaluated.
- Fine-tuning strategies: LoRA, QLoRA, adapters and prompt tuning are derived and built in Training Strategies. The LLM lessons here link to them and focus on what is specific to language models: which layers to adapt, chat data, memory budgets.
- The math (softmax, cross-entropy, perplexity, attention, positional encodings, scaling laws) is derived in Mathematics for Deep Learning; lessons link to the derivations.
How the examples run
- In your browser: NumPy, scikit-learn, SciPy and NLTK run in Python compiled to WebAssembly, so you can edit and rerun every from-scratch example: the TF-IDF formula, BM25, BPE training, Viterbi decoding, RoPE, the KV cache, DPO's loss, int4 quantization, speculative decoding. NLTK's stemmers and regex tokenizers work offline; the parts of NLTK that need downloaded data (WordNet, the Punkt sentence model) are shown as code that is not run.
- Recorded: examples that import PyTorch, Transformers, PEFT or sentence-transformers carry a Recorded badge and show the output of a real run on 4 CPU threads in a Docker image without network access. Only small cached models load there: a 4.4-million-parameter BERT (
google/bert_uncased_L-2_H-128_A-2), the GPT-2 tokenizer with a randomly initialised two-layer GPT-2 (sshleifer/tiny-gpt2, for shapes and wiring only), theall-MiniLM-L6-v2sentence encoder and therotten_tomatoesmovie-review sentences. There is no pretrained chat model in the image, so the LLM-adaptation lessons train tiny decoders from scratch on synthetic tasks inside the example. Their scores are small-scale demonstrations of the mechanism, not of what a 7-billion-parameter model would reach, and the lessons say so. - Not run here: tools that need a GPU or the network (bitsandbytes 4-bit kernels, vLLM, tiktoken's encoding download, hosted LLM APIs) are shown as plain code blocks and explained.
Every score says how it was measured: which split, how many examples, which metric. Tokenizers, vocabularies and TF-IDF weights are fitted on training text only, and text data is split by document, never by sentence fragments of the same document.
Test yourself
Why do 'the dog bit the man' and 'the man bit the dog' get the same vector with single-word counts?
- Because the vectorizer removes stop words
- Because counting words ignores their order, and both sentences contain the same words the same number of times
- Because the vocabulary is too small
- Because both sentences have five words
What does a transformer give you that a word-embedding table does not?
- A vector per word type that never changes
- A vector per token that depends on the surrounding words
- Fewer parameters
- No need for a tokenizer
In the GPT-2 tokens, what does the prefix Ġ in Ġbank mean?
- The token is a proper noun
- The token starts with a space
- The token is the last of the sentence
- The token is unknown
Why do the LLM-adaptation lessons of this course train tiny decoders inside the example?
- Because tiny decoders work better than large ones
- Because the offline recording image has no pretrained chat model and every example must finish in seconds on a CPU
- Because PEFT only works with tiny models
- Because GPUs are not supported by PyTorch