← MAIN
10 // MARKOV CHAINS

MARKOV TEXT

A chain that writes one token at a time, drawn from counts of what followed each phrase in a book.
COPIED — LONGEST RUN —

HOW TO USE

The goal is to watch a Markov chain write text one token at a time, using only counts of what followed each short run of words in a public-domain book. Press GENERATE to run the chain, or STEP to advance it one token at a time.

Choose a corpus and a token level in SOURCE, then set ORDER and TEMPERATURE in THE DIALS. Space starts and pauses the chain, and n takes one step.

The next-token panel shows the candidates after the current context, with the sampled one flashing. The copy meter shows the share of picks that sit in a verbatim run of 8 words (20 characters) or more, and the longest run shows the longest stretch that occurs in the book.

THE CHAIN SPEAKS
Press GENERATE, or STEP for one token at a time.
NEXT-TOKEN PANEL
Context window
The sampled candidate flashes.
COPY METER
Share of picks copied verbatim
No picks yet.
Transcript and source
SOURCE
CORPUS
VOCAB — · CONTEXTS — · N-GRAMS —
TOKENS ARE
THE DIALS
ORDER n: 3
TEMPERATURE: 1.00
More settings
SEED
SPEED: 6 TOKENS PER SECOND
LENGTH

HOW IT WORKS

A Markov chain writes text by looking only at the last few tokens. A token is one unit of text: a word or punctuation mark at word level, or a single character at character level. The model is nothing but counts. For every run of n − 1 tokens in a corpus, the body of text the model is built from, it stores how often each token followed that run. Generating means reading the current context, drawing the next token in proportion to those counts, appending it, and repeating. The page runs a JavaScript port of the Python package markov, which produces the same tokens for the same corpus, order, temperature and seed.

Corpora and tokens

The four bundled corpora are public-domain texts: chapter 1 of Alice's Adventures in Wonderland (1865), chapter 1 of Pride and Prejudice (1813), Shakespeare's sonnets I to XV, and the Preamble and Article I of the US Constitution1. Each file begins with a source header, which the model skips. Only the text after the separator line is used2.

Tokenization splits the text into tokens. Every run of whitespace first collapses to one space. At word level a token is either a run of ASCII letters, with inner apostrophes allowed, straight or curly, as in Don't, or a single other non-space character such as a comma or a digit3. At character level every character is a token, including the space4. The JavaScript port uses the same pattern5.

Example. The text Don't stop. becomes three word tokens: Don't, stop and .. At character level it becomes eleven tokens, one for each character and one for the space.

Counting n-grams

An n-gram is a run of n consecutive tokens. The order n is the length of the window the model counts. For order n the corpus is cut into every window of n tokens. The first n − 1 tokens of a window form the context, and the last token is its successor. The model keeps the count c(\mathrm{ctx}, w) of how often the token w followed the context \mathrm{ctx}6.

C(\mathrm{ctx}) = \sum_{w} c(\mathrm{ctx}, w)
7

Here c(\mathrm{ctx}, w) is the count of one n-gram, and C(\mathrm{ctx}) is the total count of a context: how many times it was followed by any token. Both are whole numbers of zero or more. The header chips count distinct things rather than occurrences. VOCAB is the number of distinct tokens, CONTEXTS is the number of distinct contexts, and N-GRAMS is the number of distinct (context, successor) pairs8.

The table is stored as a dictionary from each context to its successor counts. Dictionaries keep insertion order, so the candidates appear in the order they first occur in the corpus. The JavaScript port uses a Map, which keeps the same order, so the sampler walks the candidates in the same order in both languages9.

69
function COUNT-NGRAMS(tokens, n):
    k ← n − 1                                   # context length
    for i from 0 to len(tokens) − k − 1:
        ctx ← tokens[i .. i + k − 1]            # the k tokens before the successor
        w ← tokens[i + k]                       # the token that follows them
        count[ctx][w] ← count[ctx][w] + 1
    return count

The simple version is the core loop. The full version adds the two checks on the order and the length of the text, and creates the entry for a context the first time it appears.

Example. For the text a b a b a c at order 2 the context is one token, and the windows are a b, b a, a b, b a and a c. The table is a → {b: 2, c: 1} and b → {a: 2}. So C(a) = 2 + 1 = 3.

The Markov assumption

