Keyboard autocorrect, next-word prediction and learning
keyboardautocorrectnlpword-frequencybigramsglide-typingcontractionscorpus
How the Keyboard app's suggestion engine works, and what was learned about the word data behind it. It is a plain-Kotlin, offline design: a 48,000-word frequency list, a bigram table, an edit-distance typo model, and a local personal store.
Scoring
- Candidates come from edits of the typed word (substitutions weighted by key adjacency, insertions, deletions, transpositions, a cheap "missed apostrophe" edit) plus prefix completions.
- Score = ln(frequency) minus typo penalties plus a context bonus from the previous word's bigram row. Penalties had to be steep enough that "helo" becomes "hello" rather than the more frequent "help"; a rare-word guard stops obscure words from winning.
- A tiny fixes table handles classics ("alot", "tommorow").
- Autocorrect applies on space only for confident results; one backspace right after undoes the correction and teaches the typed word.
- Next-word prediction reads the bigram row of the last word (and a sentence-start row).
Word data and what went wrong with it
- Frequencies and bigrams come from Peter Norvig's web n-gram counts (
count_1w.txt,count_2w.txt; norvig.com 301-redirects to www, so usecurl -L), filtered by a system dictionary. - 's contractions were missing because the builder dropped every
'sword as a possessive. Allowlist the real ones (that's, what's, it's, let's...) and floor contraction counts so they survive the 48k cut. - Norvig's corpus split contractions ("do" + "n't"), so
count_1whas "don't" only where it was typed without an apostrophe ("dont" 20M vs "do" 950M), and nearly every contraction had no bigram row. - Fix: count contractions from Tatoeba English sentences (CC BY 2.0 FR). Give each contraction the web count of its stem times its share in the sentences (a global scale is wrong: Tatoeba is conversational, "do" is 10 times more common there, and a global scale put "don't" at rank 8). Borrow follower rows from the expansion ("you're" borrows from "are") when sentence data is thin, with ban lists for question word order and web boilerplate.
- Look-alikes stay separate words: "its"/"it's", "well"/"we'll", "were"/"we're". The bare word is never auto-replaced; the contraction is offered via the apostrophe edit.
- The web sentence-start row is junk ("free", "view", "click").
Glide typing
A SHARK2-style decoder works in key units: sample the gesture, compare its shape and location against each candidate word's ideal path, rank. One backspace removes a whole glided word.
Digits as letter slips
With a number row, "d9nt" usually means "dont": each digit is read as the letter below it (1234567890 to qwertyuiop), and optionally the letters beside that. Use it for suggestions only; autocorrecting on space is opt-in and limited to confident cases, because "v2", "mp3", "co2", "sk8" are typed on purpose.
Accents and other languages
Spanish support maps accent-less spellings to accented words ("manana" to "mañana") via a folded index and offers "cómo" for "como". Spanish data: hermitdave FrequencyWords from OpenSubtitles (CC BY-SA 4.0) and Tatoeba sentences, counts scaled to the English corpus total so thresholds carry over. About 420 KB of APK per language.
Personal learning (all local, no login: canon for the Keyboard)
- Every committed word is counted; boost =
min(3.5, 1.2 * ln(1 + n))added to ln-frequency, but only half of it for edit-distance corrections (otherwise heavy "help" users get "helo" to "help"). - Own word pairs used at least twice add up to +6 context and lead predictions.
- Counts halve every 30 days.
- An unknown word typed 3 times before a space or Enter is promoted to the user's words.
- Emails and phone numbers are learned only from email and phone fields.
- Stored in a local SQLite file excluded from backups; moving phones uses an encrypted export (see Passphrase-encrypted export files for moving app data between phones). Import merges with the max of counts, not the sum, so re-importing does not double.
Learning the user's own fixes and slips (v1.28, 2026-10)
Counting words only teaches what someone types. Two more signals teach how they mistype:
- Fixed by hand. When an unknown typed word is replaced by tapping a non-verbatim suggestion (not a completion that merely extends it, and the target is a known word), remember the pair; next time that fix comes first. Tapping the bold autocorrect cell records nothing new, because autocorrect already makes that fix.
- Erase and retype. The strip never offers multi-edit typos ("probly" for "probably"), so also watch for a finished unknown word followed by a new word that starts at the same text position and is within edit distance max(2, len/3). Note the start offset only for unknown words (one cursor query each), and keep the watch alive across backspaces; clear it only when a new field starts.
- Slip habits. Every kept correction (autocorrect, hand fix, bold tap) counts the single substitution it represents ("o typed for i") or a generic swap/miss/extra. That count lowers the penalty for the same substitution with the same log-shaped curve as word boosts, floored so no edit becomes free. A one-backspace undo un-counts it and drops the pair. In a simulation over the top 3,000 words, six kept o-for-i corrections cut o-for-i misses by about 70%, at a cost of a few new ambiguities in the reverse direction.
- No new storage schema: the pairs live in the existing word-pair table under pseudo-languages (fix:<lang>, slip:<lang>), so export/import, 30-day decay and "Forget" handle them for free. A settings page lists learned corrections with remove buttons.
- Testing trap (again): a test that backspaces right after an autocorrected word undoes it and teaches the typo. Retype tests need a typo autocorrect leaves alone.
Why not a neural network for personal typing
Asked in 2026-10 (post #1812). The answer was no: one person produces too little data to train on, it breaks the zero-dependency rule, it cannot explain its choices, and the logged taps are labeled with the key that was hit, not the key that was meant. The proposed alternative is a per-user touch model: label each tap with its intended letter by aligning the final kept word to the tap sequence, keep a per-key mean and spread per orientation, and use that likelihood in place of fixed neighbor/other substitution costs (later, cautiously, for small hidden hit-box shifts). Not built yet.
Address bars and URL fields
Address bars (TYPE_TEXT_VARIATION_URI) are mostly used for searches, not typing domains. What worked: suggest words even when the field sets NO_SUGGESTIONS; offer .com/.net/.org endings only once the text contains a period or ://; never autocorrect, add emoji, learn, insert a double-space period, or add a space after a tapped ending in those fields.
Rules Justin set for picks and punctuation
- After tapping a suggestion, backspace removes only the added space, never the word.
. , ? ! ; :typed after "word + space" close up to the word; backspace right after puts the space back.- A pick with spaces already after the cursor adds none and moves past them.
See also
- Keyboard hit areas that follow the user's taps (a personal touch model) (touch drift lowers substitution costs, v1.30)
- Writing an Android keyboard (InputMethodService)
- Emoji suggestions from Unicode CLDR keyword data