In scenarios where an LLM encounters out-of-vocabulary words during embedding generation, propose strategies for handling such cases.
Modern LLMs largely eliminate true out-of-vocabulary (OOV) tokens by using subword tokenization (BPE, WordPiece, or Unigram) paired with byte-level fallback, which decomposes any arbitrary UTF-8 string into known subwords or raw byte tokens without emitting an unknown token. When legacy word-level or WordPiece models still encounter unrepresented symbols, strategies include character or subword composition (such as FastText n-grams), `[UNK]` fallback vectors, and retrieval-augmented context (RAG) for novel domain terms.
Study Card: Handling Out-of-Vocabulary (OOV) Words in LLM Embeddings
Direct Answer
How an LLM handles previously unseen words depends on its tokenizer and embedding architecture:
- Subword Tokenization (BPE, WordPiece, Unigram): Splits rare or compound words into smaller known subunits (morphemes, stems, or affixes) already present in the vocabulary, so the embedding layer looks up valid vectors for every piece.
- Byte-Level Fallback (BBPE / SentencePiece Byte Fallback): Modern LLMs (GPT-2/3/4, Llama, Mistral, Gemma, Qwen) use byte-level BPE or SentencePiece with
byte_fallback=True. Because the base vocabulary includes all 256 byte values (0x00–0xFF), arbitrary UTF-8 words, typos, code symbols, and emojis are decomposed into byte tokens—meaning modern LLMs never emit<UNK>on valid text. - Character & Subword Composition (FastText / Character CNNs): In static embedding or hybrid architectures, an OOV word’s vector is composed by summing or pooling embeddings of its character n-grams (e.g.,
<bi,bio,iot, …). - Legacy
[UNK]/ Default Fallback & In-Context Grounding: Older word-level models or non-byte WordPiece tokenizers (such as BERT, whose unknown token is[UNK], not<UNK>) map unrepresentable scripts/characters to[UNK]. For semantically novel terms (new acronyms, proprietary names) that do tokenize into subwords but lack learned meaning, Retrieval-Augmented Generation (RAG) supplies definitions in context so contextual attention infers the meaning dynamically.
Key Terms
- Out-of-Vocabulary (OOV) Word: A word missing from a model’s discrete token vocabulary.
- Byte-Level BPE (BBPE): Subword merging directly over UTF-8 bytes, guaranteeing zero
<UNK>tokens for any Unicode input. - WordPiece: Subword tokenization (used by BERT) marking continuation pieces with
##; falls back to[UNK]for characters outside its base alphabet. - Character N-Gram Composition: Constructing representations for rare or unseen words from overlapping character sequences (used in FastText).
- Token Fertility: Average number of subword tokens needed per word; OOV/rare domain words split into many fragments, inflating sequence length and latency.
Example
When BERT’s WordPiece tokenizer encounters "biotechnological", it splits it into known subwords such as ["bio", "##tech", "##nological"] (or similar learned pieces) rather than discarding the word. If BERT sees an unseen emoji "🧬" outside its Unicode table, it outputs [UNK]. By contrast, GPT-2 or Llama’s byte-level BPE encodes "🧬" into four UTF-8 byte tokens (\xf0, \x9f, \xa7, \xac mapped to byte IDs), preserving full lossless reversibility without [UNK].
Code Implementation
import torch
# 1. Pure PyTorch character/subword composition fallback for OOV words
def compose_char_embedding(word: str, char_table: dict[str, torch.Tensor], unk_vec: torch.Tensor) -> torch.Tensor:
vecs = [char_table.get(ch, unk_vec) for ch in word]
return torch.stack(vecs, dim=0).mean(dim=0)
char_table = {c: torch.randn(64) for c in "abcdefghijklmnopqrstuvwxyz"}
unk_vec = torch.zeros(64)
oov_emb = compose_char_embedding("biotechnological", char_table, unk_vec)
print("Composed OOV embedding shape:", oov_emb.shape)
# 2. Comparing BERT WordPiece ([UNK] on unseen emoji) vs. GPT-2 Byte-Level BPE (zero UNK)
# (Requires Hugging Face model cache / network access)
# from transformers import AutoTokenizer
# bert_tok = AutoTokenizer.from_pretrained("bert-base-uncased")
# gpt2_tok = AutoTokenizer.from_pretrained("gpt2")
#
# sample = "Studying biotechnological advances 🧬"
# print("BERT tokens:", bert_tok.tokenize(sample)) # Uses '##' subwords and '[UNK]' for 🧬
# print("GPT-2 tokens:", gpt2_tok.tokenize(sample)) # Lossless byte-level fallback, no UNK
Related Concepts
- Byte Pair Encoding (BPE) & SentencePiece: Frequency-based and unigram subword vocabulary construction algorithms.
- Domain Tokenizer Adaptation: Extending a model’s vocabulary with specialized medical, legal, or code tokens to reduce fragmentation and context bloat.
- FastText: Static word embedding method leveraging bags of character n-grams for robust OOV vector synthesis.
- Retrieval-Augmented Generation (RAG): Providing definitions of unseen proper nouns or new terminology in the prompt when subword decomposition alone lacks semantics.