A Markov assumption is a simplification: the next token is taken to depend only on a fixed number of the tokens before it. Here that number is n − 1, so the model reads the last n − 1 tokens and ignores everything earlier. The order is the size of the model's memory. Order 1 remembers nothing, and order 5 remembers four tokens. At character level the memory is n − 1 characters.

P(w_t \mid w_1, \dots, w_{t-1}) \approx P(w_t \mid w_{t-n+1}, \dots, w_{t-1})
10

Here w_t is the token at position t of the text. The left side conditions on everything before it. The right side conditions only on the last n − 1 tokens. The code uses the right side directly: the lookup key is the tuple of the last n − 1 tokens11.

Sampling with temperature

Sampling draws the next token at random, with each candidate's chance equal to its share of the weights. Temperature T reweights the counts before they are normalised. Each count c becomes c1/T, and each weight is divided by the sum of all the weights1213.

p_T(w \mid \mathrm{ctx}) = \frac{c(\mathrm{ctx}, w)^{1/T}}{\sum_{w'} c(\mathrm{ctx}, w')^{1/T}}
1213

Here T is the temperature: the page allows 0.1 to 2, with 1 as the default. The sum runs over every successor w' of the context. At T = 1 the weights are the raw counts. Below 1 the most common successor gains weight, and above 1 the successors become more even. The chances sum to 1.

Example. After a the counts are b: 2 and c: 1. At T = 1 the weights are 2 and 1, so p(b) = 2/3. At T = 0.5 the weights are 22 = 4 and 12 = 1, so p(b) = 4/5 = 0.8.

Each draw uses one uniform number u in [0, 1) from a seeded generator, mulberry3214. It keeps a 32-bit state, adds a fixed constant on each step, and mixes the result with multiplies and shifts. Both languages keep only the low 32 bits of each product, so the same seed gives the same stream. The chain multiplies u by the total weight, walks the successors in order, and returns the first one whose running sum passes that value. This is the inverse CDF method: each successor owns a slice of the interval whose width is its weight1516.

Generating text

Generation starts from a prompt: a window of n − 1 tokens taken from a seeded position in the corpus, so the first pick already has a context. Each pick reads the last n − 1 tokens of the output, samples a successor, and appends it. The LENGTH setting sets how many picks a run makes17.

A context with no successor can occur only at the very end of the corpus, where the last n − 1 tokens are not followed by anything. The chain then jumps to another seeded window. The jump adds that window's tokens to the output without a pick, and it is counted as a restart. The page marks the jumped tokens in the output, and tags the pick after the jump as JUMP in the transcript1819.

The Python and JavaScript versions produce the same tokens, picks, probabilities, restarts and copy marks. The parity test checks 15 cases, including 2 that reach a restart, token for token and copy mark for copy mark20.

1721
function GENERATE(model, count, T):
    out ← a seeded window of n − 1 corpus tokens    # the prompt
    picks ← empty list
    while length of picks < count:
        ctx ← the last n − 1 tokens of out
        if ctx has no successors:
            append a seeded corpus window to out     # restart: no token is picked
            continue
        weights ← count(ctx, w)^(1/T) for each successor w
        append PICK(weights) to out and to picks
    return out, picks

The full version is the loop that generate() runs17. The restart is the only branch that emits no token, and the restart's window is drawn with the same seeded generator, so a jump is replayed exactly as well. PICK is the inverse CDF step above, and INDEX draws a whole number from the same stream22.

Copy meter and longest run

The copy meter asks how much of the output is repeated word for word from the corpus. A verbatim run is a stretch of consecutive tokens that occurs unchanged in the corpus. A token is copied when it lies in a verbatim run of at least K tokens, where K is 8 words at word level and 20 characters at character level2324. Both values were set by hand, not tuned on any text: 8 words is a short phrase, and 20 characters is about three words of English. The meter shows the share of picks that are copied.

A token is copied exactly when some window of K consecutive output tokens that contains it occurs in the corpus. Every verbatim run of at least K tokens contains such a window, and every such window is itself a run. The code slides a window of K tokens along the output and marks every token inside each window that occurs in the corpus25.

