Robot AI -- Natural Language Processing

Memory tricks that make tokenization, BERT and LLMs click

From bag-of-words to transformer language models -- these memory tricks lock in the NLP pipeline, text representations, core tasks, and the prompt engineering that makes LLMs useful.

Community
📋
NLP Forum
Ask questions · Share tricks
💬
NLP Study Room
Live · Study together now

Or continue to the sub-topics below for more specialized Study Rooms and Forums

Natural Language Processing

Memory Tricks

Proven Mnemonics & Acronyms — fast to learn, hard to forget.

NLP Pipeline
NLP PIPELINE -- Tokenize, Normalize, Represent, Model, Evaluate
RAW TEXT TO PREDICTIONS IN FIVE STEPS
Modern LLMs skip most preprocessing -- trained end-to-end with BPE subword tokenization
Tokenization: split into tokens. Normalization: lowercase, punctuation, contractions. Stop word removal: remove high-frequency low-information words. Stemming/Lemmatization: reduce to root form. Representation: convert to numerical vectors (BoW, TF-IDF, embeddings). Model: ML or DL algorithm. Evaluate: task-specific metric.
Tokenization
Split text into words, subwords, or characters
Normalization
Lowercase, punctuation handling, contraction expansion
Lemmatization
Returns actual dictionary base form (better than stemming)
Modern LLMs
Skip most preprocessing -- end-to-end with BPE tokenization
Text Representation
BOW to TF-IDF to Word2Vec to BERT -- from counting words to understanding meaning
FOUR GENERATIONS OF TEXT REPRESENTATION -- EACH MORE POWERFUL
BERT gives same word different vectors based on context -- bank in finance vs bank of river
Bag of Words (BoW): word counts, ignores order and context, sparse. TF-IDF: weights rare domain terms higher, still sparse. Word2Vec/GloVe: dense semantic vectors, king - man + woman = queen, fixed per word. BERT / contextual embeddings: same word gets different embedding based on surrounding context. All modern NLP uses contextual embeddings.
BoW
Word counts -- sparse, ignores order and context
TF-IDF
Weights rare words higher -- still sparse but smarter
Word2Vec
Dense semantic vectors -- arithmetic works, but context-free
BERT / contextual
Same word, different vector based on context -- most powerful
BERT vs GPT
BERT reads the whole sentence (bidirectional). GPT reads left-to-right only.
ENCODER FOR UNDERSTANDING -- DECODER FOR GENERATION
BERT cannot generate text. GPT cannot see the right context. Both are excellent at what they do.
BERT (Encoder-only, Bidirectional): sees entire sequence simultaneously, trained on masked language modeling, excellent for classification, NER, question answering, cannot generate text. GPT (Decoder-only, Autoregressive): sees only left context, trained on next-token prediction, excellent for text generation, creative writing, code, conversation. T5/BART: Encoder-Decoder -- best for translation and summarization.
BERT encoder-only
Bidirectional, masked LM, understanding tasks: classification, NER, QA
GPT decoder-only
Left-context only, next-token prediction, generation tasks
T5 and BART
Encoder-Decoder -- translation, summarization, seq2seq tasks
Why GPT dominates now
Scale + emergent few-shot abilities -- can do BERT tasks via prompting
Tokenization (BPE)
BPE -- Byte Pair Encoding: merge the most frequent character pair, repeat until vocabulary size reached
NO TRUE OUT-OF-VOCABULARY WORDS WITH SUBWORD TOKENIZATION
750 English words is approximately 1000 tokens -- other languages use more tokens per word
BPE Algorithm: start with character vocabulary, count all character pairs, merge most frequent into new token, repeat until target vocabulary size. Result: common words as single tokens, rare words split into subword units. No true OOV words -- any word can be handled. GPT models: 50K-100K token vocabulary. Token count affects cost, speed, and context window utilization.
BPE algorithm
Merge most frequent character pairs iteratively until target vocab size
No OOV words
Any word can be split into known subword units
Token counting
750 English words ~ 1000 tokens. Other languages: more tokens per word.
Vocabulary size
GPT models: 50K-100K token vocabulary
Prompt Engineering
CLEAR -- Context, Length, Examples, Ask specifically, Role assignment
BETTER PROMPT = BETTER OUTPUT -- PROMPT ENGINEERING IS A SKILL
Chain-of-Thought: adding Let's think step by step dramatically improves reasoning accuracy
Zero-shot: just ask -- no examples. Few-shot: provide 2-5 examples of desired format. Chain-of-Thought (CoT): add Let's think step by step -- improves math, logic, multi-step reasoning. Role prompting: Act as an expert... -- calibrates vocabulary, depth, style. Structured output: Respond in JSON format. RAG: retrieve context to ground LLM in real facts and reduce hallucination.
Zero-shot
Just ask -- no examples needed for simple clear tasks
Few-shot
Give 2-5 examples -- improves consistency and format
Chain-of-Thought
Let's think step by step -- dramatic improvement on reasoning
RAG
Retrieve documents, inject as context -- reduces hallucination
NLP Evaluation
BLEU scores translation -- ROUGE scores summaries -- Perplexity scores language models
DIFFERENT TASKS NEED DIFFERENT EVALUATION METRICS
BLEU measures n-gram overlap -- it misses semantic equivalents like automobile vs car
BLEU: n-gram overlap between generated and reference translations. Range 0-1. Correlates with human judgment but misses semantic equivalents. ROUGE: n-gram overlap for summarization. ROUGE-1 (unigrams), ROUGE-2 (bigrams), ROUGE-L (longest common subsequence). Perplexity: how well LM predicts test set -- lower is better. BERTScore: uses embeddings for semantic similarity -- better than n-gram metrics.
BLEU
N-gram overlap for translation -- misses semantic equivalents
ROUGE
N-gram overlap for summarization -- ROUGE-1, ROUGE-2, ROUGE-L
Perplexity
How surprised LM is by test text -- lower = better LM
BERTScore
Semantic similarity via embeddings -- better than BLEU/ROUGE
Machine Translation
ENCODE source then ATTEND to relevant parts then DECODE to target language
FROM RULE-BASED TO STATISTICAL TO NEURAL TO TRANSFORMER
Parallel corpora are needed for training -- back-translation helps low-resource languages
History: Rule-based (1950s-80s), Statistical phrase-based (1990s-2010s), Neural (2014 -- seq2seq + attention), Transformer (2017 -- surpassed all previous). Modern LLMs competitive for most language pairs. Parallel corpora: same content in two languages needed for training. Back-translation: translate target to source synthetically, use as additional training data.
Rule-based
Hand-crafted grammar rules -- limited coverage
Statistical (SMT)
Phrase-based, learns from parallel corpora
Neural (NMT)
Encoder-decoder + attention -- first major DL NLP breakthrough
Transformer (2017)
Surpassed RNN systems immediately -- now the standard
Information Retrieval
SPARSE uses keywords -- DENSE uses meaning -- HYBRID uses both
BM25 FOR EXACT TERMS AND SEMANTIC SEARCH FOR MEANING -- COMBINE FOR BEST RESULTS
RAG: retrieve top-K chunks and inject into LLM prompt to ground answers in real facts
Sparse retrieval (BM25, TF-IDF): keyword matching -- fast, interpretable, handles exact terms (names, codes). Dense retrieval: semantic embedding similarity -- finds relevant documents even if keywords differ. Two-stage: BM25 narrows candidates (fast), dense re-ranks (accurate). RAG pipeline: embed documents, store in vector DB, retrieve top-K, inject into LLM prompt.
BM25
Keyword matching -- fast, exact terms, still a strong baseline
Dense retrieval
Semantic embeddings -- finds synonyms and paraphrases
Two-stage pipeline
BM25 narrows, dense re-ranks -- best of both worlds
RAG
Retrieve top-K chunks, inject as LLM context, cite sources
Speech Recognition
ASR = Acoustic Signal to Recognition to transcript -- convert audio to text
WHISPER IS OPEN SOURCE AND NEAR-HUMAN ACCURACY ON ENGLISH
WER = (Substitutions + Deletions + Insertions) / Total words -- lower is better
ASR pipeline: audio signal to features (mel spectrogram) to model to text. Traditional: acoustic model + pronunciation dictionary + language model. Modern end-to-end: CTC or attention encoder-decoder. Whisper (OpenAI 2022): trained on 680K hours of multilingual audio, near-human on English, open-source and free to run locally. WER (Word Error Rate): standard evaluation metric.
Traditional ASR
Acoustic model + pronunciation dictionary + language model
End-to-end (CTC)
Directly map audio features to character sequences
Whisper
680K training hours, multilingual, near-human WER, open-source
WER formula
(Substitutions + Deletions + Insertions) / Total reference words
Coreference
COREFERENCE -- John told Mary he liked her -- who is he and who is her?
IDENTIFY WHICH WORDS IN A TEXT REFER TO THE SAME REAL-WORLD ENTITY
Winograd Schema Challenge: The trophy does not fit because it is too big -- what is too big?
Coreference resolution identifies expressions referring to the same entity. Types: pronouns (he, she, it), noun phrases (the president), proper names (John). Challenge: requires world knowledge and reasoning. Example: The city council refused the protesters a permit because they feared violence -- they = city council, not protesters. Applications: reading comprehension, information extraction, summarization.
Pronouns
He, she, it, they -- must resolve to named entities
Noun phrases
The president, the company -- track across long documents
Winograd Schema
Tests common-sense reasoning for coreference resolution
Applications
Reading comprehension, information extraction, summarization
Text Generation Decoding
GREEDY picks top token -- SAMPLING picks randomly -- TEMPERATURE controls creativity
TOP-P NUCLEUS SAMPLING IS THE STANDARD IN PRODUCTION LLM APPLICATIONS
Top-P (nucleus sampling): sample from smallest set of tokens whose cumulative probability exceeds P
Greedy: always pick highest probability token -- deterministic, fast, repetitive. Sampling: randomly sample from distribution -- diverse but can be incoherent. Temperature: below 1 = sharper (conservative), above 1 = flatter (creative). Top-K: sample from top K tokens only. Top-P (nucleus): sample from smallest token set with cumulative probability above P -- adapts to distribution shape, most widely used. Repetition penalty: downweight already-generated tokens.
Greedy
Always pick highest prob -- deterministic but repetitive
Temperature < 1
Sharper distribution -- more conservative, predictable
Temperature > 1
Flatter distribution -- more creative, sometimes incoherent
Top-P (nucleus)
Most widely used -- adapts to actual distribution shape
🎯 Exam Favorite
TOKENIZATION = Chopping a SENTENCE into LEGO BRICKS before the model reads it
TEXT IN → TOKENS OUT → MODEL READS
Tokenization — the first step in all NLP
Before any NLP model reads text, it must be tokenized — split into tokens. Tokens can be words, subwords, or characters depending on the tokenizer. "unhappiness" might become ["un", "happy", "ness"] — three tokens. Why subwords? They handle rare words and new words gracefully. GPT uses byte-pair encoding (BPE). A typical paragraph becomes 100–150 tokens. Everything in an LLM is measured in tokens — context windows, costs, limits.
🧠 Vivid Story
WORD EMBEDDINGS = Giving every word an ADDRESS in a city where similar words live close together
KING − MAN + WOMAN ≈ QUEEN
Word embeddings — meaning as location in space
Word embeddings map each word to a point in high-dimensional space (e.g., 300 numbers). Similar words cluster together — "king" and "queen" are close. The magic: vector arithmetic captures meaning. King − Man + Woman ≈ Queen. Paris − France + Italy ≈ Rome. The model doesn't understand meaning — it learns that words appearing in similar contexts get similar coordinates. Word2Vec, GloVe, and modern contextual embeddings (BERT) all work on this principle.
🔑 Key Distinction
BERT reads BOTH DIRECTIONS — GPT reads LEFT TO RIGHT only
BIDIRECTIONAL vs AUTOREGRESSIVE
BERT vs GPT — two fundamentally different Transformer approaches
Both BERT and GPT are Transformer-based but trained differently. BERT: trained by masking random words and predicting them using context from both left AND right — bidirectional. Best for understanding tasks (classification, named entity recognition, question answering). GPT: trained to predict the next word reading left to right — autoregressive. Best for generation tasks (writing, completing text, chatting). BERT is the reader; GPT is the writer.
💡 Concept Anchor
NAMED ENTITY RECOGNITION = The model HIGHLIGHTS the nouns that ARE something — people, places, orgs
NER — FIND THE WHO, WHERE, AND WHAT
Named Entity Recognition (NER) — finding the important nouns
NER identifies and classifies named entities in text: People (Barack Obama), Organizations (Google, WHO), Locations (Paris, Antarctica), Dates (March 12, 2024), and more. It's one of NLP's most practical tasks — used in news analysis, medical records, financial documents, and search engines. A sentence like "Apple announced in Cupertino that Tim Cook signed a deal with Samsung" yields: Apple (ORG), Cupertino (LOC), Tim Cook (PERSON), Samsung (ORG).
📅 Quick Reference
RAG = OPEN BOOK EXAM — the model looks things up before answering instead of relying on memory
RETRIEVE · AUGMENT · GENERATE
Retrieval-Augmented Generation — why it reduces hallucinations
RAG gives LLMs access to a knowledge base at inference time. Instead of relying purely on memorized training data: Retrieve relevant documents from a database, Augment the prompt with that retrieved context, Generate an answer grounded in the retrieved facts. Result: far fewer hallucinations, up-to-date answers, and citations. Think of it as the difference between a closed-book exam (pure LLM) and an open-book exam (RAG). Most enterprise AI systems use RAG.
⭐ Most Important
TOKENIZE → EMBED → ENCODE → DECODE → GENERATE — the complete NLP pipeline
FIVE STAGES FROM RAW TEXT TO FINAL OUTPUT
The modern NLP pipeline end to end
Every modern NLP system follows this pipeline: Tokenize (split raw text into tokens — subwords), Embed (map each token to a dense vector), Encode (run through transformer layers to build contextual representations — BERT-style), Decode (generate output tokens one at a time — GPT-style), Generate (apply sampling strategy — greedy, beam search, temperature). Understanding each stage lets you diagnose failures: garbled output could be tokenizer, poor coherence could be decoding strategy.
Tokenize
Raw text → token IDs using a learned vocabulary (BPE, WordPiece)
Embed
Token IDs → dense vectors + positional encoding
Encode/Decode
Transformer layers build or generate representations
Generate
Sampling strategy converts logits to final token choices
🐍 Code
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokens = tokenizer("Hello world", return_tensors="pt")
model = AutoModel.from_pretrained("bert-base-uncased")
outputs = model(**tokens) # contextual embeddings
🎯 Exam Favorite
BLEU measures PRECISION of n-grams · ROUGE measures RECALL of n-grams
BLEU FOR TRANSLATION · ROUGE FOR SUMMARIZATION
NLP evaluation metrics — BLEU vs ROUGE
BLEU (Bilingual Evaluation Understudy): measures how many n-grams in the machine output appear in the reference translation — precision-oriented. Standard for machine translation. Range 0–1 (higher = better). ROUGE (Recall-Oriented Understudy for Gisting Evaluation): measures how many n-grams in the reference appear in the generated summary — recall-oriented. Standard for text summarization. ROUGE-1 (unigrams), ROUGE-2 (bigrams), ROUGE-L (longest common subsequence). Both compare to human reference outputs.
BLEU
Precision of n-grams — machine output vs reference. Used for translation.
ROUGE
Recall of n-grams — reference vs machine output. Used for summarization.
Perplexity
How surprised is the model by test text? Lower = better language model.
🐍 Code
from nltk.translate.bleu_score import sentence_bleu
reference = [["the", "cat", "sat"]]; hypothesis = ["the", "cat", "sat"]
bleu = sentence_bleu(reference, hypothesis)
# For ROUGE: pip install rouge-score
from rouge_score import rouge_scorer
🔑 Key Distinction
SEMANTIC SEARCH = MEANING · KEYWORD SEARCH = EXACT WORDS — embeddings make semantic possible
SPARSE vs DENSE RETRIEVAL
Why semantic search beats keyword search for complex queries
Keyword search (TF-IDF, BM25): finds documents containing the exact query words. Fails when synonyms are used or the concept is expressed differently. Semantic search: converts query and documents to dense vector embeddings, retrieves by cosine similarity in vector space. "Heart attack" retrieves "myocardial infarction" documents because their embeddings are close. Used in RAG systems for the retrieval step. FAISS and vector databases (Pinecone, Weaviate, Chroma) store and search billions of embeddings efficiently.
Keyword (sparse)
Exact word matching — fast, interpretable, fails on synonyms
Semantic (dense)
Embedding similarity — handles synonyms, paraphrases, concepts
Hybrid
Combine both — best of precision (keywords) and recall (semantics)
🐍 Code
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(["Heart attack", "myocardial infarction"])
from sklearn.metrics.pairwise import cosine_similarity
print(cosine_similarity([embeddings[0]], [embeddings[1]]))
💡 Concept Anchor
FINE-TUNING vs PROMPTING — two ways to customize an LLM for your task
WHEN TO FINE-TUNE · WHEN TO PROMPT
Choosing between fine-tuning and prompt engineering
Prompting: write better instructions, add examples (few-shot), structure your query. Fast, cheap, no training needed. Sufficient for most tasks. Fine-tuning: update the model weights on your specific task data. Needed when: the task requires a consistent style/format the model struggles to follow via prompting, you have thousands of task-specific examples, or you need better performance than prompting achieves. Rule of thumb: always try prompting first. Fine-tune only if prompting hits a ceiling.
Prompting
Fast, cheap, flexible — try this first for every task
Fine-tuning
Better consistency and performance — requires labeled data and compute
LoRA
Efficient fine-tuning — update only 1% of parameters, get 99% of the benefit
🐍 Code
# Prompting — no training required
response = client.messages.create(model="claude-sonnet-4-6",
messages=[{"role":"user","content":"Classify sentiment: I love this!"}])
# Fine-tuning with LoRA (parameter-efficient)
# from peft import LoraConfig, get_peft_model
0
Correct
0
Missed
0
Remaining
What does this mean / stand for?
0
Correct
0
Wrong
0
Remaining
🔗 Related Sub-Subjects
🔬 Deep Learning
Transformers, BERT, GPT — the deep learning architectures that power modern NLP.
Deep Learning →
✍️ Prompt Engineering
How to get the best output from LLMs — prompting techniques, RAG, and agents.
Prompt Engineering →
📈 Model Evaluation
BLEU, ROUGE, perplexity — how NLP models are measured and compared.
Model Evaluation →
🎓 Common Exam Questions
Q: What is the difference between word-level and subword tokenization?
A: Word-level tokenization splits on spaces — "running" is one token. Problems: large vocabulary, out-of-vocabulary words. Subword tokenization (BPE, WordPiece) splits rare words into known pieces — "unhappiness" → ["un", "happy", "ness"]. Handles any word, smaller vocabulary, no OOV problem. GPT-4 uses BPE. BERT uses WordPiece. Both produce ~30,000-50,000 token vocabularies that can represent virtually any text.
Q: What is the context window and why does it matter?
A: The context window is the maximum number of tokens an LLM can process in a single forward pass. Everything outside this window is forgotten. GPT-3: 4,096 tokens. GPT-4: 128,000 tokens. Claude: up to 200,000 tokens. For RAG: you must fit retrieved documents + question + answer within the context window. For summarization: very long documents must be chunked or recursively summarized. Context window is one of the most important practical LLM constraints.
Q: Explain how RAG reduces hallucinations.
A: RAG (Retrieval-Augmented Generation) gives the model access to a current, authoritative knowledge base at inference time. Instead of relying on memorized training data: retrieve relevant chunks from the knowledge base, inject them into the prompt as context, generate an answer grounded in that context. The model is now answering from provided facts rather than from memory — dramatically reducing hallucinations and enabling citations. Critical for enterprise applications where factual accuracy matters.
Q: What is the difference between extractive and abstractive summarization?
A: Extractive summarization selects and returns the most important sentences from the original text verbatim — no generation required. Fast, no hallucination risk. Abstractive summarization generates a new summary in its own words, potentially shorter and more coherent than extracted sentences. Requires a generative model and can introduce hallucinations. Modern LLMs do abstractive summarization by default. Extractive is used when faithfulness to original wording is critical.
Q: What is named entity recognition and give three practical applications?
A: NER identifies and classifies proper nouns in text: Person, Organization, Location, Date, Product, etc. Applications: (1) News analysis — automatically tag articles by mentioned companies and people for search. (2) Medical records — extract patient names, diagnoses, drug names, dates from clinical notes. (3) Financial compliance — flag mentions of regulated entities, insider trading suspects, or sanctioned companies in communications.