Character-Level Language Models
“Before machines could write essays, they had to learn to spell.”
TL;DR
Character-level language models predict text one letter at a time, offering an open vocabulary and zero out-of-vocabulary issues at the cost of 5-6x longer sequences. RNNs with LSTM cells were the classic approach, using truncated backpropagation to handle long sequences. BPE subword tokenization ultimately won as the Goldilocks approach between character and word-level modeling, balancing manageable sequence lengths with robust vocabulary coverage. Character models remain relevant in speech recognition for spelling correction in noisy transcripts, in specialized domains like biological sequences, and in today’s byte-level models. For how modern tokenization feeds into production systems, see LLM Serving.

1. Problem Statement
Modern LLMs (GPT, Llama, Claude) operate on tokens (sub-words). But to understand why, we must study the alternatives. Character-Level Modeling is the task of predicting the next character in a sequence.
- Input:
['h', 'e', 'l', 'l'] - Target:
'o'
Why build a Char-LM?
- Open Vocabulary: No “Unknown Token”
<UNK>issues. It can generate any word. - Robustness: Handles typos (
"helo") and biological sequences ("ACTG") natively. - Simplicity: Vocab size is about 100 (printable ASCII), or 256 for byte-level models that cover all of Unicode, instead of 50,000+ (GPT-2’s byte-level BPE has 50,257).
2. Understanding the Requirements
2.1 The Context Problem
Prediction depends on long-range dependencies.
- “The cat sat on the m…” -> a -> t. (Local context).
- “I grew up in France… I speak fluent F…” -> r -> e… (Global context).
A Char-LM must remember history that is 5-6x longer than a Word-LM (an average English word is about 5 characters, plus a space). If a sentence is 20 words, the Char-LM sees 100-120 steps.
2.2 Sparse Inputs, Dense Embeddings
- One-Hot Encoding: Each character is a sparse vector.
ais always[1, 0, ...]. - Embedding: We still learn a dense vector for ‘a’, capturing nuances like “vowels cluster together”.
3. High-Level Architecture
We compare RNN (Recurrent) vs Transformer (Attention).
RNN Style (The Classic):
[h] -> [e] -> [l] -> [l]
| | | |
v v v v
(S0)-> (S1)-> (S2)-> (S3) -> Predict 'o'
State S3 must encode “We are in the word ‘hello’”.
Transformer Style (Modern):
Input: [h, e, l, l]
Attention: l attends to h, e, l.
Output: Prob(o)
4. Component Deep-Dives
4.1 Tokenization Trade-offs
| Strategy | Vocab Size | Sequence Length (for 1000 words) | OOV Risk |
|---|---|---|---|
| Character | ~100 | ~5,000-6,000 chars | None |
| Word | 100K-1M | 1000 words | High (Rare names) |
| Subword (BPE) | ~50k | ~1300 tokens | Low |
Why BPE won: It balances the trade-off. It keeps sequence length manageable (for Transformer O(N²) attention) while handling rare words by falling back to smaller pieces.
4.2 The Output-Layer Cost
Predicting 1 out of 100 chars is cheap. Predicting 1 out of 50,000 tokens is expensive (large Matrix Mul at the end). Char-LMs are fast at the final layer, but slow overall because they need many more steps for the same text.
4.3 What Subword Tokenization Costs You
BPE won, but it has side effects that character models never had, and they show up in production:
- Character-level tasks get harder: when “strawberry” is one or two tokens, the model never sees its letters directly, so counting letters, spelling backwards or fixing a single typo is surprisingly error-prone.
- Numbers depend on chunking: if “12345” splits into arbitrary multi-digit pieces, arithmetic gets harder to learn. The original LLaMA tokenizer split all numbers into individual digits for this reason.
- Some languages pay a token tax: Petrov et al. (2023) found that the same text can need many times more tokens in some languages than in English, up to roughly 15x in their comparison. That means higher cost, higher latency and a shorter effective context window for those users.
- Noisy text fragments: a typo can turn one common token into several rare ones, which is why ASR transcripts and user-generated text are harder for subword models than clean prose.
4.4 Measuring Quality: Bits per Character
Character models are scored in bits per character (BPC): the average cross-entropy per character, in base 2. Training code usually reports loss in nats, so BPC = loss / ln 2.
- To compare with a word-level model, convert to word perplexity: PPL_word = 2^(BPC × characters per word, including the space).
- For scale: on the enwik8 benchmark (the first 100MB of English Wikipedia), Transformer-XL reported 0.99 BPC.
5. Data Flow: Training Pipeline
- Raw Text: “Hello world”
- Vectorizer:
[H, e, l, l, o, _, w, o, r, l, d]->[8, 5, 12, 12, 15, 0, ...] - Windowing: Create pairs
(Input, Target).[8, 5, 12]->12(“Hel” -> “l”)[5, 12, 12]->15(“ell” -> “o”)
- Loss Calculation: Cross Entropy Loss on the prediction.
6. Implementation: RNN Char-LM
import math
import torch
import torch.nn as nn
class CharRNN(nn.Module):
def __init__(self, vocab_size, hidden_size, n_layers=1):
super().__init__()
self.embedding = nn.Embedding(vocab_size, hidden_size)
self.rnn = nn.LSTM(hidden_size, hidden_size, n_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, vocab_size)
def forward(self, x, hidden=None):
# x: [Batch, Seq_Len] (e.g., indices of chars)
embeds = self.embedding(x)
# rnn_out: [Batch, Seq_Len, Hidden]
rnn_out, hidden = self.rnn(embeds, hidden)
# Predict next char for EVERY step in sequence
logits = self.fc(rnn_out)
return logits, hidden
@torch.no_grad()
def generate(self, start_char, char_to_ix, ix_to_char, max_len=100):
# Inference Loop
curr_char = torch.tensor([[char_to_ix[start_char]]])
hidden = None
out = start_char
for _ in range(max_len):
logits, hidden = self.forward(curr_char, hidden)
probs = nn.functional.softmax(logits[0, -1], dim=0)
next_ix = torch.multinomial(probs, 1).item()
out += ix_to_char[next_ix]
curr_char = torch.tensor([[next_ix]])
return out
Training with truncated backpropagation (Section 7.1) on a toy corpus:
text = "hello world, hello there. " * 50
chars = sorted(set(text))
char_to_ix = {c: i for i, c in enumerate(chars)}
ix_to_char = {i: c for c, i in char_to_ix.items()}
data = torch.tensor([char_to_ix[c] for c in text])
model = CharRNN(len(chars), hidden_size=64)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
seq_len, hidden = 32, None
for step in range(200):
start = (step * seq_len) % (len(data) - seq_len - 1)
if start < seq_len:
hidden = None # wrapped around to the start of the text: reset the state
x = data[start:start + seq_len].unsqueeze(0)
y = data[start + 1:start + seq_len + 1].unsqueeze(0)
if hidden is not None:
hidden = tuple(h.detach() for h in hidden) # TBPTT: keep the state, cut the gradient
logits, hidden = model(x, hidden)
loss = nn.functional.cross_entropy(logits.reshape(-1, len(chars)), y.reshape(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
# The toy corpus repeats, so the loss goes near zero; real text will not
print(f"loss {loss.item():.3f} nats/char = {loss.item() / math.log(2):.2f} bits/char")
print(model.generate("h", char_to_ix, ix_to_char, max_len=40))
7. Scaling Strategies
7.1 Truncated Backpropagation through Time (TBPTT)
You cannot backpropagate through a book with 1 million characters: memory grows with every step, and gradients vanish or explode.
We process chunks of 100 characters.
Crucial: We pass the hidden state from Chunk 1 to Chunk 2, but we detach the gradient history. The model remembers the context, but doesn’t try to learn across the boundary.
7.2 Byte-Level Models Today
Pure character models fell out of favor for general-purpose LLMs, but the idea came back at the byte level:
- Byte-level BPE (GPT-2 onward) starts its vocabulary from the 256 byte values, so no input is ever out of vocabulary, then merges frequent byte sequences into tokens.
- ByT5 (Xue et al., 2021) runs a T5-style model directly on UTF-8 bytes and holds up much better under spelling noise than its subword counterpart.
- MEGABYTE (Yu et al., 2023) groups bytes into fixed-size patches: a large global model works on patches and a small local model predicts the bytes inside each one, which shortens the sequence the expensive model sees.
- Byte Latent Transformer (Pagnoni et al., 2024) makes the patches dynamic, spending more compute where the next byte is hard to predict, and reports matching a tokenizer-based Llama 3 training recipe at the 8B-parameter scale.
The trade-off has not changed: bytes buy robustness and an open vocabulary, and the architecture has to win back the sequence-length cost.
8. Failure Modes
- Hallucinated Words: “The quxijumped over…”
- Since it spells letter-by-letter, it can invent non-existent words that “sound” pronounceable.
- Incoherent Structure: It closes parentheses
)that were never opened(.- Small models lose track of structure (open brackets, quotes) once it spans more steps than their state can carry. Larger models and attention over longer contexts help.
9. Real-World Case Study: Andrej Karpathy’s char-rnn
Karpathy’s 2015 blog post “The Unreasonable Effectiveness of Recurrent Neural Networks” trained a Char-RNN on:
- Shakespeare: Resulted in fake plays.
- Linux Kernel Code: Resulted in C code that looked plausible (comments, indentation, mostly matched brackets) even though it did not compile. This showed that neural nets learn Syntactic Structure just from statistical co-occurrence. His later minGPT and nanoGPT projects use a character-level Shakespeare dataset as their smallest example for the same reason: it is the simplest possible tokenizer.
10. Connections to ML Systems
This connects to Custom Language Modeling in Speech (see custom language modeling for ASR).
- ASR systems can use Char-LMs to correct spelling in noisy transcripts.
- If ASR hears “Helo”, the Char-LM says “l followed by o is unlikely after He, it should be ‘ll’”.
11. Cost Analysis
Training: Cheap at small scale. A small Char-RNN on a few MB of text trains on a laptop in minutes to hours. Inference: Expensive.
- To generate a 1000-word essay (5,000-6,000 chars), you run the model 5,000-6,000 times (serial).
- A BPE Token-LM runs about 1,300 times.
- That roughly 4x latency penalty is why Char-LMs are not used for Chatbots.
12. Key Takeaways
- Granularity Matters: Breaking text down to atoms (chars) simplifies vocabulary but complicates structure learning.
- Embeddings: Even characters need embeddings. ‘A’ and ‘a’ should be close vectors.
- Subword Dominance: BPE won because it sits in the “Goldilocks” zone: short sequences, manageable vocab.
- Bytes Are Back: Byte-level and patch-based models keep the robustness of character models while attacking their sequence-length cost.
FAQ
What are the advantages of character-level language models?
Character-level models have an open vocabulary with no unknown token issues, handle typos and novel words natively, and use a tiny vocabulary of roughly 100 characters. This makes them robust for specialized domains like biological sequences (ACTG) and useful for spell correction in ASR systems where noisy transcripts need character-level reasoning.
Why did subword tokenization like BPE replace character-level models?
BPE balances the trade-off between sequence length and vocabulary size. Character models require 5-6x longer sequences (5,000-6,000 characters for a 1000-word essay), which is prohibitively expensive for Transformer attention at O(N-squared). BPE keeps sequences at around 1300 tokens per 1000 words with a manageable 50K vocabulary and low out-of-vocabulary risk.
How does truncated backpropagation through time work for character models?
Instead of backpropagating through millions of characters, the model processes chunks of around 100 characters. The hidden state is passed from chunk to chunk so the model remembers context, but gradient history is detached at chunk boundaries to prevent vanishing or exploding gradients. The model remembers but does not try to learn across boundaries.
Why are character-level models not used for chatbots?
Generating a 1000-word essay requires running the model 5,000-6,000 times serially for character-level output versus roughly 1,300 times for BPE token-level output. That roughly 4x latency penalty makes character models impractical for interactive applications where users expect fast responses.