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.
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.
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.
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.
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.
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
function COUNT-NGRAMS(tokens, n):
if n < 1:
raise error "order must be at least 1"
if len(tokens) < n:
raise error "need at least n tokens"
count ← empty map # keys keep first-seen order
k ← n − 1 # context length
for i from 0 to len(tokens) − k − 1: # the last k tokens have no successor
ctx ← tokens[i .. i + k − 1] # a tuple of k tokens (a joined key in JavaScript)
if ctx is not in count:
count[ctx] ← empty map
w ← tokens[i + k]
count[ctx][w] ← count[ctx][w] + 1 # a successor not seen before counts as 0
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.
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.
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 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.
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.
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.
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
function GENERATE(model, rng, count, T):
k ← order − 1 # context length
N ← number of corpus tokens
i ← INDEX(rng, N − k) # seeded start, windows 0 .. N − k − 1
out ← tokens[i .. i + k − 1] # the prompt; empty when k = 0
picks ← empty list
restarts ← 0
while length of picks < count:
ctx ← the last k tokens of out # the empty context when k = 0
succ ← successors[ctx], or nothing if ctx is unseen
if succ is missing or empty:
j ← INDEX(rng, N − k)
append tokens[j .. j + k − 1] to out
restarts ← restarts + 1
continue # the jump emits no pick
weights ← [c^(1/T) for each (w, c) in succ] # in insertion order
idx ← PICK(weights, rng)
append (length of out, succ[idx]) to picks
append succ[idx] to out
return out, picks, restarts
function PICK(weights, rng):
total ← sum of weights
u ← UNIFORM(rng) · total # one draw in [0, total)
cum ← 0
for idx from 0 to len(weights) − 1:
cum ← cum + weights[idx]
if u < cum:
return idx
return len(weights) − 1 # only rounding at the top of the range
function INDEX(rng, k):
return min(k − 1, trunc(UNIFORM(rng) · k)) # a whole number in [0, k)
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.
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.
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
| Order | Copied picks | Copied share | Longest run |
|---|---|---|---|
| 1 | 0 of 120 | 0.0% | 2 |
| 2 | 0 of 120 | 0.0% | 7 |
| 3 | 103 of 120 | 85.8% | 14 |
| 4 | 118 of 120 | 98.3% | 20 |
| 5 | 120 of 120 | 100.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.
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)
constants: K = 8 for words, K = 20 for characters; MAX-RUN = 20
function COPY-CHECK(out, picks, K):
marked ← a list of False, one entry per token of out
for q from K − 1 to len(out) − 1: # the window of K tokens ending at q
if out[q − K + 1 .. q] occurs among the corpus windows of length K:
for t from q − K + 1 to q:
marked[t] ← True # every token in a copied window
copied ← [marked[p] for each pick at position p in picks]
pct ← 0 if copied is empty, else 100 · (number of True in copied) / (length of copied)
longest ← 0
for each pick at position p in picks:
longest ← max(longest, RUN-ENDING-AT(out, p))
return copied, pct, longest
function RUN-ENDING-AT(out, p):
length ← 0
while length < min(MAX-RUN, p + 1) and out[p − length .. p] occurs among the corpus windows of length length + 1:
length ← length + 1
return length
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.
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.
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 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.
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.
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)
function PERPLEXITY(model, tokens, start, α):
k ← n − 1 # context length
V ← number of distinct training tokens
totals ← empty map # C(ctx), summed once per context
log-sum ← 0
count ← 0
for t from max(start, k) to len(tokens) − 1:
ctx ← tokens[t − k .. t − 1]
succ ← model.successors[ctx], or nothing if ctx was never seen
if ctx is not in totals:
totals[ctx] ← sum of the counts in succ # 0 when ctx was never seen
p ← (succ[tokens[t]] + α) / (totals[ctx] + α · (V + 1)) # a missing successor counts as 0
log-sum ← log-sum + log(p)
count ← count + 1
if count = 0:
raise error "no tokens to score"
return exp(−log-sum / 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.
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):
| Order | Contexts | N-grams | Train perplexity | Held-out perplexity |
|---|---|---|---|---|
| 1 | 1 | 622 | 223.58 | 494.24 |
| 2 | 622 | 1,787 | 13.18 | 208.72 |
| 3 | 1,787 | 2,229 | 7.37 | 290.87 |
| 4 | 2,229 | 2,329 | 7.03 | 348.83 |
| 5 | 2,329 | 2,357 | 7.06 | 379.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.
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.
| Parameter | Value | Used by |
|---|---|---|
| Corpus | Four 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 level | Words: 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 space | tokenizer |
| Order n | 1 to 5. The model reads the last n-1 tokens and predicts the next | counts, sampling, copy meter |
| Temperature T | 0.1 to 2 (default 1). Weights are count^(1/T) | sampling |
| Seed | 0 to 2147483647. Picks the starting window and every draw | sampling |
| Length | 60, 120 or 240 picks | generation |
| Restart | At a context with no successor (only at the corpus end), jump to another seeded window | sampling |
| Copied run K | 8 words, or 20 characters: a token is copied when it lies in a verbatim corpus run of at least K tokens | copy meter |
| Longest run cap | 20 tokens | longest run |
| Held-out split | Last 10% of tokens, rounded | perplexity |
| Smoothing alpha | 0.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.