N-gram Perplexity Calculator
Train a bigram or trigram model on your corpus and see every probability behind the perplexity number.
Corpus & model
1 line · 144 charsEstimate: 46 tokens · ~0.0 MB of count tables.
Perplexity
Train a model to begin
Paste a corpus, choose an order and click Train model.
Paste a corpus, choose unigram, bigram or trigram order, and score any test text. The tool builds count tables in your browser, applies Laplace add-k or fixed-weight linear interpolation (Jelinek-Mercer style, not Kneser-Ney), maps unknown words to <unk> and shows a per-token table with counts, probability, log2 contribution and the substituted formula. Sentence sentinels, lowercase, punctuation stripping, HTML stripping, number classes and OOV simulation use the identical pipeline on corpus and test. You can compare two smoothing constants, sweep k and download the breakdown as an RFC-4180 CSV. Nothing is uploaded and there is no neural model or text generation.
- Homework fixture: P = 3/9 · 2/9 · 2/8 · 3/9 = 1/162, so PP = 162^(1/4) ≈ 3.57 — every factor is visible in the breakdown table.
- OOV handling: The unseen word zebra is scored through <unk> and flagged, so the OOV count and its effect on perplexity stay explicit.
- Smoothing comparison: The compare panel shows both perplexities and the delta; add-k mass changes unseen-event probabilities, not just observed bigrams.
Examples
Hand-computable fixture
corpus: the cat sat. the dog sat. · test: the cat sat. · bigram, k=1P = 3/9 · 2/9 · 2/8 · 3/9 = 1/162 · PP ≈ 3.57The four scored tokens are the, cat, sat and </s>; <s> is context only.
Unknown word
test: the zebra sat.zebra flagged OOV, scored via <unk>OOV count and percentage make the impact of unseen vocabulary visible.
Smoothing sweep
k ∈ {0.01, 0.1, 0.5, 1, 2}Five-point perplexity chartAdd-k mainly changes probabilities of unseen events; the chart shows where the model becomes too flat.
About this tool
The N-gram Perplexity Calculator trains a small classical language model on your corpus and scores any test text against it. Choose unigram, bigram or trigram order, apply Laplace add-k or fixed-weight interpolation, and read the exact probability behind every token instead of trusting a single opaque number.
The preprocessing pipeline is deliberately shared: lowercase, punctuation stripping, HTML stripping, number classes, sentence sentinels and OOV simulation run identically on corpus and test. That matters because a capitalized test word silently becoming out-of-vocabulary would invalidate both perplexity and the OOV percentage.
Everything happens in the browser tab. The tool never calls a model API, never generates text, and never uploads proprietary research corpora. Count tables are bounded with a pre-train memory estimate, and the per-token breakdown exports as an RFC-4180 CSV with formula-injection neutralisation.
What this tool does not do
- Classical n-gram statistics only — no embeddings, transformers or generation.
- Sentence splitting uses simple [.!?] boundaries; abbreviations and decimals can create spurious sentence breaks.
- The browser caps count tables with an estimate; very large trigram models are rejected before training.
- Interpolation uses fixed, normalized weights rather than learned or Kneser-Ney discounts.
How to use this tool
Paste a corpus
Add training text on the left, then tick preprocessing options such as lowercase or OOV simulation.
Train
Pick order 1–3 and click Train model. The summary shows tokens, vocabulary size and distinct n-grams.
Score test text
Paste the text to score. Perplexity, bits per token and OOV statistics update with the smoothing settings.
Inspect and export
Expand the token table for counts and formulas, compare a second k, then download the CSV.
Use cases
NLP homework
Check a hand calculation against a model that shows counts and substitutions at each step.
Corpus sanity checks
Compare perplexity across draft corpora with the same test set and smoothing configuration.
Instructor demos
Toggle k and interpolation weights live to show how smoothing reshapes token probabilities.
Estimator conventions
| Estimator | Formula |
|---|---|
| Laplace | P(w|h) = (c(h,w) + k) / (c(h) + k·V) |
| Interpolation | λₙ·Pₙ + λₙ₋₁·Pₙ₋₁ + λ₁·P₁ with normalized weights |
| OOV | Unknown test types are scored as <unk>; exclude policy drops them from M |
| Sentinels | (n−1) `<s>` prefixes and one `</s>` per sentence; `<s>` is never scored |
| Perplexity | PP = 2^(−1/M · Σ log2 P(wᵢ|hᵢ)) |
Interpolation here is Jelinek-Mercer-style linear interpolation of raw estimates, not Kneser-Ney discounting.
Common mistakes
Mistake:Comparing perplexities from different preprocessing settings.
Fix:Keep the options identical on both sides; retrain after any change.
Mistake:Using a trigram on a ten-word corpus.
Fix:The tool still computes a result but warns that the model is sparse and the number is illustrative.
Mistake:Setting k=0 with unseen events.
Fix:Zero probability makes perplexity infinite; the breakdown marks the offending token and suggests raising k.
Mistake:Expecting Kneser-Ney from interpolation.
Fix:This is fixed-weight linear interpolation; proper Kneser-Ney continuation counts are out of scope.
Frequently asked questions
How is perplexity calculated?
Perplexity is 2 raised to the negative average log2 probability of the scored tokens: PP = 2^(−1/M · Σ log2 P(wᵢ|hᵢ)). The breakdown table shows P, log2 P and the running formula for each token. `<s>` prefixes are context only; `</s>` is scored, a convention pinned by the tool so hand calculations agree with the displayed number.
What does add-k smoothing change?
Laplace smoothing replaces a raw count with (c + k) and enlarges the denominator by k·V, where V is the vocabulary including `<unk>`. Larger k gives more probability mass to unseen events and usually raises perplexity; smaller k trusts the corpus counts. The compare panel and five-point k sweep make the effect concrete.
How are out-of-vocabulary words handled?
By default a test word missing from the training vocabulary is scored as `<unk>` and flagged in the breakdown, with an OOV count and percentage. You can also enable OOV simulation during training, which replaces corpus hapax words with `<unk>` so the class has real mass, or exclude OOV tokens from scoring entirely — a convention some textbooks prefer.
Why interpolate with lower orders?
Higher-order contexts are often unseen even when their words are known. Linear interpolation blends the order-n estimate with lower-order and unigram estimates using normalized λ weights (0.6/0.3/0.1 by default). This is Jelinek-Mercer-style interpolation, not Kneser-Ney: there is no discounting or continuation count.
What corpus size can the browser handle?
The tool estimates token count and count-table bytes before training and rejects estimates above roughly 80 MB, which is a practical browser limit for trigram Maps. For larger corpora use a unigram or bigram model, shorten the text, or run an offline script. Nothing is uploaded at any point.
Are my corpus and test text saved?
No. Corpus and test text stay in the tab and are not persisted or sent anywhere. Only your smoothing preferences remain available for the session; downloading the CSV is the only way text leaves the page, and that is an explicit action.
References & standards
Related tools
Agent Tool Flowchart Builder
Design agentic tool-call DAGs with decision branches and bounded loops. Validates reachability, cycle handling, and emits clean Mermaid flowcharts — fully in your browser.
AI Agent Memory & Buffer Simulator
Compare sliding window, summary buffer, and vector memory strategies
AI API Client SDK Generator
Generate typed API client SDK files from OpenAPI specifications or cURL requests
AI Code Explainer
Explain code snippets with grounded cloud AI
AI Code Security Auditor
Scan source code for high-confidence OWASP Top 10 vulnerabilities
AI Code Translator
Translate code into idiomatic implementations in another language