NLP & Transformersintermediatemust-know5 min

The Attention Mechanism

How a model knows which earlier words matter for the one it is reading.

When you read "The cat sat on the mat because it was tired", you know "it" means the cat, because you looked back at the right word. Attention lets a model do the same. For each word, it scores how relevant every other word is, then builds that word's meaning mostly from the high scorers. Older models squeezed a whole sentence into one fixed summary and lost detail on long inputs. It is the core idea inside every Transformer, including ChatGPT.

NLP & Transformersintermediatemust-know5 min

Transformer Architecture

The design behind ChatGPT and almost every modern language model.

The Transformer is the design behind almost every modern language model. Older models read text one word at a time, which was slow and tended to forget early words. A Transformer looks at all the words at once and uses attention to let each word pull in information from the others, so GPUs can process a whole passage in parallel. It is built from repeated blocks of attention followed by a small feed-forward network, with shortcut connections and normalisation keeping deep stacks trainable.

NLP & Transformersintermediatemust-know5 min

Tokenization & BPE

How text gets chopped into the pieces a model actually reads.

Tokenization breaks raw text strings into numerical token IDs that neural networks can process. Character level tokenization creates tiny vocabularies but long sequences. Word level tokenization creates huge vocabularies with frequent out of vocabulary errors. Byte Pair Encoding (BPE) is a subword tokenization algorithm that iteratively merges the most frequent pairs of adjacent bytes or characters. BPE balances vocabulary size and sequence length, handling rare words and code efficiently without out of vocabulary errors.

NLP & Transformersintermediatemust-know5 min

BERT vs GPT: Encoder vs Decoder

Two kinds of Transformer: one built to understand text, one built to write it.

BERT and GPT are both Transformers, built for different jobs. BERT reads a whole sentence at once, looking both left and right, and is trained by filling in hidden words. That makes it strong at understanding text: classifying it, searching it, or finding answers inside it. GPT reads strictly left to right and is trained to predict the next word, which makes it strong at writing new text. Most chatbots today are GPT-style, while search systems often still use BERT-style models.

NLP & Transformersadvancedmust-know5 min

The KV Cache

Why chatbots stay fast as they write, and why they eat so much GPU memory.

When a model writes text one word at a time, each new word needs to look back at all the words before it. Without a cache, the model would recompute the same information for those earlier words at every single step. The KV cache stores each word's keys and values the first time they are calculated and reuses them, so each step only does the work for the newest word. Generation becomes much faster, but the cache grows with every word and can fill the GPU's memory.

NLP & Transformersbeginner5 min

Word2Vec, GloVe & Embeddings

Turning words into numbers so that similar meanings sit close together.

Word embeddings turn each word into a list of a few hundred numbers, placed so that words with similar meanings sit close together. That lets a model see that king and queen are related, which a plain list of word IDs never could. Word2Vec learned these numbers by predicting a word from its neighbours, or the neighbours from the word. GloVe learned them from how often words appear together across a whole body of text. Both give each word one fixed meaning, whatever the sentence.

NLP & Transformersbeginner4 min

Text Classification Pipelines

Sorting text into categories, from spam filters to support tickets.

Text Classification assigns categorical labels to raw text documents (sentiment analysis, spam detection, intent routing). Pipelines evolved from classical TF-IDF with Logistic Regression or Naive Bayes to fine tuned BERT models and zero shot LLM prompts. Production pipelines require robust text cleaning, handling class imbalance, threshold calibration, and monitoring for domain drift.

NLP & Transformersbeginner5 min

TF-IDF & BM25

The keyword scoring behind classic search engines, and why it still matters.

TF-IDF and BM25 are foundational lexical keyword search algorithms. TF-IDF weights words by Term Frequency (how often a word appears in a document) multiplied by Inverse Document Frequency (how rare the word is across the corpus). Okapi BM25 improves TF-IDF by adding Term Frequency Saturation and Document Length Normalization, serving as the default retrieval algorithm in Elasticsearch and Lucene.

NLP & Transformersbeginner4 min

Stemming, Lemmatization & Stopwords

Cleaning messy text before older NLP models can use it.

Text Preprocessing prepares raw natural language text for machine learning algorithms. Traditional NLP pipelines remove noise using Lowercasing, Stopword Removal (filtering out common filler words like 'the' or 'is'), Stemming (chopping word suffixes using heuristic rules), and Lemmatization (mapping words to valid dictionary roots). Modern Transformer language models use raw subword tokenization (BPE), rendering manual text preprocessing obsolete.

NLP & Transformersintermediate4 min

Self-Attention vs Cross-Attention

Words looking at their own sentence, versus looking at a different one.

Self Attention and Cross Attention are the two primary attention operations in Transformer models. In Self Attention, Queries, Keys, and Values all derive from the exact same input sequence, allowing tokens to attend to other tokens within the same sequence. In Cross Attention, Queries come from one target sequence (like a Decoder), while Keys and Values come from a separate source sequence (like an Encoder or text prompt).

