Build and query an N-gram language model with KenLM
KenLM is a C++ library for estimating word N-gram language models and quickly querying sentence probabilities from saved models. An N-gram estimates the likelihood of the next word from counts of sequences of N consecutive units. KenLM is therefore not a complete conversational text generator; it is a language-model engine that an ASR decoder or statistical machine-translation system can combine with other signals to score candidate sentences. [KenLM repository](https://github.com/kpu/kenlm) · [KenLM paper](https://aclanthology.org/W11-2123/)
Build and query an N-gram language model with KenLM
KenLM is a C++ library for estimating word N-gram language models and quickly querying sentence probabilities from saved models. An N-gram estimates the likelihood of the next word from counts of sequences of N consecutive units. KenLM is therefore not a complete conversational text generator; it is a language-model engine that an ASR decoder or statistical machine-translation system can combine with other signals to score candidate sentences. KenLM repository · KenLM paper
What does an N-gram score mean?
A 3-gram model uses up to the previous two words as context when estimating the next word. For example, it estimates what may follow “the weather is” from word sequences in its training corpus. KenLM’s lmplz estimator uses modified Kneser–Ney smoothing. Smoothing adjusts observed counts and uses statistics from shorter contexts so unseen fragments do not automatically receive probability zero. KenLM estimation guide · N-gram queries in the paper
KenLM does not generate arbitrary sentences. It calculates probabilities for supplied words or partial contexts. An ASR or translation decoder can combine that score with other signals to rank candidates. A higher KenLM score means a sequence better fits the model’s training distribution; it does not prove the sentence is true or semantically correct.
Create an ARPA model from a corpus
Assume KenLM has been built and its lmplz and build_binary executables are available. Building is a developer task with compiler tools and dependencies such as Boost. Build steps vary by system and source version, so follow the repository’s BUILDING instructions. Official build instructions
Prepare a text corpus with one sentence per line. Sentence markers, case, and number and punctuation normalization should match how inference input will be prepared. For example, if training text is lowercased but queries retain original capitalization, vocabulary mismatches may increase. Check that the corpus represents the target domain and does not contain excessive duplicates, which can make the model over-prefer those patterns.
The following example estimates a 3-gram and writes ARPA text. -S sets a memory limit and -T a temporary-file directory. Replace the example paths and memory with values available on your system. Estimator options and pipeline
bin/lmplz -o 3 -S 4G -T /tmp < corpus.txt > corpus.arpaOn success, corpus.arpa contains the model vocabulary, N-gram probabilities, and backoff information. Text format is easy to inspect, but a large model can take substantial space and time to load. Convert it to KenLM’s binary format:
bin/build_binary corpus.arpa corpus.binaryLoad the binary from an application or Python binding to query it. KenLM provides probing hash tables and trie structures: probing favors lookup speed, while trie structures favor lower memory use. Choose based on actual model size and application memory/latency needs. The binary must match the structure expected by KenLM; loading a binary built for another structure can fail. Storage structures and binary usage
Query sentence scores in Python
The repository provides Python binding examples. Installation may need to match the C++ compiler tools and Python ABI. If installation fails, check the active virtual environment and compiler, then consult the official build guide. The code below follows documented usage and has not been executed here. Python module example
import kenlm
model = kenlm.Model("corpus.binary")
score = model.score("the weather is nice .", bos=True, eos=True)
print(score)bos=True and eos=True request scoring with beginning- and end-of-sentence markers. Match token boundaries, punctuation, and boundary-marker conventions between training data and queries. KenLM scores are log base 10. They are usually negative; a larger value such as −4 means the model rates that sequence relatively higher than one with −8. Do not directly compare magnitudes from differently tokenized text or different corpora. Score description in the KenLM repository
Checks when integrating with a decoder
A language model does not produce ASR output on its own. A decoder may combine acoustic-model scores and search among candidate sentences, weighting the language-model score. If the weight is too small, contextual correction has little effect; if too large, fluent phrases can override evidence in the input. Tune the weight on development data from the target domain, then check character or word errors and actual error types on a separate evaluation set. A KenLM score alone cannot measure system performance.
Use this minimum verification sequence:
Record corpus language, domain, sentence cleanup, and tokenization rules.
Confirm `lmplz` finished, produced an ARPA output, and the file is nonempty.
Confirm the binary produced by `build_binary` can be read by Python or the decoder.
Check whether scores for a few selected sentences and short variants reflect the expected context differences. This is an initial sanity check, not a quality evaluation.
Evaluate decoder weights and end-to-end errors on independent validation data; verify that training and evaluation corpora do not overlap.
Summary
KenLM’s strength is estimating and compacting large N-gram models and answering repeated queries efficiently. Good results also depend on corpus normalization, tokenization, decoder score combination, and evaluation—not just the model file.
References
Kenneth Heafield, [KenLM: Faster and Smaller Language Model Queries](https://aclanthology.org/W11-2123/), WMT 2011
Kenneth Heafield, [KenLM estimation guide](https://kheafield.com/code/kenlm/estimation/)
KenLM, [official GitHub repository](https://github.com/kpu/kenlm)