Tokens
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A language model never sees letters, only numbers. A tokenizer cuts text into tokens, pieces such as words or parts of words, and gives each one an ID. Train a real byte pair encoding (BPE) tokenizer on four words, watch neighbouring letters fuse into tokens, split a word it has never seen into known pieces, then follow its IDs into the model's embedding table and back out as text.
Models only see numbers
A language model does arithmetic, so it cannot read letters. Before any text goes in, a tokenizer cuts it into pieces called tokens and gives each piece a number, its ID. The model only ever sees those IDs.
text -> tokenizer -> tokens -> IDs -> model
token a piece of text: a word, part of a word,
a letter or a punctuation mark
ID the number the tokenizer gives each tokenاقرأ الدرس خطوة بخطوة
Models only see numbers
A language model does arithmetic, so it cannot read letters. Before any text goes in, a tokenizer cuts it into pieces called tokens and gives each piece a number, its ID. The model only ever sees those IDs.
text -> tokenizer -> tokens -> IDs -> model token a piece of text: a word, part of a word, a letter or a punctuation mark ID the number the tokenizer gives each tokenStart from single letters
To build a tokenizer, take a training corpus, a sample of text: here four words and how often each appears. Split every word into single characters. These 10 characters are the first vocabulary, IDs 0 to 9.
corpus = {"low": 5, "lower": 2, "newest": 6, "widest": 3} low x5 -> l o w lower x2 -> l o w e r newest x6 -> n e w e s t widest x3 -> w i d e s t vocabulary d e i l n o r s t w IDs 0 .. 9Count neighbouring pairs
Byte pair encoding (BPE) counts every pair of neighbouring symbols, weighted by how often its word appears. "e s" is in newest (6 times) and widest (3): 9 in total. "s t" also scores 9; the first one found wins.
pairs = count_pairs(words) e s 9 s t 9 w e 8 l o 7 o w 7 n e 6 ... best = ('e', 's') (9; first of the tied pairs)Merge the top pair
The winning pair becomes one new symbol, "es", with the next free ID, 10. Every "e s" in the corpus is joined into "es". The merge is written down: the ordered list of merges is what the tokenizer learns.
best = max(pairs, key=pairs.get) words = merge_all(words, best) merges.append(best) low l o w lower l o w e r newest n e w es t widest w i d es t merges = [('e', 's')] "es" -> ID 10Repeat: tokens grow
Count again, merge again. "es t" scores 9, so "est" gets ID 11. Then "l o" (7) becomes "lo", ID 12, and "lo w" (7) becomes "low", ID 13. We stop after 4 merges; GPT-2's tokenizer learned 50,000.
pass best pair count new token ID 1 e s 9 es 10 2 es t 9 est 11 3 l o 7 lo 12 4 lo w 7 low 13 low low lower low e r newest n e w est widest w i d estTokenize a new word
"lowest" was never in the corpus. Split it into letters, then apply the 4 merges in the order they were learned: es, est, lo, low. Two tokens are left: "low" and "est". An unseen word still splits into known pieces.
def encode(word, merges): symbols = tuple(word) for pair in merges: symbols = merge(symbols, pair) start l o w e s t + es l o w es t + est l o w est + lo lo w est + low low estLook up the IDs
Each token is looked up in the vocabulary: "low" is 13 and "est" is 11. So the 6 letters of "lowest" become 2 numbers, [13, 11]. Frequent pieces get their own token; rare words take several.
vocab = sorted(set("".join(corpus))) + ["".join(p) for p in merges] vocab.index("low") -> 13 vocab.index("est") -> 11 "lowest" -> [13, 11] (6 letters, 2 tokens)Limits are counted in tokens
The model reads a sequence of IDs, up to a fixed length called the context window. GPT-2's was 1,024 tokens. Limits and prices are counted in tokens, not words: English text averages about 4 characters per token.
context window [13, 11, ...] GPT-2 1,024 tokens at most rule of thumb 1 token ~ 4 characters of English 100 tokens ~ 75 wordsEach ID picks a vector
Inside the model, each ID selects one row of a learned table, the embedding table. The row is a vector, a list of numbers the transformer layers work on. GPT-2 small: 50,257 rows of 768 numbers each.
ID 13 -> row 13 -> vector of 768 numbers ID 11 -> row 11 -> vector of 768 numbers GPT-2 small 50,257 x 768 table = 50,000 merges + 256 bytes + 1 end token the numbers are learned during trainingDecode IDs back to text
The model answers one token ID at a time. Decoding runs the tokenizer backwards: look up each ID and join the pieces. If it outputs 13 then 11, the text is "low" + "est" = "lowest".
print("".join(vocab[i] for i in ids)) 13 -> "low" 11 -> "est" "low" + "est" -> "lowest"
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Why does a language model need a tokenizer at all?
The model does arithmetic on numbers. The tokenizer cuts text into tokens and maps each token to its ID; inside the model each ID then selects a row of the embedding table.
02A corpus has "hug" 10 times and "pug" 5 times. Which pair does the first BPE merge choose?
"u g" appears in both words, so its count is 10 + 5 = 15, the highest. BPE counts every neighbouring pair, weighted by how often its word appears, and merges the most frequent one.
03With the four merges es, est, lo, low (in that order), how is "slow" tokenized?
"s l o w": no "e s" pair, so the first two merges do nothing; "l o" becomes "lo", then "lo w" becomes "low". What is left is "s" + "low".
04GPT-2's context window is 1,024 tokens. What does that limit count?
The context window is a limit on the number of tokens in the sequence the model reads. In English a token averages about 4 characters, so 1,024 tokens is roughly 770 words.
05What does the embedding table do with a token ID?
The embedding table has one row per token in the vocabulary (50,257 in GPT-2). An ID picks its row, a learned vector (768 numbers in GPT-2 small), which the transformer layers then work on.
المسرد
- Token
- A piece of text the model reads as one unit: a whole word, part of a word, a single character or a punctuation mark.
- Tokenizer
- The program that cuts text into tokens and maps each token to its ID, and that joins the pieces back into text when decoding.
- Token ID
- The whole number that stands for a token in the vocabulary. The model only ever sees IDs.
- Vocabulary
- Every token the tokenizer knows, each with its ID. GPT-2's has 50,257.
- Byte pair encoding (BPE)
- A way to build a vocabulary: start from single characters (or bytes), then repeatedly merge the most frequent neighbouring pair into a new token.
- Merge
- One learned rule of BPE, such as e + s → es. The ordered list of merges is what the tokenizer learns.
- Context window
- The most tokens a model can read at once. GPT-2's was 1,024.
- Embedding table
- A learned table with one row (a vector of numbers) per token ID. It is how IDs become something the transformer can compute with.
الملاحظات والمصادر
- Real tokenizers such as GPT-2's start from the 256 possible bytes, not letters, so any text, emoji included, can be tokenized. A space is part of the token that follows it.
- GPT-2 applies merges by rank (the earliest-learned pair present goes first), which gives the same tokens as applying them in order here.
- The Python program in the lesson is real: run it and it prints the four merges, then [13, 11], then lowest.
- The model's answer in the last step is an illustration of decoding, not the output of a real model.
- Sennrich, Haddow & Birch, Neural Machine Translation of Rare Words with Subword Units (ACL 2016): BPE for subword tokens
- Radford et al., Language Models are Unsupervised Multitask Learners (OpenAI, 2019): GPT-2, byte-level BPE, 50,257 tokens, 1,024 context
- OpenAI GPT-2 source code: the released BPE encoder (encoder.py)
- Vaswani et al., Attention Is All You Need (2017), section 3.4: embeddings
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, chapter 2: tokenization and BPE
- Hugging Face LLM Course, chapter 6.5: Byte-Pair Encoding tokenization
- OpenAI Help Center, What are tokens and how to count them?
- Python Library Reference: collections.Counter
اختبار يتاح بعد الخطوة الأخيرة.