NLP & Transformersintermediate4 min

Why Multi-Head Attention

Several attention steps side by side, each tracking a different relationship.

A single attention step can only focus on one kind of relationship at a time. Multi-head attention runs several smaller attention steps side by side, each with its own learned view of the words. One head might track which noun a pronoun refers to, another might track word order, another might link a verb to its object. Their results are then joined back together. It costs about the same as one large attention step, but captures several different relationships at once.

NLP & Transformersintermediate4 min

Why Divide by √d_k

Why attention divides its scores by a square root, and what breaks if it does not.

Attention scores how well two words match by multiplying their vectors together and adding up the result. The longer those vectors are, the bigger the scores tend to get. Very large scores push the softmax step to extremes, where one word gets nearly all the attention and the gradients almost vanish, so learning stalls. Dividing the scores by the square root of the vector length keeps them in a sensible range, whatever size the model is, so training stays healthy.

NLP & Transformersintermediate4 min

Causal Masking

Stopping a model from cheating by peeking at the next word during training.

A model like GPT learns by predicting the next word, so during training it must never be allowed to peek at the words that come after. Causal masking enforces that. Before attention decides which words to focus on, every score pointing at a future word is blocked out, so each word can only use itself and the words before it. This lets the model learn from every position in a sentence at once, in parallel, without cheating by looking ahead.

NLP & Transformersintermediate4 min

The Feed-Forward Block

The part of a Transformer that seems to store facts.

The Feed Forward Network (FFN) block is a two layer point wise dense network applied to each token independently in a Transformer block. While Multi Head Attention routes context between tokens, the FFN processes and transforms features within each token position. Research shows FFN layers act as associative key value memories, storing factual knowledge learned during pretraining. Modern architectures replace standard FFN blocks with SwiGLU gated activations or Mixture of Experts (MoE) routing.

NLP & Transformersintermediate5 min

Tokenizer Pitfalls (Numbers, Code, Unicode)

Why models struggle with spelling, maths and some languages: blame the tokenizer.

Tokenizer Pitfalls describe how subword tokenization artifacts negatively impact Large Language Model behavior. Issues include poor math reasoning due to arbitrary digit splitting, inefficient code indentation tokenization, trailing space sensitivity, and multilingual byte inflation. Understanding tokenizer quirks explains why LLMs fail simple character counting tasks like counting letters in strawberry.

NLP & Transformersintermediate4 min

Static vs Contextual Embeddings

Why bank should mean something different in river bank and bank account.

Static Embeddings (Word2Vec, GloVe) assign a single fixed vector to each word regardless of surrounding sentence context. Contextual Embeddings (BERT, RoBERTa) generate dynamic feature vectors where a word representation changes based on surrounding sentence context. Contextual embeddings resolve polysemy, distinguishing between 'bank' of a river and 'bank' for money.

NLP & Transformersintermediate4 min

Masked vs Causal Language Modelling

Fill in the blank, or guess the next word? Two ways to train a language model.

Masked Language Modeling (MLM) and Causal Language Modeling (CLM) are the two core self supervised pretraining paradigms in NLP. Masked Language Modeling (BERT) hides random tokens in an input sequence and trains the model using bidirectional context to fill in the missing words. Causal Language Modeling (GPT) hides future tokens using causal masking and trains the model left to right to predict the single next token.

NLP & Transformersintermediate4 min

NER & Sequence Labelling

Pulling names, places and dates out of plain text.

Named Entity Recognition (NER) is a core Information Extraction task that locates and classifies named entities in unstructured text into predefined categories (Person, Organization, Location, Date). NER is framed as a Token Level Sequence Labelling task using the BIO Tagging format (Begin, Inside, Outside). Architectures evolved from Conditional Random Fields (CRF) and BiLSTM-CRF to fine tuned BERT token classification heads.

NLP & Transformersintermediate5 min

Topic Modelling & LDA

Finding the main themes in thousands of documents nobody has labelled.

Topic modelling finds the main themes in a pile of documents without anyone labelling them. The classic method, LDA, assumes each document is a mix of a few topics and each topic is a mix of words, then works backwards from the word counts to find them. It might discover a topic made of goal, match and striker, which you would call football. Modern tools like BERTopic instead group documents by meaning using Transformer embeddings, and usually find cleaner topics.

NLP & Transformersintermediate5 min

Machine Translation

How translation went from phrase rules to neural networks.

Machine Translation (MT) converts source language text into target language text while preserving semantic meaning. Statistical Machine Translation (SMT) relied on phrase tables and language models. Neural Machine Translation (NMT) replaced hand-crafted rules with end-to-end sequence to sequence models (Encoder-Decoder LSTMs and Transformers). Evaluation relies on automatic overlap metrics (BLEU, chrF) and neural quality estimation models (COMET).

NLP & Transformersintermediate5 min

Summarization & ROUGE/BLEU

How to score a summary when there is no single right answer.

