Train a byte-pair encoder on a small text file, then reproduce GPT-2 token IDs. Each stage includes a Russian and Kazakh study note, a question for SynQ and the original English specification.
Set up your project
Choose a starter for your language. C++ · Go · Java · Python · Rust · TypeScript.
Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.
- Starter templates
- Reference solutions
- Language environments
- Download the source snapshot (ZIP)
- Upstream test runner
Русский. Выберите стартовый проект выше. В каждом из восьми этапов есть задание, контрольный пример и вопрос, который можно задать SynQ AI Tutor.
Қазақша. Жоғарыдан бастапқы жобаны таңдаңыз. Сегіз кезеңнің әрқайсысында тапсырма, өзін-өзі тексеру мысалы және SynQ AI Tutor-ға қоятын сұрақ берілген.
Contents
Core project
1. UTF-8 bytes
Русский · Байты UTF-8
Реализуйте команду bytes для файла с текстом. Выведите десятичное значение каждого байта в виде массива JSON. Пробелы и переводы строк входят во входные данные. Для проверки сохраните одну букву Қ без перевода строки: результат должен быть [210, 154].
Вопрос для SynQ. Почему у одной буквы два значения? Как отличить число байтов от числа символов?
Қазақша · UTF-8 байттары
Мәтіндік файл үшін bytes командасын жазыңыз. Әр байттың ондық мәнін JSON массивіне шығарыңыз. Бос орын мен жол соңы да мәтінге кіреді. Файлға жол соңын қоспай жалғыз Қ әрпін жазыңыз. Нәтиже [210, 154] болуы тиіс.
SynQ-ға сұрақ. Неліктен бір әріп екі санмен беріледі? Байт саны мен таңба санын қалай ажыратасыз?
English specification
In this stage, you’ll implement the first step of a tokenizer, a bytes command that converts text into UTF-8 bytes.
The bytes command
A language model can’t read text. It only reads numbers, called token IDs. A tokenizer turns the text into token IDs for the model.
The first step of a tokenizer is to convert raw text into bytes.
The bytes command reads a file and prints its UTF-8 bytes as a JSON array, one number per byte.
$ ./your_program.sh bytes text.txt
For example, if the file contains hi 👋, the output is:
[104, 105, 32, 240, 159, 145, 139]
h is 104, i is 105, and the space is 32. The last four numbers, 240, 159, 145, 139, are the wave emoji.
Tests
The tester will write hi 👋 to text.txt and execute your program like this:
$ ./your_program.sh bytes text.txt
Your program must print the bytes as a JSON array:
[104, 105, 32, 240, 159, 145, 139]
The tester will also run your program on a few other files, including an empty file, a file with only an emoji, and a file with several lines.
Notes
- Spaces, newlines, and tabs are bytes too. Keep every one of them: a space is
32, a newline is10, and a tab is9. An empty file has no bytes, so its output is[]. - Every byte is a number from 0 to 255. A larger number means you’re printing characters, not bytes.
- The tester reads your output as JSON, so
[104,105]and[104, 105]both pass. Print only the JSON array to stdout, and send debug output to stderr, like the starter code’s log line.
2. Most frequent pair
Русский · Самая частая пара
Команда top-pair читает массив целых ID. Подсчитайте все соседние пары, включая перекрывающиеся. При равной частоте выберите пару, впервые встретившуюся левее остальных. Для [8, 9, 1, 2] ответ [8, 9].
Вопрос для SynQ. Сколько раз встречается пара [7, 7] в [7, 7, 7] и почему?
Қазақша · Ең жиі кездесетін жұп
top-pair командасы бүтін ID сандарының массивін оқиды. Қабаттасатын жұптарды қоса, көршілес элементтердің барлық жұбын санаңыз. Жиілігі тең болса, сол жақтан оқығанда бірінші кездескен жұпты таңдаңыз. [8, 9, 1, 2] үшін жауап [8, 9].
SynQ-ға сұрақ. [7, 7, 7] тізімінде [7, 7] жұбы неше рет кездеседі? Неліктен?
English specification
In this stage, you’ll implement the top-pair command to find the pair of tokens a tokenizer should combine next.
Why combine pairs?
GPT-2 sees Hello world as 2 tokens: Hello, and world with the space before it. Your bytes command sees it as 11 bytes. A tokenizer gets from 11 down to 2 by repeatedly combining the most common pair of tokens into a new token.
This stage finds the most common pair. Later stages combine it and repeat.
The top-pair command
The top-pair command counts every pair of neighboring ids and prints the one that appears most often. Overlapping pairs count, so aaa has the pair (97, 97) twice. When two pairs tie, the pair that appears first, reading left to right, wins.
Your program reads ids from ids.json and parses it as JSON. The ids are already integers, so there is no UTF-8 step for this stage.
For example, in [1, 2, 3, 1, 2], the pairs are (1, 2), (2, 3), (3, 1), and (1, 2) again. The pair (1, 2) appears twice, so the most frequent pair is:
[1, 2]
In [8, 9, 1, 2], the pairs (8, 9), (9, 1), and (1, 2) each appear once. They all tie, so the first pair from the left wins:
[8, 9]
In [1, 2, 3, 4, 3, 4, 1, 2], (1, 2) and (3, 4) both appear twice. (1, 2) appears first, so it wins:
[1, 2]
Tests
The tester will write [1, 2, 3, 1, 2] to ids.json and execute your program like this:
$ ./your_program.sh top-pair ids.json
Your program must print the pair as a JSON array:
[1, 2]
The tester will also run your program on a few other lists, including ties, overlapping pairs, and the ids of aaabdaaabac.
Notes
- Print only the winning pair. Later stages give that pair its own new id.
- Don’t assume ids fit in a byte. Later stages create ids 256 and up and count their pairs the same way.
3. Merge a pair
Русский · Слияние одной пары
Команда merge читает пару из --pair и проходит массив слева направо. На этом этапе заменяйте совпадение числом 256 и переходите сразу за оба обработанных элемента. Для [7, 7, 7] и пары 7,7 получится [256, 7].
Вопрос для SynQ. Почему число замен иногда меньше числа пар, подсчитанных на прошлом этапе?
Қазақша · Бір жұпты біріктіру
merge командасы --pair арқылы берілген жұпты оқып, массивті солдан оңға қарай қарайды. Осы кезеңде сәйкес жұпты 256 санымен ауыстырып, келесі өңделмеген элементке көшіңіз. [7, 7, 7] массиві мен 7,7 жұбы үшін нәтиже [256, 7].
SynQ-ға сұрақ. Неліктен ауыстыру саны алдыңғы кезеңде саналған жұптар санынан аз болуы мүмкін?
English specification
In this stage, you’ll implement the merge command to combine a pair of tokens into a new token.
Your progress
22 → 18 tokens for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
merge ██████████████████ 18 tokens ← this stage
GPT-2 ██████ 6 tokens ← the goal
Why merge?
Merging is how GPT-2 grew its vocabulary. In GPT-2’s training text, the most common pair of bytes was a space (byte 32) followed by t (byte 116), the start of words like the, to, and that. GPT-2 merged that pair first and gave it the new id 256.
After that merge, every the, to, and that with a space before it takes one token fewer. A word at the very start of a text has no space before it, so its t stays a separate token. In to the top of the tree, 4 of the 5 words that start with t follow a space, so the sentence drops from 22 tokens to 18.
32 and 116 are byte values. GPT-2’s vocabulary numbers single bytes in its own order, so its ids for a space and t are 220 and 83. Later stages convert between the two.
The merge command
A merge gives a pair of ids its own new id. Byte ids go from 0 to 255, so the first free id is 256. This stage makes one merge, so its new id is always 256. Later stages combine this with top-pair to train a tokenizer, and give each new merge the next id: 257, 258, and so on.
Like top-pair, the merge command parses ids.json as a JSON array of integers. It reads the ids from left to right. Each time it finds the pair given by --pair, it replaces those two ids with the new id.
For example, in [1, 2, 3, 1, 2], the pair (1, 2) appears twice. Replacing it with 256 gives:
[256, 3, 256]
Matches can’t overlap. In [97, 97, 97], reading from the left, the first two ids match (97, 97) and become 256. The third 97 has nothing left to pair with, so it stays:
[256, 97]
This is different from counting. top-pair counts (97, 97) twice in this list, but a merge can’t use the middle 97 twice.
Tests
The tester will write [1, 2, 3, 1, 2] to ids.json and execute your program like this:
$ ./your_program.sh merge ids.json --pair 1,2
Your program must print the merged ids as a JSON array:
[256, 3, 256]
The tester will also run your program on a few other lists, including overlapping matches, a pair that never appears, the ids of aaabdaaabac, and the bytes of the sentence from “Your progress”.
Notes
--pairis two integers separated by a comma, with no spaces.- Order matters.
--pair 1,2matches1followed by2, never2followed by1.
4. Learn merges
Русский · Обучение BPE
Команда train читает корпус как байты UTF-8. На каждом шаге найдите самую частую пару в текущем списке, замените все её непересекающиеся вхождения и сохраните пару. Новые ID идут от 256 по порядку. Вывод — массив пар в порядке обучения. Для текста abab без перевода строки и двух слияний ожидается [[97, 98], [256, 256]].
Вопрос для SynQ. Покажите список ID после первого слияния. Как он определяет второе?
Қазақша · BPE ережелерін үйрету
train командасы мәтін корпусын UTF-8 байттары ретінде оқиды. Әр қадамда ағымдағы тізімдегі ең жиі жұпты тауып, оның қабаттаспайтын кездесулерін ауыстырыңыз да, жұпты сақтаңыз. Жаңа ID сандары 256-дан басталады. Жұптарды үйретілген ретімен шығарыңыз. Жол соңы жоқ abab мәтіні және екі біріктіру үшін нәтиже [[97, 98], [256, 256]].
SynQ-ға сұрақ. Бірінші біріктіруден кейінгі ID тізімін көрсетіңіз. Ол екінші жұпты қалай анықтайды?
English specification
In this stage, you’ll implement the train command to learn which pairs to merge from a text file.
Your progress
22 → 11 tokens for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
train ███████████ 11 tokens ← this stage
GPT-2 ██████ 6 tokens ← the goal
The 11 comes from five merges learned from the sentence itself, with --num-merges 5. After the fifth merge, the sentence is 11 tokens long.
How GPT-2 learned its merges
GPT-2’s tokenizer comes from repeating the steps of earlier stages: find the most frequent pair, merge it, and repeat. GPT-2 did this 50,000 times on its training text. Its first six merges were:
| New id | Pair | Token |
|---|---|---|
| 256 | (32, 116) |
␠t |
| 257 | (32, 97) |
␠a |
| 258 | (104, 101) |
he |
| 259 | (105, 110) |
in |
| 260 | (114, 101) |
re |
| 261 | (111, 110) |
on |
␠ marks a space, byte 32. Later merges build on earlier ones. Merge 262 combines ␠t and he into ␠the. This loop is called byte-pair encoding, or BPE.
The train command
The train command reads text from a file and runs the loop as many times as --num-merges asks:
- Convert the text into UTF-8 bytes.
- Find the most frequent pair. On a tie, the pair that appears first, reading left to right, wins.
- Replace that pair with the next new id. The first merge creates 256, the second creates 257, and so on.
- Repeat steps 2 and 3 on the new list until you have done
--num-mergesmerges. Keep going even when the most frequent pair appears only once.
For example, here’s aaabdaaabac with --num-merges 3:
| Round | Ids | Most frequent pair | New id |
|---|---|---|---|
| 1 | [97, 97, 97, 98, 100, 97, 97, 97, 98, 97, 99] |
(97, 97), 4 times |
256 |
| 2 | [256, 97, 98, 100, 256, 97, 98, 97, 99] |
(256, 97), tied with (97, 98) and first |
257 |
| 3 | [257, 98, 100, 257, 98, 97, 99] |
(257, 98), 2 times |
258 |
The command prints the merged pairs in order:
[
[97, 97],
[256, 97],
[257, 98]
]
The tester parses your output as JSON, so spacing and line breaks are up to you. [[97,97],[256,97],[257,98]] on one line passes too.
Tests
The tester will write aaabdaaabac to corpus.txt and execute your program like this:
$ ./your_program.sh train corpus.txt --num-merges 3
Your program must print the merged pairs as a JSON array:
[
[97, 97],
[256, 97],
[257, 98]
]
The tester will also ask for 6, 10, and 50 merges, including on a corpus with spaces and newlines, and for 5 merges on the sentence from “Your progress”.
Notes
- Print only the pairs, in the order you merged them. A pair’s position gives its id, so the list needs no ids.
- The tester never asks for more merges than the text allows.
5. Encode
Русский · Кодирование по рангу
Команда encode применяет готовый список слияний к новому тексту. Среди пар, которые сейчас присутствуют, выбирайте правило с наименьшим индексом в списке. Правило с индексом i создаёт ID 256+i. Для текста abab и правил [[97, 98], [256, 256]] результат [257].
Вопрос для SynQ. Почему подсчёт частот заново может изменить результат кодирования?
Қазақша · Ранг бойынша кодтау
encode командасы дайын біріктіру ережелерін жаңа мәтінге қолданады. Ағымдағы жұптардың ішінен ережелер тізімінде индексі ең кіші жұпты таңдаңыз. Индексі i болатын ереже 256+i ID санын жасайды. abab мәтіні мен [[97, 98], [256, 256]] ережелері үшін нәтиже [257].
SynQ-ға сұрақ. Жиілікті қайта санау неге кодтау нәтижесін өзгертуі мүмкін?
English specification
In this stage, you’ll implement the encode command to turn new text into token ids with a list of learned merges.
Your progress
11 tokens for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
encode ███████████ 11 tokens ← this stage
GPT-2 ██████ 6 tokens ← the goal
The 11 comes from encoding the sentence with the five merges learned from it.
Why encode?
GPT-2’s tokenizer was trained once. Since then, it has encoded every prompt with the same 50,000 merges, replayed in the order they were learned. That is how Hello world becomes [15496, 995], the same two ids every time.
Your train command produces exactly that kind of list. In this stage, you’ll use it.
The encode command
The encode command reads text from text.txt and merges from merges.json, a JSON array of pairs in the same format train prints. A pair’s position in the list is its rank, and the pair at index i, counting from 0, creates id 256 + i.
- Convert the text into UTF-8 bytes.
- Find the pair with the earliest rank that is still present in the ids.
- Merge every occurrence of that pair, the same way the
mergecommand does. - Repeat until no pair of neighboring ids is in the list.
For example, training on aaabdaaabac gave the merges [[97, 97], [256, 97], [257, 98]]. Here’s how they encode the text aaab:
| Round | Ids | Pair with the earliest rank | New id |
|---|---|---|---|
| 1 | [97, 97, 97, 98] |
(97, 97), rank 0 |
256 |
| 2 | [256, 97, 98] |
(256, 97), rank 1 |
257 |
| 3 | [257, 98] |
(257, 98), rank 2 |
258 |
No pairs are left, so the output is:
[258]
The same merges encode the training text as [258, 100, 258, 97, 99].
Rank is not frequency. Training picked the most frequent pair, but encoding ignores how often a pair appears. It only looks at rank.
To see the difference, take a new text, ababa, and say merges.json is [[98, 97], [97, 98]]. The text’s bytes are [97, 98, 97, 98, 97], so (97, 98) and (98, 97) each appear twice.
(98, 97) is first in merges.json, so it has the earliest rank and is merged first. That turns the ids into [97, 256, 256]. Both 98s are now used up, so (97, 98) is no longer present, and the output is:
[97, 256, 256]
Tests
The tester will write aaab to text.txt and [[97, 97], [256, 97], [257, 98]] to merges.json, then execute your program like this:
$ ./your_program.sh encode text.txt --merges merges.json
Your program must print the token ids as a JSON array:
[258]
The tester will also run your program on a few other files, including the training text, the ababa example above, an empty file, and the sentence from “Your progress”.
Notes
- Always apply the earliest learned merge that is still present.
- Applying a later merge first can produce ids a model never saw in training.
6. Decode
Русский · Декодирование
Команда decode раскрывает каждый ID от 256 и выше в два ID по таблице слияний. Соберите все исходные байты в один буфер и декодируйте его как UTF-8. Некорректные последовательности обрабатывайте по правилу замены U+FFFD. При пустой таблице [210, 154] даёт строку «Қ», а [240, 159] — один символ замены. Выведите строку JSON.
Вопрос для SynQ. Что произойдёт с буквой Қ, если декодировать каждый её байт отдельно?
Қазақша · Кодты мәтінге айналдыру
decode командасы 256 және одан үлкен әр ID санын ереже кестесі арқылы екі ID санына жіктейді. Бастапқы байттардың бәрін бір буферге жинап, UTF-8 мәтініне айналдырыңыз. Жарамсыз тізбек үшін U+FFFD алмастыру таңбасын қолданыңыз. Ережелер кестесі бос кезде [210, 154] массиві «Қ» мәтінін, ал [240, 159] бір алмастыру таңбасын береді. Мәтінді JSON жолы ретінде шығарыңыз.
SynQ-ға сұрақ. Қ әрпінің екі байтын бөлек декодтасаңыз, не болады?
English specification
In this stage, you’ll implement the decode command to turn token ids back into text.
Your progress
Back to the original text for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
encode ███████████ 11 tokens
decode ██████████████████████ 22 bytes, the original text ← this stage
GPT-2 ██████ 6 tokens ← the goal
Decoding those 11 ids with the same five merges gives the sentence back.
Why decode?
A language model writes its answer as token ids. Decode turns those ids back into text.
👋 is four UTF-8 bytes, [240, 159, 145, 139]. GPT-2 splits them across two tokens, [41840, 233], ids from its own vocabulary. Token boundaries don’t have to line up with character boundaries: the first token holds [240, 159, 145] and the second holds [139]. UTF-8 needs all four bytes to make 👋, so decoding the first token by itself gives the replacement character �. Join the bytes from both tokens first, and the result is 👋.
Your decoder does the same with any text. Complete characters come back as themselves. Bytes that stop halfway through a character come back as �.
The decode command
The decode command parses two JSON files in the formats from earlier stages: ids.json is an array of ids, and merges.json is an array of pairs.
- Build the same vocabulary training would. Id
nbelow 256 is the single byten. Id256 + iis the bytes of the first id in mergei, followed by the bytes of the second. - Join every token’s bytes into one buffer.
- Decode that buffer as UTF-8. Wherever the bytes are invalid, use the replacement character U+FFFD.
For example, [258, 100] with the three merges from aaabdaaabac prints:
"aaabd"
258 expands to 257 and 98, then to 256, 97, and 98, and finally to the bytes of aaab. 100 is d.
[240, 159, 145, 139] prints the wave emoji.
How many replacement characters?
U+FFFD, shown as �, is a replacement character, not a replacement byte. One � can stand for several bytes. Read the buffer left to right, one character at a time:
- The first byte says how long the character is. 0–127 is a 1-byte character, 194–223 starts a 2-byte one, 224–239 a 3-byte one, and 240–244 a 4-byte one.
- Every byte after the first must be a continuation byte, 128–191.
- If the character is complete, output it. If a byte doesn’t fit, or the buffer ends first, output one
�for the bytes read so far and start the next character at the byte that didn’t fit. - A byte that can’t start a character, like 255 or a stray continuation byte, is one
�by itself.
| Bytes | Prints | Why |
|---|---|---|
[240, 159] |
"\uFFFD" |
240 starts a 4-byte character and 159 continues it. The buffer ends first, so both bytes are one �. |
[255, 255] |
"\uFFFD\uFFFD" |
255 never starts a character, so each 255 is its own �. |
[240, 240] |
"\uFFFD\uFFFD" |
The second 240 doesn’t continue the first, so the first 240 is one �. The buffer ends after the second 240, so it is another �. |
The exact rule
For invalid input, the tests in this stage only use cut-off characters and bytes that never appear in UTF-8, so the rule above is enough. UTF-8 also limits the second byte after four lead bytes, which rules out overlong encodings, surrogates, and values above U+10FFFF:
| First byte | Length | Second byte |
|---|---|---|
| 224 | 3 | 160–191 |
| 237 | 3 | 128–159 |
| 240 | 4 | 144–191 |
| 244 | 4 | 128–143 |
A second byte outside its range doesn’t fit, just like any other byte that doesn’t continue a character. This is the Unicode Standard’s maximal subpart rule. The built-in decoders in Python, Rust, and TypeScript follow it exactly. Java’s differs only on surrogates, which these tests don’t use.
Tests
The tester will write [258, 100] to ids.json and [[97, 97], [256, 97], [257, 98]] to merges.json, then execute your program like this:
$ ./your_program.sh decode ids.json --merges merges.json
Your program must print the text as a JSON string:
"aaabd"
The tester will also run your program on a few other lists, including the full wave emoji, half of the wave emoji, bytes that are never valid UTF-8, and the ids of the sentence from “Your progress”.
Notes
- Join every token’s bytes before decoding. The half-emoji is one replacement character. The program should keep running when the bytes are not valid UTF-8.
For Python
bytes.decode("utf-8", errors="replace")replaces invalid bytes this way.
For TypeScript
new TextDecoder().decode(bytes)replaces invalid bytes this way.
For Java
new String(bytes, StandardCharsets.UTF_8)replaces invalid bytes this way.
For Rust
String::from_utf8_lossyreplaces invalid bytes this way.
For Go
- Write the decoding loop yourself, following the rule in “How many replacement characters?”. Ranging over a string gives one U+FFFD per invalid byte, and
strings.ToValidUTF8gives one per run of invalid bytes, so neither matches. Once a character’s bytes are complete,utf8.DecodeRunedecodes them.
For C++
-
Write the decoding loop yourself, following the rule in “How many replacement characters?”. The C++ standard library has no UTF-8 decoder that replaces invalid bytes. Valid characters can be copied to the output as their bytes, and each
�is the 3 bytes 239, 191, 189. -
Print the text with your JSON library, so quotes, backslashes, and newlines are escaped correctly.
"\uFFFD"and"�"are the same JSON string, so either passes.
7. Split like GPT-2
Русский · Границы фрагментов GPT-2
В режиме --pretokenize gpt2 сначала разделите строку по шаблону GPT-2, приведённому ниже. Примените слияния независимо внутри каждого фрагмента и соедините списки ID. В строке Hello world's 123!! пять фрагментов. Проверьте пробел перед world и границу перед 's.
Вопрос для SynQ. Какое слияние допустимо внутри Hello, но недопустимо между разными фрагментами?
Қазақша · GPT-2 мәтін бөліктерінің шекарасы
Ағылшын бөлімінде берілген GPT-2 үлгісімен --pretokenize gpt2 режимінде мәтінді алдымен бөліктерге бөліңіз. Әр бөліктің ішінде біріктіру ережелерін бөлек қолданып, ID тізімдерін соңында жалғаңыз. Hello world's 123!! мәтіні бес бөліктен тұрады. world сөзінің алдындағы бос орынды және 's алдындағы шекараны тексеріңіз.
SynQ-ға сұрақ. Hello сөзінің ішінде қандай біріктіруге болады? Екі бөліктің шекарасында нені біріктіруге болмайды?
English specification
In this stage, you’ll implement the --pretokenize gpt2 option to split text into chunks before merging, the way GPT-2 does.
Your progress
11 → 13 tokens for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
train ███████████ 11 tokens
split █████████████ 13 tokens ← this stage
GPT-2 ██████ 6 tokens ← the goal
The 13 comes from the same five merges. One of them joins ␠the to the ␠t of the next word, which are now in different chunks, so it no longer applies.
Why split first?
The GPT-2 paper found plain BPE spending merges on dog., dog!, and dog?, one token for each variation. So GPT-2’s merges were learned on text that was split into chunks first, and no merge ever joined two chunks.
An encoder has to split the same way. Otherwise it merges across boundaries that training never crossed, and produces tokens GPT-2 never saw in those places. GPT-2 encodes dog. dog! dog? as dog, ., ␠dog, !, ␠dog, and ?, where ␠ marks a space. ␠dog is one token, used twice.
Splitting with GPT-2’s pattern
GPT-2 splits with this pattern, from tiktoken:
'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s
The pattern starts with an apostrophe. Its first branch matches the contractions 's, 'd, 'm, 't, 'll, 've, and 're.
Split the text with this pattern, encode each chunk with the merges from --merges, and concatenate the ids. A space joins the chunk that follows it. For example, the text Hello world's 123!! splits into five chunks:
"Hello" " world" "'s" " 123" "!!"
These are exactly GPT-2’s five tokens for it. With merges [[108, 108], [111, 32]], the ids are:
[
72, 101, 256, 111, 32, 119, 111, 114, 108, 100, 39, 115, 32, 49, 50, 51, 33,
33
]
ll inside Hello becomes 256. The o and the following space are in different chunks, so they stay 111 and 32.
Three rules settle the tricky cases:
- The optional space before letters, numbers, and punctuation is U+0020 only. A non-breaking space is a chunk of its own.
- Contractions are case sensitive.
don'tsplits intodonand't, andDON'Tsplits intoDON,', andT. - Devanagari vowel signs are marks, outside
\p{L}, so a run of them is its own chunk.हिंदीsplits intoह,िं,द, andी.
With --pretokenize gpt2, the encode command reads the same text.txt and merges.json as before.
Tests
The tester will write Hello world's 123!! to text.txt and [[108, 108], [111, 32]] to merges.json, then execute your program like this:
$ ./your_program.sh encode text.txt --merges merges.json --pretokenize gpt2
Your program must print the token ids as a JSON array:
[
72, 101, 256, 111, 32, 119, 111, 114, 108, 100, 39, 115, 32, 49, 50, 51, 33,
33
]
The tester will also run your program on a few other files, including DON'T, हिंदी, a non-breaking space, and the sentence from “Your progress”.
Notes
- The apostrophe in the example is U+0027.
For Python
- Your project already includes the
regexpackage, which supports\p{L}and++. Useimport regexin place of the built-inre.
For TypeScript
- TypeScript regexes don’t support possessive quantifiers. Replace each
++with+, which gives the same chunks here, and use theganduflags. Withoutu,\p{L}matches the literal textp{L}.
For Java
- Compile the pattern with
Pattern.UNICODE_CHARACTER_CLASS. Otherwise\sdoesn’t match a non-breaking space.
For Go
- Go’s
regexppackage has no lookahead, so your project already includesregexp2/v2, which runs the pattern unchanged. Compile it withregexp2.Noneand step through the chunks withFindStringMatchandFindNextMatch. Withregexp2.RE2,\sdoesn’t match a non-breaking space.
For Rust
- The
regexcrate has no lookahead, so your project already includesfancy-regex, which runs the pattern unchanged.Regex::newcompiles it, andfind_itergives the chunks.
For C++
std::regexhas no\p{L}, so your project already includes PCRE2, which runs the pattern unchanged. Compile it withPCRE2_UTF | PCRE2_UCP, then callpcre2_matchin a loop, starting each search where the last chunk ended. WithoutPCRE2_UCP,\sdoesn’t match a non-breaking space.
8. Match GPT-2
Русский · Словарь GPT-2
Режим --vocab читает vocab.json и merges.txt. Преобразуйте байты в печатные символы по таблице GPT-2, выполните слияния по рангам внутри фрагментов и найдите итоговые ID в словаре. Для Hello world без перевода строки ожидается [15496, 995]. Проверьте также начальный пробел и текст с двумя переводами строки.
Вопрос для SynQ. Почему пробел меняет ID слова и где это видно в словаре?
Қазақша · GPT-2 сөздігі
--vocab режимі vocab.json және merges.txt файлдарын оқиды. GPT-2 кестесі бойынша байттарды баспа таңбаларына айналдырыңыз, әр бөліктің ішінде жұптарды рангімен біріктіріңіз, соңғы ID сандарын сөздіктен табыңыз. Жол соңы жоқ Hello world мәтіні үшін нәтиже [15496, 995]. Мәтін алдындағы бос орын мен қатар тұрған екі жол соңын да тексеріңіз.
SynQ-ға сұрақ. Бос орын сөздің ID санын неліктен өзгертеді және оны сөздіктен қалай көруге болады?
English specification
In this stage, you’ll implement the --vocab option to produce GPT-2’s exact token ids from its vocabulary files.
Your progress
6 tokens for the example sentence to the top of the tree
Here’s how many tokens the sentence to the top of the tree takes so far:
bytes ██████████████████████ 22 tokens
split █████████████ 13 tokens
GPT-2 ██████ 6 tokens ← this stage
The sentence splits into 6 chunks, and GPT-2’s vocabulary has one token for each of them.
Matching GPT-2
Your encoder already splits text like GPT-2. The last piece is GPT-2’s own vocabulary: its 50,000 merges and the id of every token. With those, the text Hello world encodes as:
[15496, 995]
The text Hello world, with a leading space, encodes as:
[18435, 995]
These are the same ids OpenAI’s tokenizer produces, and you can watch GPT-2’s quirks happen. The text strawberry strawberry encodes as:
[301, 1831, 8396, 41236]
The first strawberry has no space before it and splits into st, raw, and berry. The second one includes its space, and strawberry is a single token.
GPT-2’s files
The --vocab flag names the directory that holds vocab.json and merges.txt. GPT-2’s files store each byte as a printable character. Bytes 33–126, 161–172, and 174–255 are printable, so they map to themselves. The other 68 bytes, in increasing order, map to U+0100 and upward. The first 33 of them are bytes 0 to 32, so a byte n below 33 is stored as U+0100 + n.
Check your table against these five bytes:
| Byte | Value | Stored as | Id in vocab.json |
|---|---|---|---|
! |
33 | ! |
0 |
a |
97 | a |
64 |
| Tab | 9 | ĉ (U+0109) |
197 |
| Newline | 10 | Ċ (U+010A) |
198 |
| Space | 32 | Ġ (U+0120) |
220 |
vocab.json is a JSON object that maps each token to its id, like {"!": 0, "Hello": 15496, "Ġworld": 995}. Parse it with your language’s JSON library. Its keys use JSON escapes such as "\u0120" for Ġ, and the library turns them back into characters.
merges.txt lists pairs in rank order, after a #version line.
Split the text with the same pattern as earlier stages. For each chunk, map its UTF-8 bytes to characters, merge the characters using the ranks in merges.txt, and look up each piece in vocab.json:
" Hello" → bytes 32 72 101 108 108 111
→ characters Ġ H e l l o
→ merged by rank into ĠHello
→ vocab.json id 18435
Splitting first still matters. In Hello\n\nworld, the two newlines are separate chunks, so they stay two newline tokens instead of becoming GPT-2’s double-newline token, 628:
[15496, 198, 198, 6894]
Tests
The tester will write Hello world to text.txt, put GPT-2’s vocab.json and merges.txt in a gpt2 directory, and execute your program like this:
$ ./your_program.sh encode text.txt --vocab gpt2
Your program must print the token ids as a JSON array:
[15496, 995]
When a short text passes, the tester’s log shows the piece of text behind each id, like "Hello" " world". When one fails, it shows the expected pieces next to yours.
The tester will also run your program on a few other files, including strawberry strawberry, a Hindi sentence, a short program with indented lines, and the sentence from “Your progress”.
Notes
- In
merges.txt, skip blank lines and only the first line,#version: 0.2. Real merges such as# #also start with#. Split each remaining line on a single space. - None of the hidden texts contain
<|endoftext|>. - Ids from earlier stages are byte values. Here, look every token up in
vocab.json. If a lookup fails, check your byte-to-character table.
Source and licence
Stage material by CodeCrafters. Source snapshot · Original licence.
MIT License Copyright (c) 2026 CodeCrafters Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.