Methods for computing over human language — turning raw text into representations a model can use, and the models and task families built on them, from rule-based preprocessing and count statistics through neural encoders. The treatment is linguistic and methodological: large decoder-only language models at scale, and speech as an audio signal, are separate subjects.
Foundations and Concepts
Every language technology begins with the same raw material: a collection of real text. That collection is called a Corpus, and almost everything a system later appears to know about language is a reflection of what its corpus happened to contain. A corpus of news reports, a corpus of legal judgments and a corpus of film reviews each teach a different version of the same language, which is why the first question to ask about any result is what text produced it. Before any computation happens, that text is surveyed, and the set of distinct word forms found in it becomes the Vocabulary — the fixed inventory of forms the system is prepared to recognise at all.
Counting words forces a distinction that beginners often blur, the one captured by Type vs Token. In the sentence “the cat sat on the mat” there are six tokens, because there are six word occurrences, but only five types, because “the” appears twice. Tokens measure how much text there is; types measure how varied it is. The ratio between them is the first crude signal of a text’s richness, and the gap between them is what makes a vocabulary much smaller than the corpus it came from.
Because the vocabulary is fixed when it is built, any system will eventually meet a word that is simply not in it — a new name, a typo, a technical coinage, a word in a dialect the corpus never sampled. Such a word is Out-of-Vocabulary (OOV), and handling it gracefully rather than discarding it is one of the recurring engineering problems of the field. A related but different resource is a Lexicon: not a list of what happened to occur, but a curated store of words with linguistic information attached to each one, such as its base form, its possible parts of speech and its senses. A vocabulary is an observation; a lexicon is knowledge.
Linguists describe language in layers, and this field borrows the layering wholesale, because each layer suggests different computations. Morphology is concerned with how individual words are built out of smaller meaningful pieces; each such piece is a Morpheme, so that “unhappiness” is really three of them joined together, “un”, “happy” and “ness”. One step up, Syntax governs how words combine into phrases and sentences, and explains why “the dog bit the man” and “the man bit the dog” use identical words to opposite effect. Above that sits Semantics, the layer of literal meaning: what a well-formed sentence actually asserts about the world.
Meaning, however, is never neatly one-to-one with form, and two situations are worth separating early. Polysemy describes one word carrying several related senses, as “mouth” does for a person and for a river — the senses are distinct but visibly connected. Homonymy describes two unrelated meanings that merely happen to share a form, like the “bat” that flies and the “bat” used to hit a ball. Both force a system to choose a sense from context rather than from the word alone. Beyond literal meaning lies Pragmatics, which deals with what a speaker intends in a situation: “can you pass the salt?” is grammatically a question about ability and practically a request, and only the context tells them apart.
These layers are not merely descriptive, because once a human marks them explicitly on real text the result becomes training material. Linguistic Annotation is exactly that act of labelling — marking word classes, phrase boundaries, senses or entities onto a corpus so that a machine has examples of the judgement it is being asked to reproduce. Annotation is slow and expensive, and its quality sets a ceiling on everything built from it.
Not every useful comparison needs linguistic knowledge, though. Edit Distance (Levenshtein) measures how far apart two strings are by counting the smallest number of single-character insertions, deletions and substitutions that turn one into the other, so “kitten” and “sitting” sit three edits apart. It is a purely surface-level measure, and precisely because it ignores meaning it is a dependable tool for matching misspellings, variant spellings and unfamiliar forms back onto known words.
Finally, one idea runs underneath the whole field and connects almost every technique that follows: Language Modelling, the task of assigning probabilities to sequences of words so that likely continuations score higher than unlikely ones. Framing language as prediction is what allows a machine to prefer “a strong cup of tea” over “a powerful cup of tea” without being told the rule, and it is the hinge between the descriptive vocabulary of this section and the statistical machinery of the rest.
Text Preprocessing
Raw text is messy in ways that matter enormously to a machine and not at all to a human reader. The same word may arrive capitalised, misspelt, wrapped in markup, padded with stray spaces or encoded two different ways, and a naive program will treat each variant as a separate word. Preprocessing is the disciplined reduction of that variety: a pipeline that turns a document into a clean, consistent sequence of units a model can count. It runs in a natural order — first tidy the characters, then cut the text into pieces, then reduce those pieces to their base forms, and finally, for modern neural systems, cut them into something smaller still.
Cleaning & Normalisation
The umbrella idea here is Text Normalization: deliberately collapsing harmless differences in form so that genuinely different content stands out. Every step below is a choice about which differences are harmless, and that choice depends on the task — which is why normalisation is a design decision, not a default.
The simplest step is Lowercasing, which merges “Apple” and “apple” into one form. It immediately shrinks the vocabulary, and it immediately destroys the distinction between a fruit and a company, so it suits topic-level work better than name-finding. Punctuation Removal strips commas, quotes and full stops, which helps when only content words matter and hurts when sentence boundaries or emoticons carry signal. Whitespace Normalization squeezes runs of spaces, tabs and line breaks into single separators, repairing the ragged spacing that copied and scraped text usually carries.
Two problems are invisible until they bite. Unicode Normalization addresses the fact that the same visible character can be stored in more than one way — an accented letter as a single code point or as a letter plus a combining accent, or curly quotes beside straight ones — so two strings that look identical compare as different until they are converted to one canonical form. HTML Stripping deals with text harvested from the web, where tags, scripts and entities must be removed so that markup is not mistaken for language. For everything else irregular there is Regular Expression Cleanup, the use of pattern rules to delete or rewrite recurring debris such as URLs, email addresses, phone numbers or boilerplate footers.
Two further steps change the content rather than its form. Stop Word Removal discards extremely common function words such as “the”, “of” and “is”, which carry little topical weight and consume a large share of the tokens; it is a sensible economy for keyword-style methods and a mistake wherever grammar matters, since “not” and “no” often sit on such lists. Spell Correction maps misspellings back onto known words, which can recover many otherwise unrecognised forms, but corrects confidently and sometimes wrongly — unusual names and technical jargon are its usual casualties.
Tokenization
Once the characters are clean, the text must be cut into units. Tokenization is that cutting, and it is the step that decides what the rest of the pipeline is even allowed to count. It is far less obvious than splitting on spaces: “don’t”, “New York”, “state-of-the-art” and “3.14” each force a decision, and languages written without spaces force all of them at once.
Cutting usually happens at two scales. Sentence Segmentation finds sentence boundaries, which is harder than looking for full stops because abbreviations, decimals and initials all end in one; it matters because so many later methods work one sentence at a time. Within a sentence, Word Tokenization produces the individual word-level units, resolving contractions, hyphens and attached punctuation along the way. Because these decisions are conventions rather than truths, shared conventions became standards: the Treebank Tokenizer applies the rule set used in the classic annotated treebanks, splitting “don’t” into “do” and “n’t” and separating trailing punctuation, so that text processed today lines up with corpora annotated decades ago.
Morphological Processing
Even after clean tokenization, one concept arrives wearing several costumes: “organise”, “organises”, “organising” and “organised” are four forms of one idea. Morphological processing folds those variants together so that evidence about a concept is pooled instead of scattered across near-duplicate entries.
The blunt approach is Stemming, which chops suffixes off by rule and accepts that the result need not be a real word — “studies” and “studying” both become “studi”, which is useless to read and perfectly serviceable as a key for matching. The best-known rule set is the Porter Stemmer, a compact sequence of suffix-rewriting steps for English that has been a default for decades, and its successor the Snowball Stemmer generalises the same idea into a small language for writing stemmers, so that many languages are covered and the aggressiveness can be tuned.
The careful approach is Lemmatization, which returns the real dictionary form — “was” to “be”, “mice” to “mouse” — by consulting linguistic knowledge instead of trimming letters, and often needs to know the word’s part of speech to choose correctly. A widely used implementation is the WordNet Lemmatizer, which looks each form up in a hand-built lexical database and therefore produces readable, trustworthy base forms at the cost of speed and of coverage for anything the database never recorded. Stemming is cheap and approximate; lemmatization is slower and right.
Subword Tokenization
Word-level units leave one problem unsolved. Any fixed word list is finite, so new names, typos and rare compounds arrive as unknowns, and vocabularies large enough to reduce that risk become unwieldy. Subword Tokenization escapes the dilemma by making the units smaller than words: frequent words stay whole, rare ones break into familiar fragments, and nothing is ever truly unrecognisable because the fragments can always be assembled. “Tokenizing” might become “token” plus “izing”, and an unseen surname becomes a handful of pieces rather than a shrug.
The pieces are learned from the corpus itself rather than designed. Byte-Pair Encoding (BPE) starts from single characters and repeatedly merges the most frequent adjacent pair into a new unit, growing a vocabulary of fragments that reflects what the text actually contains; stop merging when the vocabulary reaches the size you want. Byte-Level BPE runs the same procedure over raw bytes instead of characters, which means every possible input — any script, any emoji, any corrupted sequence — is representable without a special unknown symbol.
Variants differ in how they choose the merge or the split. WordPiece merges the pair that most improves the likelihood of the training text rather than the merely most frequent one, a slightly more principled criterion. Unigram Language Model Tokenization inverts the construction: it begins with a large pool of candidate fragments and prunes those the data can do without, then segments each word by picking the most probable combination of surviving pieces, which conveniently allows alternative segmentations to be scored. Tying these together in practice is SentencePiece, a tool that trains such vocabularies straight from raw text — treating the space as just another character — so that no language-specific word splitter is needed first, and the identical procedure serves languages that never write spaces at all.
Text Representation
A model cannot read; it can only compute with numbers. Text representation is the bridge — the step that turns cleaned, tokenized language into vectors — and the choice of bridge decides what the model is able to notice. The field’s history runs through three stages, each fixing a weakness of the last: long lists of word counts, then compact learned vectors in which similar words sit close together, and finally vectors that change with the sentence a word appears in.
Sparse Representations
The oldest and still the most interpretable approach treats a document as nothing more than the words it contains. That is the Bag of Words (BoW) view: word order is thrown away and only membership and frequency survive, so “the film was good, not bad” and “the film was bad, not good” look identical. The representation is a long vector with one slot per vocabulary entry, almost all of whose slots are zero for any single document — which is exactly what makes it sparse, and what makes it cheap to store.
What goes into each slot is the first decision. Binary Term Occurrence records only presence or absence, which suits short texts where a word is unlikely to repeat meaningfully. Count Vectorization instead records how many times each word occurs, keeping the intuition that a word repeated ten times matters more than one mentioned once. Some order can be smuggled back in with the N-gram, a contiguous run of n units treated as a single feature, so that “not good” becomes a feature in its own right and short phrases such as “machine learning” stop dissolving into unrelated words. Stacking one such vector per document produces the Document-Term Matrix, the rectangular table — documents down the side, vocabulary across the top — that classical text analysis works on.
Raw counts have an obvious flaw: the commonest words dominate while saying least. The standard remedy weighs two quantities against each other. Term Frequency (TF) captures how often a word appears in this document, the local evidence that it is what the document is about. Inverse Document Frequency (IDF) captures the opposite, global fact — a word appearing in nearly every document discriminates between none of them, so its weight is pushed down, while a word confined to a few documents is pushed up. Multiplying the two gives TF-IDF, which remains a startlingly strong baseline: it rates a word highly only when it is frequent here and rare elsewhere.
Refinements of that idea run in several directions. BM25 is the ranking function search engines grew up on; it keeps the same intuition but lets repeated occurrences saturate, so the tenth mention adds far less than the second, and it corrects for document length so long documents do not win by sheer size. Hashing Vectorizer attacks a practical problem instead: rather than building and storing a vocabulary, it sends each word through a hash function to a fixed number of slots, which allows streaming text of unlimited size at the price of occasional collisions and the loss of the ability to read a feature back as a word. Looking at pairs rather than single words, Pointwise Mutual Information (PMI) for Text measures how much more often two words co-occur than chance would predict, which is how word pairs such as “black” and “hole” are revealed as a unit — and that statistic is the hinge into the next section, since it describes words by their company.
Static Word Embeddings
Sparse vectors have no notion of similarity: “film” and “movie” occupy different slots and are as unrelated as “film” and “turnip”. The escape is one of the most productive ideas in the field, the Distributional Hypothesis — words used in similar contexts tend to mean similar things. If meaning is company, then observing a word’s neighbours over a large corpus is enough to place it.
Placing it is what a Word Embedding does: it assigns each word a short dense vector, a few hundred numbers, learned so that words with similar contexts get similar vectors. All those vectors together define an Embedding Space, a geometry in which distance means something — nearest neighbours are near-synonyms, and whole regions correspond to topics such as food, finance or weather. These are called static embeddings because each word gets exactly one vector for all time, whatever sentence it later lands in.
The method that popularised them is Word2Vec, which learns the vectors by setting up a simple prediction game over a sliding window of text. It comes in two mirror-image forms: Continuous Bag of Words (CBOW) predicts the missing middle word from its surrounding context and trains quickly, while Skip-Gram does the reverse, predicting the surrounding context from the middle word, which learns rare words better because each occurrence generates several training examples. Making either practical needs one trick, since scoring every vocabulary entry at every step is hopeless: Negative Sampling replaces that full comparison with a tiny one, asking the model only to prefer the genuine neighbour over a handful of randomly drawn words.
Other designs reach the same geometry differently. GloVe works not from a sliding window but from the global table of how often each pair of words co-occurs, fitting vectors whose relationships reproduce those aggregate ratios. FastText fixes a blind spot of the whole family: because each word is an indivisible symbol, a form never seen during training has no vector at all, and related forms such as “walk” and “walking” are learned independently. It represents a word as the sum of Subword Embeddings, vectors for the character fragments inside it, so morphology is shared and a brand-new word can still be assembled from pieces — a decisive advantage for languages that build long words out of many parts.
That these spaces capture structure and not just proximity is shown by the Word Analogy test, the celebrated observation that vector arithmetic lands in sensible places: king minus man plus woman arrives near queen, and Paris minus France plus Italy near Rome. The result is genuine evidence that directions in the space encode relations such as gender or capital-of, and it is also routinely oversold — analogies hold for some relations and fail for many others, and the biases of the training corpus are inherited along with the useful regularities.
Contextual Embeddings
One vector per word is a hard ceiling, because many words have several meanings and a static vector can only be their blurred average. The fix is to stop storing vectors and start computing them: Contextual Embeddings are produced on the fly for each occurrence, so the “bank” in “river bank” and the “bank” in “bank loan” receive different vectors from the same model.
The idea arrived at scale with ELMo, which read each sentence forwards and backwards with recurrent networks and used the internal states as the word’s representation — the first widely adopted demonstration that representations should be functions of the sentence, and the hinge on which the field turned towards pretrained models.
Once whole sentences are being encoded, it is natural to want a single vector for a span of text, and a Sentence Embedding is exactly that: one point standing for an entire sentence or paragraph, so that two sentences can be compared directly for meaning rather than word overlap. The simplest way to build one is a Pooled Sentence Vector, formed by averaging or taking the maximum over the token vectors — crude, order-insensitive, and often good enough to be the sensible first thing to try.
These sentence-level vectors changed how search works. Dense Retrieval encodes every document in a collection as a vector in advance, encodes the query the same way at search time, and returns the nearest neighbours, so a question phrased in entirely different words from the answering passage can still find it — the match is on meaning, not on shared keywords. It is the direct descendant of the sparse weighting schemes above, and the two are often combined, each covering the other’s failures.
Topic Modelling
Given tens of thousands of documents and no labels at all, the useful question is not what any single document says but what themes run through the collection. Topic modelling answers it without supervision: it discovers recurring clusters of words that tend to appear together, calls each cluster a topic, and describes every document as a mixture of them. Nobody specifies the topics in advance, and nobody names them — the method returns word groups such as “goal, match, coach, season” and leaves the reader to recognise sport. Two intuitions drive the whole family: documents about the same thing reuse the same words, and a document can be about several things at once.
The earliest approach treats the problem as one of geometry and compression. Latent Semantic Analysis (LSA) takes the large, sparse table of which words occur in which documents and factorises it into a far smaller number of dimensions, on the argument that the surface table is a noisy view of a simpler underlying structure. Squeezing it pulls synonyms together, because words that substitute for one another load on the same dimension, and so documents that share no vocabulary can still be recognised as similar. The same technique applied to search is known as Latent Semantic Indexing (LSI), where queries and documents are both projected into the reduced space and compared there — one method, two names, differing only in whether the goal is analysis or retrieval. Its weakness is interpretive: the dimensions are mathematically convenient but can carry negative weights, and a topic that is partly negative is not something a reader can picture.
Treating the problem as probability instead removes that awkwardness. Probabilistic Latent Semantic Analysis (pLSA) proposes an explicit story about how a document was written: for each word, first pick a topic, then pick a word from that topic’s vocabulary. Everything is a proper probability, so the output reads naturally — this document is sixty per cent one theme and forty per cent another. What it lacks is any discipline over the documents it has never seen, because it fits a free set of proportions to each training document individually and so has no principled way to describe a new one.
Supplying that discipline produces the method that became the standard. Latent Dirichlet Allocation (LDA) keeps the two-step generative story and adds an assumption about where a document’s mixture comes from: it is itself drawn from a distribution over mixtures. That assumption is encoded in a Dirichlet Prior, whose single concentration setting expresses a prior belief about concentration — a low value says each document is probably about one or two themes, a high value says themes are spread thinly across many. The prior does real work: it stops the model from fitting noise, it regularises rare words, and it lets an unseen document be placed without refitting.
A fitted model hands back two tables, and understanding them is understanding the output. The Document-Topic Distribution gives, for each document, the share of it belonging to each topic — the row you use to classify, cluster or recommend. The Topic-Word Distribution gives, for each topic, the probability of every word, and its highest-probability words are the only description of a topic you ever get; reading the top ten is how a topic acquires a human name. The first table says what each document is about, the second says what each topic is.
Not every method needs a probabilistic story. Non-negative Matrix Factorization for Topics returns to the factorisation idea but forbids negative values, so every topic is a sum of word weights and every document a sum of topic weights, with nothing cancelling anything out. The constraint alone buys much of the interpretability of the probabilistic models, and in practice it is fast and often yields noticeably crisper topics on short texts, which makes it a sensible alternative rather than a historical footnote.
All of this leaves a hard practical question: how many topics, and is the result any good? Likelihood on held-out text answers it poorly, because a model can grow statistically better while its topics become less readable. The usual recourse is Topic Coherence, which scores a topic by how strongly its top words genuinely associate in a reference corpus — a coherent topic puts “goal”, “match” and “coach” together, an incoherent one mixes “goal” with “mortgage”. Sweeping the number of topics and keeping the setting with the best coherence is the standard way to choose it, and it is only ever an approximation of the real criterion, which is whether a human finds the topics meaningful.
Probabilistic and Sequence Models
Language arrives in order, and that order carries much of the information. The models in this section are the pre-neural answer to it, and they share one framing: treat a sentence as a sequence of random choices, estimate the probabilities from counted data, and then search for the most probable explanation of what was observed. Three uses of that framing follow one another naturally — scoring how plausible a sequence of words is, labelling each position in a sequence, and generating a whole new sequence in another language. The machinery is still worth learning, both because it remains strong when data is scarce and because the problems it exposes are the ones later methods inherited.
Statistical Language Models
The first task is to say how likely a sentence is. In principle the probability of each word depends on everything before it, which is impossible to count; the working compromise is the N-gram Language Model, which assumes a word depends only on the few words immediately preceding it. With a window of three, “a strong cup of” makes “tea” highly likely and “brick” almost impossible, and the probabilities are simply counted from a corpus. The approximation is crude and astonishingly effective — it drove speech recognition and translation for decades.
Its fatal arithmetic is easy to see. Any plausible word sequence that happens never to occur in the training text gets a count of zero, and a zero multiplies the probability of the whole sentence to zero, declaring a perfectly ordinary sentence impossible. Everything else in this section is a cure for that zero, and the cures are collectively called smoothing: shave probability mass from what was observed and redistribute it to what was not.
The simplest cure is Laplace Smoothing (NLP), which pretends every possible sequence was seen one extra time. It is a single line of code and it never returns zero, but with a large vocabulary the invented counts swamp the real ones and it gives far too much weight to sequences that genuinely never occur. Good-Turing Smoothing is far more thoughtful: it estimates how much probability the unseen deserves from how many things were seen exactly once, reasoning that a corpus full of one-off events is a corpus likely to keep producing new ones — the data itself says how surprising the future should be.
Better still is to fall back on shorter contexts, since a four-word history may be unseen while its last two words are common. Backoff does this discretely: use the longest history that was actually observed, and if it was not, drop a word and ask again, discounting as it goes. Linear Interpolation Smoothing instead always blends all the orders at once, mixing the long-context and short-context estimates with learned weights, which is simpler to tune and tends to be more robust. The method that won in practice is Kneser-Ney Smoothing, whose insight is that a word’s fallback probability should depend not on how often it occurs but on how many different contexts it occurs in. “Francisco” is frequent yet appears almost only after “San”, so as a general-purpose guess it is a poor one — counting contexts rather than occurrences corrects exactly that, and the result remained the strongest count-based language model for years.
Sequence Labelling Models
The second task is to attach a label to every position in a sequence — a word class, or a mark saying that these three words name a company. Labels interact, because some sequences of labels are natural and others are nonsense, so the positions cannot be decided independently.
Before modelling, multi-word spans need encoding as per-token labels. The BIO Tagging Scheme does this with three marks: B for the beginning of a span, I for a token inside it, and O for everything outside, so two adjacent names do not silently merge. The BILOU Tagging Scheme refines it by marking the last token of a span and giving single-token spans their own label, which gives the model sharper evidence about boundaries and often measurably better accuracy at the cost of more labels to learn.
The classic model is the HMM Tagger, which tells a generative story: a hidden chain of labels moves from one state to the next with some probability, and each state emits the observed word. Two probability tables — label-to-label and label-to-word — are all it needs, and both can be counted from annotated text. Using it means searching an exponential number of label sequences, which is made tractable by the Viterbi Algorithm, a dynamic program that sweeps through the sentence keeping only the best path into each state at each position and then traces the winner back. It is the workhorse decoder of the whole family. Its companion, the Forward-Backward Algorithm, computes something different: not the single best path but the total probability flowing through each state, which is what lets the model be trained when the labels are unknown and what gives a per-position confidence rather than one hard answer.
Generative stories constrain what evidence can be used, because each word must be emitted from its label alone — awkward when the clues you want are overlapping features such as capitalisation, suffixes and neighbouring words. Discriminative models drop the story and model the labels given the words directly. The Maximum Entropy Model (MaxEnt) does so one position at a time, combining arbitrary weighted features and choosing the distribution that is as uniform as possible while still matching the observed feature statistics — committing to nothing the data does not support. Its limitation is that each position is normalised separately, which biases it towards states with few outgoing options. The Conditional Random Field (CRF) removes that flaw by scoring the whole label sequence at once and normalising globally, so rich features and label-to-label consistency are handled together. It became the standard for sequence labelling, and it still sits on top of neural encoders today as the layer that keeps the output sequence coherent.
Statistical Machine Translation
The third task puts both of the above to work at once. Statistical Machine Translation replaced hand-written translation rules with a simple and radical proposal: learn to translate from millions of sentence pairs that humans have already translated. The pieces are a model of how faithfully a candidate renders the source, a language model of the kind described above to keep the output fluent, and a search for the candidate that best satisfies both — fidelity and fluency pulling against each other.
The hard hidden problem is that the pairs are aligned only sentence to sentence; which word corresponds to which is unknown. The IBM Alignment Models solved it with a graded series of models that infer those word correspondences from co-occurrence alone, each adding a refinement the last one lacked — the tendency of words to keep their position, the fact that one word may render as several. Running them over a large parallel corpus yields a word-alignment, learned without anyone marking a single one by hand.
Word-by-word translation, however, produces stilted output, because meaning and word order live in groups of words rather than in single ones. Phrase-Based MT was the resulting mature design: extract from the alignments a large table of corresponding multi-word fragments, then build a translation by choosing a covering of the source with those fragments and reordering them. Because idioms and short constructions are memorised whole, local fluency improves dramatically, and this was the state of the art — and the system behind commercial translation — until neural models took over.
Neural NLP Models
Everything earlier in this chapter treated text as something to be counted: words tallied, probabilities estimated, features hand-designed. The models gathered here learn their own representation of language instead. A large network is shown an enormous quantity of ordinary text, given an artificial puzzle about that text to solve, and in solving it acquires a working sense of how words behave together. Only afterwards is the trained network pointed at a specific job, where it then needs comparatively little labelled data to do well.
That two-stage habit, one broad and expensive training run on raw text followed by many cheap reuses, sets the shape of this section. We start with the puzzles themselves, since a model is largely defined by what it was trained to predict. We then meet the two families of architecture built on those puzzles: models that only read, and models that read and write. We close with a question that arises only once a model can produce language at all, namely how it picks the actual words it emits.
Pre-training Objectives
Raw text is abundant; labelled text is scarce. A pre-training objective bridges that gap by hiding part of a passage and asking the model to restore it, so the text becomes its own answer key. No human annotation is needed, which is why these objectives can be run over billions of words.
Masked Language Modeling (MLM) is the best known of them. Scattered words in a passage are blanked out, and the model must recover each missing word from everything around it, the words before it and the words after. Because both sides stay visible, what the model learns at each position is a genuinely two-sided reading of it. Span Masking raises the difficulty by hiding a contiguous stretch of several words rather than isolated ones: guessing a whole phrase cannot be done from local grammar alone, so the model is pushed toward longer-range understanding.
Next Sentence Prediction (NSP) works one level up, on pairs of passages. Shown two chunks of text, the model judges whether the second really followed the first or was pulled from somewhere else. The aim is a feel for how sentences connect rather than for how words do. Later experiments found the signal weak and easy to pass for superficial reasons, and many models simply drop it.
Replaced Token Detection attacks a different inefficiency. When only a small fraction of positions is blanked, only that fraction teaches the model anything. So instead of removing words, this objective quietly substitutes plausible alternatives and asks the model to mark which positions were tampered with. Every position now carries a learning signal, and a given quality is reached with far less computation.
Denoising Autoencoder Pretraining generalises all of the above: corrupt a passage however you like, by deleting words, shuffling sentences or masking stretches, and train the model to emit a clean copy of the original. Because the output is a whole passage rather than a few filled blanks, it suits models that both read and write. Causal Language Modeling (CLM) is the strictest objective of the group: predict the next word using only the words to its left, never peeking ahead. That restriction is exactly what lets a trained model generate text one word at a time, with nothing but its own output as context.
Encoder Models
An encoder reads a passage and turns every word into a vector coloured by its neighbours on both sides. It produces understanding rather than sentences: ideal for judging, labelling or comparing text, unable to compose a reply. Most of the models below share one skeleton and differ in their training recipe, their size, or the languages they cover.
BERT was the first of them to be widely adopted, trained by combining masked word prediction with the sentence-pair objective, and it established the pattern of pre-training once and fine-tuning cheaply for each new job. RoBERTa keeps that architecture and repairs the recipe: much more text, longer training, larger batches, freshly chosen blanks each time a passage is seen, and no sentence-pair objective at all. Its lesson, that how a model is trained can matter more than how it is wired, runs through the rest of the family.
Two members trade a little accuracy for cost. ALBERT shrinks the parameter count by sharing one set of layer weights across depth and by factorising the large word-vector table, so a deep model stays modest in memory. DistilBERT takes the other route: a smaller student network is trained to reproduce the outputs of a full-size teacher, keeping most of its accuracy at roughly half the size and twice the speed. ELECTRA is the member built on replaced-token detection, and the clearest demonstration of that objective's efficiency. XLNet avoids blanking altogether by predicting the words of a passage in many different random orders; across enough orderings each word is eventually predicted from both sides, so two-sided context is gained without ever inserting an artificial placeholder that will never appear in real use.
Two are built for many languages at once. Multilingual BERT (mBERT) trains a single model on text from around a hundred languages over one shared vocabulary; because related languages end up sharing structure inside the model, a task trained where labelled data is plentiful often works in a language that has almost none. XLM-RoBERTa (XLM-R) applies the improved recipe to a far larger multilingual collection, and is the stronger choice for that kind of transfer.
The last three concern comparing two pieces of text. Word-level vectors are not directly useful for asking how close two sentences are, so Sentence-BERT (SBERT) fine-tunes an encoder until whole sentences land in a space where nearness means similarity of meaning. That gives the Bi-Encoder pattern: encode each text independently, store the vectors, and compare them later with one cheap geometric operation, which is what makes searching millions of documents feasible. A Cross-Encoder instead feeds both texts through the model together and emits a single score; seeing both halves at once is more accurate, but nothing can be precomputed, so every pair costs a full pass. In practice the two combine, a bi-encoder fetching a shortlist that a cross-encoder then reorders.
Encoder-Decoder Models
Give a reading network a writing half and the model can produce text as well as absorb it, consuming an input passage and emitting a new one. That single shape covers a surprising range of jobs, because so many of them can be phrased as turning one piece of text into another.
T5 pushes the idea to its logical end by casting every problem as text in and text out, with a short instruction prefixed to the input to say which problem it is. Classifying, translating, condensing and answering then share one format, one model and one training procedure. BART arrives from the denoising side: pre-trained to reconstruct deliberately corrupted passages, which is very nearly the job of rewriting text, it is correspondingly strong wherever an input has to be compressed or rephrased. mBART extends that denoising pre-training across many languages at once, giving one model that can rewrite or convert between them. MarianMT takes the opposite, pragmatic line: a large collection of small, fast models, each trained for a single language pair and light enough to run in ordinary production settings.
Decoding Algorithms
At each step a generating model outputs a probability for every word in its vocabulary. A decoding algorithm turns that stream of distributions into one concrete sentence, and the choice shows up directly in the character of what comes out.
Greedy Decoding takes the single likeliest word at every step and never reconsiders. It is fast and often adequate, but one early confident mistake can never be undone. Beam Search hedges by carrying several partial sentences forward together, extending each and keeping the best few by overall probability, so a strong continuation can rescue a weak start. It needs one correction: each extra word multiplies in another probability below one, so longer candidates score worse merely for being longer, and Length Normalization (Decoding) divides that effect out so curt, truncated answers do not always win.
Searching hard for the most probable sentence is right when there is a correct answer to find. It is wrong when variety matters, because the safest word, chosen again and again, is bland and repetitive. The remaining three methods therefore sample rather than search. Temperature Sampling flattens or sharpens the distribution before drawing from it: low settings behave almost greedily, high settings take more risks. Top-k Sampling restricts the draw to the k likeliest words, cutting off the long tail of nonsense that would otherwise occasionally be picked. Top-p (Nucleus) Sampling makes that cut adaptive, keeping just enough of the top words to reach a chosen share of the total probability: a narrow choice where the model is confident, a wide one where it is genuinely uncertain. Together with the objectives and architectures above, these settings decide how a neural model sounds, not merely what it knows.
NLP Tasks
The earlier parts of this chapter were about means: how to clean text, how to represent it, how to model it. This part is about ends. A task is a precise statement of what we want done with a passage, and the useful way to group them is by the shape of the answer: a single label for a whole text, a label for every word in it, a structure spanning the sentence, facts lifted out into a table-like form, or fresh text written in response.
That shape is not a presentational detail. It decides how training data must be annotated, which kind of model fits, and how success can be measured at all. The five sections below move from the simplest output shape to the most open-ended one.
Classification & Inference Tasks
Text Classification is the basic form: one passage goes in, one label from a fixed set comes out. Because the output is so small, these tasks are cheap to annotate, easy to score and a natural first application of any new representation.
Its best-known instance is Sentiment Analysis, deciding whether a review or a message is positive, negative or neutral, with the familiar traps of irony, negation and faint praise. Intent Classification is the same machinery pointed at a different label set: given what a user typed to an assistant, which of the actions the system supports was being requested. Spam Detection is the oldest widely deployed case of all, separating wanted mail from unwanted, and unusual in having an adversary who rewrites the text specifically to slip past the classifier. Stance Detection needs two inputs rather than one: a text and a claim, and the question is whether the text supports it, opposes it or ignores it. The same sentence can favour one claim and oppose another, so the label belongs to the pair, not to the text.
That pairwise flavour defines the rest of this group. Natural Language Inference (NLI) asks, of a premise and a hypothesis, whether the first entails the second, contradicts it, or leaves it undecided; it is the closest thing in this field to a test of everyday reasoning, which is why it is used so heavily as a diagnostic. Paraphrase Detection is a yes-or-no judgement on whether two sentences say the same thing in different words, useful for spotting duplicate questions and repeated content. Semantic Textual Similarity (STS) replaces that verdict with a graded score, recognising that two sentences may be partly, not wholly, about the same thing. Tasks over sentence pairs like these are the natural home of models that encode and then compare texts.
Sequence Labelling Tasks
Here the answer is as long as the input: one tag per word, in order. The structure is flat but the context matters enormously, because the right tag for a word usually depends on its neighbours, and a tag sequence has to be coherent as a whole rather than word by word.
Part-of-Speech (POS) Tagging marks each word with its grammatical category and so resolves words that could belong to several, which is the first step many pipelines take. Chunking groups adjacent words into flat phrases, a noun phrase here and a verb phrase there, giving shallow structure without the cost of a full parse. Named Entity Recognition (NER) finds the stretches of text that name people, organisations, places and dates, labelling each with its type; much of what follows later in this section is built on top of it. Slot Filling is its task-oriented cousin: in a spoken request to book a journey, mark which words give the destination and which the date, so an assistant can populate the fields of an action. Semantic Role Labeling goes after who did what to whom. Around each verb it marks the participants by the role they play, the doer, the thing affected, the instrument, the place, which is the layer of meaning that survives when the same event is described with a different arrangement of words.
Parsing & Resolution Tasks
Parsing returns a structure over the sentence rather than a flat row of tags. Two structures are in common use, and they answer slightly different questions.
Constituency Parsing builds a nested tree in which words combine into phrases and phrases into larger phrases, up to the whole sentence, showing how the sentence is assembled out of parts. Dependency Parsing describes the same sentence as direct labelled links between words, each word hanging off the word it modifies. It gets at who relates to whom more directly, and it transfers better to languages with freer word order, which has made it the more common choice in practice.
The two resolution tasks settle what words actually refer to. Coreference Resolution groups together the mentions that point at the same thing, so that a pronoun, a descriptive phrase and a name are recognised as one entity across a paragraph; without it, any system reading more than a single sentence loses track of who is being discussed. Word Sense Disambiguation handles the other ambiguity: a word with several established meanings must be assigned the one intended here, so that a bank beside a river is not confused with the one holding an account.
Information Extraction Tasks
Information Extraction names the overall ambition of this group: read unstructured prose and emit structured records, so that a shelf of documents can be queried like a table. It is where the labelling and parsing above start to pay for themselves, since each step narrows what the next one has to consider.
Once mentions have been found, Relation Extraction decides how two of them are connected, who founded which company or which treatment addresses which condition, turning isolated mentions into linked facts. Entity Linking pins each mention to a unique entry in a reference knowledge base, which is what distinguishes two people who share a name and what allows facts gathered from different documents to be merged safely. Event Extraction looks for happenings rather than things: a word that signals the event, plus the participants, the time and the place arranged around it. Open Information Extraction abandons the fixed schema altogether, pulling out whatever subject, relation and object triples a sentence happens to offer; the output is messier, but the method can be aimed at any subject area without commissioning new annotation. Question Answering sits at the end of the group as its most user-facing form: given a question and a document or a collection, return the answer, often as a stretch of the source text, which is why it is scored much like extraction is.
Generation Tasks
The tasks above return labels and structures, which can be marked right or wrong. The tasks here return language, where many different outputs are acceptable and none is the single correct one. That one difference changes how these systems are trained, how they fail and how they must be judged.
Text Generation is the umbrella: produce fluent, coherent text that continues from or responds to an input. Machine Translation is the oldest concrete case, carrying meaning from one language into another under the strict constraint that nothing may be added or quietly lost. Condensing a document comes in two kinds worth keeping apart. Extractive Summarization selects the most important sentences already present and strings them together, which guarantees that every word is faithful to the source but often reads disjointedly. Abstractive Summarization writes new sentences that compress the content, which reads far better and brings the real risk of asserting something the source never said.
Headline Generation is condensation at its most extreme: one short line that must be accurate and also make a reader want to continue. Paraphrase Generation keeps the meaning and changes the wording, which serves both rewriting tools and the manufacture of extra training examples. Dialogue Generation adds the hardest ingredient, memory: each reply must fit not only the last message but everything said earlier, and stay consistent about what the system has already claimed. Across all of these the output is one of many acceptable answers, which is exactly why judging quality is itself an open problem, and the subject of the section that follows.
Evaluation in NLP
A reported score is only as meaningful as the measure behind it, and measuring a language system is harder than measuring one that predicts a number or a category. For most interesting outputs there is no single correct answer: two renderings of a sentence into another language can both be perfect and share hardly a word, and two condensed versions of a report can be equally faithful while emphasising different things. Everything in this section is an attempt to get a usable number out of that situation, and each measure buys its convenience with a specific blind spot worth knowing before quoting it.
Human Evaluation is the ground truth that all the rest approximate. Readers rate outputs for accuracy, fluency and usefulness, or choose between two systems' answers placed side by side. It is the only measure that reflects what a reader actually experiences, and it is slow, costly and hard to reproduce: judges disagree with each other, and the same judge drifts over a long session. So it is kept for final checks and published comparisons, while automatic measures carry the daily work of development, where a model is scored hundreds of times a week.
When the expected answer is short and definite, direct comparison suffices. Exact Match (EM) awards credit only when the produced string is identical to the reference. That is unforgiving by design, appropriate when the answer is a name or a figure, and unfairly harsh when a correct answer merely carries an extra article or a different spelling. Span F1 softens the judgement for answers that are stretches of text: it compares the predicted stretch with the reference at the level of overlapping words, balancing how much of what was returned is correct against how much of the correct material was returned at all. A nearly right boundary therefore scores nearly right, which is what makes it the standard companion to extraction and reading tasks.
For whole generated sentences, the usual approach is to compare the output with one or more reference texts by counting the pieces they share. BLEU counts how many of the output's short word sequences also occur in the reference and penalises output that is suspiciously brief; it has been the default for translation for two decades, and it is blind to a perfectly good synonym. ROUGE turns the emphasis around for condensed text, asking instead how much of the reference's content the output managed to cover. METEOR repairs some of that rigidity by matching word stems and synonyms rather than identical strings alone, tracking human opinion more closely at a higher computational cost and with a dependence on language resources. chrF drops below the word altogether and compares sequences of characters, which is markedly fairer to languages that build long words out of many parts, and to outputs that differ from the reference only in an ending.
Two measures count the repair work an output needs instead of the overlap it achieves, and for both a lower figure is the better one. Translation Edit Rate (TER) reports the proportion of insertions, deletions, substitutions and block moves a person would have to perform to turn the system's sentence into the reference. Word Error Rate (WER) applies the same edit-counting logic where there genuinely is one intended sequence of words, as in transcription, so that any departure from it counts as an error.
BERTScore abandons string matching entirely. It represents both the output and the reference with a pre-trained model and pairs their words by similarity of meaning, so a synonym or a reordering is no longer punished. It follows human ratings more faithfully than the counting measures, at the price of depending on a model, and inheriting that model's biases and uneven language coverage. Perplexity is the odd one out here, because it measures a model rather than an output: how surprised the model is by held-out text it has never seen. Lower perplexity means it assigns higher probability to real language, which makes it the standard gauge while a model is being trained, and it says nothing about whether the model is useful for any particular job.
Finally, benchmarks package data, tasks and measures together so that different systems can be compared on equal footing. GLUE collects a spread of sentence and sentence-pair problems into one leaderboard with a single aggregate figure, which is how progress in this field came to be discussed as a number. SuperGLUE was assembled once models began to saturate that first collection, deliberately harder problems chosen to leave room for improvement, and it illustrates the usual lifecycle: a benchmark is informative until it is solved, then becomes a floor rather than a target. SQuAD plays the same role for reading comprehension, pairing passages with questions whose answers are stretches of those passages, and scoring them by exact agreement and by overlap. It is the clearest illustration of how a task, its data and its measures arrive as a single package, and of why a score always has to be read together with the package it came from.