Text Summarization models are evaluated using automated n-gram overlap metrics (ROUGE and BLEU) and modern neural metrics. BLEU measures n-gram Precision (used mainly in translation). ROUGE measures n-gram Recall (used mainly in summarization to check if key facts were included). ROUGE-1 measures unigram overlap, ROUGE-2 measures bigram overlap, and ROUGE-L measures Longest Common Subsequence.

NLP & Transformersintermediate5 min

Extractive vs Abstractive QA

Copy the answer out of a document, or write it in your own words?

Question Answering (QA) algorithms extract or generate answers to user queries given context documents. Extractive QA models (BERT on SQuAD) locate the exact start and end character span tokens within a passage to extract text answers directly. Abstractive QA models (Generative LLMs) read source documents and synthesize fluent natural language answers in new words. Modern production systems combine vector search retrieval (RAG) with abstractive LLM generators.

NLP & Transformersintermediate5 min

Sentence Embeddings & Sentence-BERT

Turning a whole sentence into numbers so you can search by meaning.

A sentence embedding turns a whole sentence into a single list of numbers, so similar sentences end up close together. Plain BERT can only compare two sentences by reading them together, so finding the most similar pair among 10,000 sentences takes around 65 hours. Sentence-BERT is trained so each sentence becomes a vector on its own, just once. Comparing vectors is then quick arithmetic, and the same search takes about five seconds. This is what powers semantic search and RAG retrieval.

NLP & Transformersintermediate5 min

Beam Search & Decoding Strategies

Keeping several possible sentences going at once to find a better one.

Beam Search Decoding is a heuristic search algorithm used in seq2seq models, machine translation, and summarization to discover sequence outputs that maximize overall joint probability. Unlike Greedy Decoding (which picks the single highest-probability token at each step, missing better global sequences), Beam Search maintains a fixed number of B candidate hypotheses (Beam Width B). At each step, it expands all B paths into V next-token candidates, selects the top B highest cumulative log-probability paths, and repeats until end-of-sequence [EOS] tokens are generated.

NLP & Transformersintermediate4 min

Perplexity

Measuring how surprised a language model is when observing a sequence of text.

Perplexity (PPL) is the standard intrinsic evaluation metric for language models. It is exponentiation of the average negative log-likelihood (Cross-Entropy Loss) per token: PPL = exp(Cross-Entropy). Intuitively, Perplexity represents the effective branching factor: a Perplexity of 10 means the model is as confused at each step as if it were choosing uniformly among 10 equally likely words. Lower Perplexity indicates a better-fitting model with higher predictive confidence.

NLP & Transformersadvanced5 min

Positional Encodings & RoPE

Attention has no sense of word order, so we have to add it back in.

Positional Encodings inject token order information into Transformer models. Because self attention computes pairwise similarities without regard to word sequence order, Transformers require explicit position signals. Original Transformers used Absolute Sinusoidal Positional Encodings. Modern Large Language Models use Rotary Position Embedding (RoPE), which rotates Query and Key vectors in complex 2D planes to naturally encode relative distance between tokens.

NLP & Transformersadvanced5 min

Grouped-Query & Multi-Query Attention

Sharing keys and values across attention heads to save a lot of memory.

When a model generates text it stores keys and values for every past word, and that store, the KV cache, can eat most of the GPU's memory. Standard attention keeps a separate set for every attention head. Multi-query attention shares one set across all heads, which saves a lot of memory but can cost some quality. Grouped-query attention is the middle ground: heads are split into groups, and each group shares one set. It keeps nearly all the quality while cutting cache memory several times over.

NLP & Transformersadvanced4 min

Why Attention Is O(n²)

Double the text and attention costs four times as much. Here is why.

In standard attention, every word compares itself with every other word. With n words that is n times n comparisons, so the cost grows with the square of the length. Double the text from 4,000 to 8,000 words and the work and memory for attention go up four times, not two. That is the main reason long context windows are expensive, and why so much research goes into cheaper alternatives like FlashAttention, sliding windows and state space models.

NLP & Transformersadvanced5 min

FlashAttention & Efficient Attention

The same attention, two to four times faster, by moving less data around.

FlashAttention computes exactly the same attention as normal, just much faster. On a GPU the slow part is not the maths but moving a huge table of scores in and out of the large, slow memory. FlashAttention works on small tiles that fit in the tiny, fast memory, finishing each piece before moving on, so that giant table is never written out in full. Memory then grows in a straight line with length instead of with its square, and training runs two to four times faster.

NLP & Transformersadvanced5 min

Linear Attention, Mamba & SSMs

An alternative to attention that scales to a million words.

State space models like Mamba are an alternative to attention for long sequences. Attention compares every word with every other, so its cost grows with the square of the length. A state space model instead reads the sequence in order and carries a fixed-size summary forward, updating it at each step, so the cost grows only in a straight line. Mamba's key idea is letting each word decide what to keep or forget in that summary, which makes inputs of a million words practical.

SCROLL · SAVE · TAP TO GO DEEPER