Before a Transformer calculates a single self-attention weight or hallucinates an answer, raw human text must undergo a brutal mathematical conversion into integer arrays. Step inside the discrete machinery powering modern LLMs.
Computers cannot compute vectors from strings directly. Every neural network operates on tensors of real numbers. The central architectural challenge of NLP is: What discrete unit of language should receive an integer ID?
Every unique word receives an ID. English has >1,000,000 words. Medical and legal jargon adds millions more.
[UNK] (unknown) and loses all semantic context.
Only individual letters and punctuation symbols receive token IDs. The dictionary is small (~256 symbols), but sequence lengths explode.
Frequent words stay intact as single tokens (e.g. "security"), while rare or typo-ridden words decompose gracefully into syllables ("un" + "break" + "able").
In Unicode, accented characters like é can be represented as precomposed bytes (é) or decomposed characters (e + ́). NFKC canonicalization forces consistent representations.
GPT-4 executes an intricate regex expression before subword merging to prevent contractions, punctuation, and whitespaces from bleeding across semantic boundaries.
(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^
\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[
]*|\s*[
]+|\s+(?!\S)|\s+
Because GPUs execute tensor math on uniform rectangular batches, inputs must be padded to a fixed sequence length. Special tokens anchor dialogue boundaries, while Attention Masks tell self-attention heads which positions to ignore.
Web handles like "SolidGoldMagikarp" were assigned single-token IDs during BPE creation from raw Reddit scrapes, but filtered out during pre-training. Their embedding weights were never updated via backprop, causing bizarre hallucinations when prompted.
Adversaries insert zero-width spaces (U+200B) or subword splits to bypass string-matching firewalls, while LLM tokenizers strip the invisible characters and reassemble the attack vector.
# 1. GPT-4 Tokenization via OpenAI's tiktoken
import tiktoken
enc = tiktoken.get_encoding("cl100k_base") # GPT-4 & GPT-3.5-Turbo
prompt = "Transformers tokenize human language into subwords."
token_ids = enc.encode(prompt)
print(f"Token IDs ({len(token_ids)}): {token_ids}")
# 2. Hugging Face AutoTokenizer with Attention Mask & Padding
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")
inputs = tokenizer(["Audit LLM", "Full security telemetry"], padding=True, return_tensors="pt")
print("Tensor Input IDs:", inputs["input_ids"])
print("Attention Mask:", inputs["attention_mask"])