\mathrm{copied} = 100 \cdot \frac{\#\{\, p \in \mathrm{picks} : \exists\, q \in [\,p,\; p + K - 1\,] \text{ with } \mathrm{out}[q - K + 1 \ldots q] \text{ in the corpus} \,\}}{\#\{\mathrm{picks}\}}
2627

Here \mathrm{copied} is the percentage the meter shows, and K is the threshold above. The set \mathrm{picks} holds the generated tokens, and \mathrm{out} is the whole output, including the starting window and any restart windows, so a window can cover them. The window \mathrm{out}[q - K + 1 \ldots q] is the K tokens that end at position q. A window ending at q covers position p exactly when p \le q \le p + K - 1. The count is over picks only, so the prompt and the restart tokens are not counted.

On the page the marks are set while the chain writes. A mark is set once and never cleared, so when a window completes, a pick inside it changes from new to copied, up to K − 1 tokens after it was written. The meter and the transcript change at that moment2829.

The table gives the measured meter for Alice at word level, with the page's defaults: seed 1, temperature 1 and 120 picks. The command below prints the same copied share and longest run on its last line30.

python -m markov generate --corpus alice --order n --words 120 --seed 1, for each order n

OrderCopied picksCopied shareLongest run
10 of 1200.0%2
20 of 1200.0%7
3103 of 12085.8%14
4118 of 12098.3%20
5120 of 120100.0%20

The share rises with order. At order 1 the chain draws each word from corpus frequencies alone, and no eight-word stretch of this run occurs in the book. At order 5 almost every context has exactly one successor (on the training text of Alice, 2,329 contexts for 2,357 distinct n-grams), so the walk follows the book word for word. At character level, with K = 20 and the same seed, the share is 0.0% at orders 1 to 4 and 32.5% (39 of 120 picks) at order 5.

The longest run is the longest verbatim run that ends at a pick, capped at 20 tokens. The suffix that ends at the pick grows one token at a time while it occurs in the corpus, and the search stops at the first miss, because a suffix can occur only if every shorter suffix ending at the same token occurs too3132. The corpus windows of length l are every run of l consecutive corpus tokens, stored as a set, so each membership test is one lookup33.

23242526273132
function COPY-METER(out, picks, K):
    marked ← no token marked
    for each window of K consecutive tokens in out:
        if the window occurs in the corpus:
            mark every token in the window
    copied ← for each pick, whether its token is marked
    return 100 · (number of copied picks) / (number of picks)

The full version is the loop that copy_report() runs. Its first loop marks every window that is in the corpus, and a mark is never cleared, so a token counted as copied stays copied. RUN-ENDING-AT is the suffix search for the longest run, with the same cap as the page.

Add-alpha smoothing

A model that counts only what it saw gives probability 0 to a token that never followed its context, and the logarithm of 0 is undefined. Add-alpha smoothing adds a small pseudo-count \alpha to every count, so every token gets a positive probability. The denominator gains \alpha (V + 1). The V counts the training tokens that are distinct, and the extra 1 is an unknown-token bucket. It reserves mass for a token the training text never had, so the probabilities over the vocabulary and the bucket sum to 13435.

P_\alpha(w \mid \mathrm{ctx}) = \frac{c(\mathrm{ctx}, w) + \alpha}{C(\mathrm{ctx}) + \alpha\,(V + 1)}
3435

Here \alpha is the smoothing constant, 0.01 by default and always above 0, and V is the number of distinct training tokens. The counts c and C are the ones defined above. A context the training text never had has C = 0, so each token gets 1/(V + 1) after it36.

Example. For a b a b a c at order 2, V = 3 and C(a) = 3. With \alpha = 0.01, P_\alpha(c \mid a) = (1 + 0.01) / (3 + 0.01 \times 4) = 1.01 / 3.04 \approx 0.332. A token the text never had after a gets 0.01 / 3.04 \approx 0.003.

The constant is small on purpose. With \alpha = 1 (Laplace smoothing) the training perplexity on Alice is 230.54 at order 1, 232.89 at order 2 and 291.03 at order 3, so the smoothing mass hides the fit. With 0.01 it falls from 223.58 to 7.37 over the same orders.

Perplexity

Perplexity measures how well the model predicts a text. It is the exponential of the average negative log probability per token, where the log is the natural logarithm. A model that gives every token probability 1/8 has perplexity 8, which is the number of equally likely choices it is effectively making. Lower is better. The page does not compute perplexity; the command line does37.

\mathrm{PP} = \exp\!\left(-\frac{1}{N} \sum_{t=t_0}^{L-1} \log P_\alpha(w_t \mid \mathrm{ctx}_t)\right)
38

Here L is the number of tokens, w_t is the token at position t, and \mathrm{ctx}_t is the n − 1 tokens before it. The scored positions start at t_0 = \max(\mathrm{start}, n - 1), the first position with a full context at or after the start, and N = L - t_0 is their number. Tokens before the start are not scored. The train score starts at 0, and the held-out score starts at the first held-out token39.

40
function PERPLEXITY(model, tokens, start, α):
    total ← 0
    count ← 0
    for each position t from max(start, n − 1) to len(tokens) − 1:
        ctx ← the n − 1 tokens before t
        p ← (count of tokens[t] after ctx + α) / (total count after ctx + α · (V + 1))
        total ← total + log(p)
        count ← count + 1
    return exp(−total / count)

The running sum of logs is kept instead of a product of probabilities, because a product of thousands of numbers below 1 shrinks toward zero and cannot be stored in a float. The memo totals stores each context's total count the first time it is needed. The probability in the loop is the add-alpha formula above41.

Train and held-out perplexity

A model can be scored on the text it was counted from, which gives its train perplexity, or on text it never counted, which gives its held-out perplexity. The held-out tail is the last 10% of tokens, rounded, so 266 of Alice's 2,658 tokens are held out and 2,392 train the model42. The command below prints both scores for each order. The contexts and N-grams columns come from the training tokens37.

python -m markov perplexity --corpus alice --order 1..5 (add-alpha smoothing with alpha 0.01):

OrderContextsN-gramsTrain perplexityHeld-out perplexity
11622223.58494.24
26221,78713.18208.72
31,7872,2297.37290.87
42,2292,3297.03348.83
52,3292,3577.06379.69

Train perplexity falls from 223.58 at order 1 to 7.37 at order 3 and then levels off. Held-out perplexity is lowest at order 2, at 208.72, and rises to 290.87 at order 3 and 379.69 at order 5. That rise is overfitting: the table fits the training text more closely as the order grows, and the fit does not carry over to new text. At order 5 the training text has 2,329 contexts and 2,357 distinct n-grams, so almost every context has exactly one successor, and the model puts nearly all its probability on that one token.

From counts to language models

Large language models also predict the next token, one at a time, and they also sample it with a temperature. The difference is the memory. A model of this kind is a neural network, a function with adjustable numbers called weights. It turns a context of thousands of tokens into a distribution over the vocabulary, so it can use a context it has never seen word for word. It stores no table of phrases. A Markov chain is the same loop, with a context limited to n − 1 tokens and probabilities read directly from counts. Training a large model lowers the same negative log probability that perplexity measures.

Parameters and their values

ParameterValueUsed by
CorpusFour public-domain texts, 5 to 14 KB each: Alice in Wonderland chapter 1, Pride and Prejudice chapter 1, Shakespeare's sonnets I to XV, and the Constitution's Preamble and Article I (Project Gutenberg eBooks #11, #1342 and #1041; the National Archives transcript for the Constitution)all
Token levelWords: runs of ASCII letters with inner apostrophes (straight or curly), plus each other non-space character. Characters: every character, with whitespace runs collapsed to one spacetokenizer
Order n1 to 5. The model reads the last n-1 tokens and predicts the nextcounts, sampling, copy meter
Temperature T0.1 to 2 (default 1). Weights are count^(1/T)sampling
Seed0 to 2147483647. Picks the starting window and every drawsampling
Length60, 120 or 240 picksgeneration
RestartAt a context with no successor (only at the corpus end), jump to another seeded windowsampling
Copied run K8 words, or 20 characters: a token is copied when it lies in a verbatim corpus run of at least K tokenscopy meter
Longest run cap20 tokenslongest run
Held-out splitLast 10% of tokens, roundedperplexity
Smoothing alpha0.01 by default; must be above 0 (add-alpha with an unknown-token bucket)perplexity

How these were chosen: The corpora are short so that the page can hold one in memory. The order range stops at 5. At order 5 on Alice the longest run reaches the 20-token cap and the copy meter reaches 100%. The temperature range keeps 0 out of the formula, since c1/0 is undefined. The smoothing alpha is small on purpose: with Laplace smoothing (alpha 1) the training perplexity rises from 232.89 at order 2 to 291.03 at order 3, which hides the fit that the table is meant to show. None of these values was tuned on held-out text.