Skip to content
Projects

Text Prediction System – The First Rung Under Every LLM

Associated link:

github.com/Daniil-Hirchyts/ngram-text-prediction (opens in new tab)

Every large language model, however capable, answers one question over and over: given the text so far, what comes next? This project answers that same question with nothing but counting, in Scala 3 and without a single machine learning library. I built it during my Bachelor of Engineering (BEng) in Computer Science and Technology at the Montpellier University Institute of Technology.

The purpose was to build the oldest working version of a language model by hand and see where it breaks. Each point of failure is a problem the field later spent decades solving. Anyone putting language models into production is asked why a model invents facts, why its context has a limit and what temperature does. Those answers come more easily after building the first rung of the ladder.

One Question, Three Verbs

Claude Shannon asked this question in 1948, when he generated rough English by choosing each word according to what tends to follow the previous one. An n-gram model is that idea, made operational. If “the cat” was followed twice by “sleeps” and once by “eats”, the next word is “sleeps” with probability 2/3 and “eats” with 1/3.

That small table is already a complete language model, and it has the same three operations as a modern one:

  • Train: read a corpus and record what follows what. Here, that means counting.
  • Predict: turn the current context into a probability for every candidate word. Here, a lookup in a trie.
  • Generate: draw a word from that distribution, append it and repeat.

Trained on public domain books, it writes sentences like this one: “the queen said get to your places shouted the queen can you play croquet”. Each stretch of a few words is plausible, because each was seen. The whole has no meaning and no intent. The system produces likely continuations, with no notion of truth. It is the simplest possible demonstration of why a fluent answer and a correct answer are different things.

Why Longer Context Stops Working

Better prediction needs more context: “of” tells you little, while “the queen of” tells you a lot. But every extra word multiplies the number of contexts the model would need to have seen. These are the figures for the English corpus, about 108,000 words of text with a vocabulary of about 9,300:

ContextPossible contextsActually seenTop-3 accuracy, exact match
1 word9,3009,30019.4%
2 words87 million57,0009.7%
3 words813 billion94,0002.8%

Of the 3-word contexts that did appear, 92% appeared exactly once. On held-out text, an exact 3-word lookup could answer only about 15% of the time, so the longest context is the most specific and also the least useful. The project’s original documentation described trigrams as the best balance, and the measurement overturned it. Language is too combinatorial for any corpus to cover by enumeration, and this is the root problem the rest of the field works on.

The Best That Counting Can Do

The standard engineering response is to fall back. If the last three words are unknown, try the last two, then one. I implemented stupid backoff (Brants et al., 2007): a word keeps the score of the longest context in which it appears, multiplied by 0.4 for each word dropped, and the scores are rescaled into a real distribution. It needs only the counts already stored.

localhost:8080

Looking up “would like to”Seen 10 times

Top suggestion: visit, 38%, from 3-word context.

Type a sentence: Tab or a row accepts the suggestion. Drop the context to 1 word, or type a phrase the model never saw, and each row shows the shorter context that answered and the 0.4 penalty it paid.

Measured on a 90/10 split, the same way a model is evaluated today:

ContextEnglish, exactEnglish, with fallbackFrench, exactFrench, with fallback
1 word19.4%19.4%16.0%16.0%
2 words9.7%19.9%8.7%16.9%
3 words2.8%20.1%2.1%16.9%

Coverage rises from about 15% of positions to 94%. Accuracy barely moves beyond the single-word model. The fallback rescues the system from silence, but it cannot give it understanding. To a count table, “the cat sleeps” says nothing about “the dog sleeps”, because those are unrelated keys. A larger corpus would raise the ceiling a little, and the structure of the approach keeps the ceiling in place.

What Each Limit Forced Next

Reading the history of language modeling from the inside of this code, each major step lines up with a limit I could reproduce on my own machine:

Limit in this projectWhat changedWhere it came fromWhere you meet it today
“Cat” and “dog” are unrelated keysWords become vectors, so similar words share what is learnedBengio et al., 2003; word2vec, 2013Embeddings and semantic search
Context stops after 3 wordsNetworks that carry state, then attention over the whole passageSequence models, 2014; Transformer, 2017The context window
The table grows with every new sequence and cannot answer for unseen onesA fixed set of learned parameters that generalizeNeural language modelsModel size and training cost
Whole words only, so an unknown word is a dead endSubword tokens that compose into any wordSubword units, 2016Tokenizers and per-token pricing
Always taking the top word loops foreverSampling from the distributionNucleus sampling, 2019Temperature and top-p
108,000 words of evidenceOrders of magnitude more data and computeScaling laws, 2020The cost of frontier training
Likely text, with no notion of being helpful or trueTraining on human preferenceInstruction tuning, 2022Assistants, and residual hallucination

The final row matters most once a model is in production. Those later steps improved how well a model estimates what comes next and shaped which continuations it prefers. The core task is still prediction, which is why grounding, retrieval and evaluation remain the deployer’s job.

Decisions That Carry Over

Three design choices in this small system apply directly to larger ones.

Sampling beats always picking the top word. Generation initially chose the most likely word and fell into repeating loops. Drawing randomly in proportion to the probabilities fixed it, which is the same reasoning behind temperature.

The tokenizer is part of the model. The first version kept only the letters a to z, which altered about 20% of French words (“était” became “tait”). Training and prediction now share one Unicode-aware tokenizer. Mismatched or careless tokenization remains a common source of quiet quality loss.

Store what you can combine. The original saved probabilities, which cannot be merged, so adding text to a model was impossible and 692 KB of text produced a 31 MB file. Models now store raw counts in SQLite and new text is an upsert inside a transaction. The two built-in models take about 26 MB together.

The Cherry on Top: A Working Product

The model is wrapped in an application you can use: inline autocomplete that also works mid-word, through a prefix search over a second trie, plus ranked suggestions, text generation and custom models trained on uploaded files, with a suggestion taking about 4 ms locally.

Recorded on the original version, so some labels have since changed.

An audit of the running application found the worst defects outside the algorithm: every restart deleted the trained models, a crafted model name allowed path traversal, the test suite did not compile, and unbounded generation could take 43 seconds for 32,000 words. All are fixed and covered by 84 tests, and Akka was replaced with Apache Pekko because of its licence change. The stack is Scala 3, Pekko HTTP, SQLite and ScalaTest.

When Counting Is Still the Right Answer

An n-gram model will not replace an LLM, and on general language it reaches 20% where modern models are far beyond it. It still has a place. For narrow vocabularies, such as form fields, part codes or templated messages, a count table answers in milliseconds, runs anywhere, costs nothing per call and can be audited line by line. Before committing to an LLM, find out what the simplest baseline achieves, because that number is what the larger system has to beat to justify its cost.

More