Start by reading model weights from a safetensors file. Build the numerical operations of a transformer and follow the data from tensors to token generation.

Set up your project

Choose a starter for your language. Go · Python · Rust.

Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.

Contents

Core project

1. Read safetensors

In this stage, you’ll implement the inspect command to print what’s inside a trained model’s file.

How an inference engine works

An inference engine is the program that runs a trained model. The model here is GPT-2, and it comes already trained, as a file of numbers called its weights.

GPT-2’s weights are in a file called model.safetensors. It holds 160 named tables of numbers:

model.safetensors
├── wte.weight      one row of 768 numbers for each of 50,257 tokens
├── wpe.weight      one row of 768 numbers for each of 1,024 positions
├── h.0.…           13 tables for layer 0
├── h.1.…           13 tables for layer 1, and so on up to h.11
├── ln_f.weight
└── ln_f.bias

GPT-2 doesn’t read words. It reads token ids, numbers that each stand for a word or a part of a word. For example, the prompt “The capital of France is” becomes the ids [464, 3139, 286, 4881, 318].

The weights do nothing on their own. Reading the file, running the layers, and choosing each next word are the engine’s work, and the engine is what you build.

Step What it does Stages
Inspect Reads every tensor’s name, shape, and first numbers. Preparation, not generation Read safetensors
Embed Turns each token id into a row of numbers Embed tokens
Attend Mixes earlier tokens into the current one Causal attention, Multi-head attention, Residual connections, Transformer block
Score Scores every possible next token Logits
Pick Takes the highest score, or samples Greedy decode, Sample a token
Repeat Feeds the new token back in, reusing past work KV cache
Run All of it on GPT-2’s real 548 MB file Run GPT-2

You build each row in one or two stages. Generation itself starts at Embed, with the token ids. Inspect comes first because it makes the weights readable, and checkable.

Why start with inspect?

The model file is a set of named tables of numbers. The tables are called tensors. They hold numbers arranged in different ways, for example 4 numbers in a single list, or 6 numbers in 2 rows of 3.

To generate text, your engine does arithmetic with these numbers, so it has to read them correctly first. inspect prints every tensor’s name, data type, shape, and first numbers, so you can see exactly what your engine loaded. It keeps earning its place after this stage. When numbers in later stages come out wrong, inspect is how you check what you loaded.

The inspect command

inspect answers one question: what is in this model file? You point it at a file, and it prints what it finds:

$ ./your_program.sh inspect model.safetensors

The output is a JSON array with one entry per tensor, sorted by name. Each entry has the tensor’s:

  • name
  • dtype, the kind of number it holds, such as F32, a 32-bit float
  • shape, the tensor’s sizes. [4] is a single list of four numbers.
  • first, its first 4 numbers, or all of them when the tensor has fewer

For a tensor named scale whose four numbers are 1, 0.5, 0.25, and 0.125, the output is:

[
  {
    "name": "scale",
    "dtype": "F32",
    "shape": [4],
    "first": [1.0, 0.5, 0.25, 0.125]
  }
]

The file uses a format called safetensors. The starter code’s loader already reads it, and returns every tensor’s dtype, shape, and numbers, by name.

That’s the entire exercise: load the tensors, pick out a few values, and print them as JSON. There’s no model arithmetic in this stage. Later stages do the computing, on the tensors the loader returns.

Tests

The tester will write a model.safetensors file holding the scale tensor from the example, then execute your program like this:

$ ./your_program.sh inspect model.safetensors

Your program must print:

[
  {
    "name": "scale",
    "dtype": "F32",
    "shape": [4],
    "first": [1.0, 0.5, 0.25, 0.125]
  }
]

The tester reads your output as JSON, so [1,0.5] and [1.0, 0.5] both pass. It will also run a tensor with more than four numbers, a file whose tensors are not in name order, a file with two tensors, and a file with an I32 tensor.

Original stage zf8

2. Embed tokens

In this stage, you’ll implement the embed command to turn each token id into a row of numbers.

Why embed?

GPT-2 doesn’t read text. It reads tokens, which are words or pieces of words, and each token has a number called its id. GPT-2 knows 50,257 tokens. For example, the prompt “The capital of France is” is five tokens, with the ids [464, 3139, 286, 4881, 318].

An id is only a label, like a locker number. It says which token this is, and nothing about it. GPT-2 does all its work with arithmetic, so it swaps each id for a row of 768 numbers that describe the token. Those numbers were set during training, and tokens used in similar ways ended up with similar rows. For example, the six rows most similar to the row for ” Monday” are the other six days of the week.

Token rows and position rows

The rows are in a table called wte.weight, with one row for each token id. It is one of GPT-2’s weights, the numbers it learned in training.

A token’s row doesn’t say where the token sits in the prompt. So a second table, wpe.weight, has one row for each position: row 0 for the first token, row 1 for the second, and so on, up to 1,024 positions.

A token’s embedding is the sum of its two rows, added number by number. For example, “France” is token 4881, at position 3 in “The capital of France is”. Here are the first 4 of its 768 numbers, rounded:

row 4881 of wte.weight      [-0.07,  0.05,  0.16, -0.07, ...]
row 3 of wpe.weight       + [ 0.00, -0.07,  0.11,  0.00, ...]
                            ---------------------------------
embedding of "France"     = [-0.07, -0.02,  0.27, -0.07, ...]

If “France” appeared again at position 5, it would use the same row 4881 of wte.weight but row 5 of wpe.weight, so its embedding would be different.

The embed command

embed reads two files. In this stage’s example:

  • ids.json holds the token ids, [1, 0].
  • model.safetensors holds the two tables:
    • wte.weight, with shape [2, 2] and values 1, 2, 3, 4.
    • wpe.weight, with shape [2, 2] and values 10, 20, 30, 40.

For the id at position i in ids.json, counting from 0:

  1. Take row id of wte.weight.
  2. Take row i of wpe.weight.
  3. Add the two rows, number by number.
Finding a row

The loader gives you each table as a tensor: one flat list of its numbers, and a shape that says how to cut the list into rows. With a shape of [rows, columns], the rows sit one after another, so row r starts at index r * columns:

wte.weight, shape [2, 2]

index      0    1    2    3
values     1    2    3    4
           ------   ------
           row 0    row 1

For Python

The starter code’s load_tensors returns a dictionary like {"wte.weight": {"dtype": "F32", "shape": [2, 2], "values": ...}}. For each tensor, "values" holds its flat list of numbers.

For Rust

The starter code’s load_tensors returns a HashMap<String, Tensor>. Each Tensor holds its shape in shape and its flat list of numbers in values.

For Go

The starter code’s loadTensors returns a map[string]tensor. Each tensor holds its shape in Shape and its flat list of numbers in Values.

So in this example, the rows of wte.weight are [1, 2] and [3, 4], and the rows of wpe.weight are [10, 20] and [30, 40]:

Position Id Row of wte.weight Row of wpe.weight Embedding
0 1 [3, 4] [10, 20] [13, 24]
1 0 [1, 2] [30, 40] [31, 42]

Print the embeddings in order, as a JSON array of rows:

[
  [13, 24],
  [31, 42]
]
Tests

The tester will write model.safetensors and ids.json, then execute your program like this:

$ ./your_program.sh embed model.safetensors ids.json

Your program must print:

[
  [13.0, 24.0],
  [31.0, 42.0]
]

The tester reads your output as JSON, so 13 and 13.0 both pass. It will also run two tables of random numbers, with rows of four numbers and ids that repeat and are not in order. The numbers change on every run, and the tester’s log lists every tensor it wrote.

Notes
  • Print only the JSON to stdout. Send debug output to stderr, the way the starter code prints its Logs from your program will appear here! line.

For Python

  • A slice of values is a memoryview, which json.dumps can’t print, so build each embedding as a list. Keep the tensors themselves as the loader returns them. GPT-2’s real weights wouldn’t fit in the test server’s memory as Python floats.

Original stage pq6

3. Causal attention

In this stage, you’ll implement the attn command to mix each token’s row with itself and the rows before it.

Why attention?

After embedding, the row for a token is only that token. For example, take the sentence “The capital of France is”. The row for “is” does not yet depend on “France”, so nothing in it says which capital comes next.

Attention fixes this by replacing each row with a weighted average of itself and the rows before it. Later words don’t exist yet when GPT-2 writes a word. For example, in one of its later steps, GPT-2 gives the row for “is” these weights:

Word Weight
“The” 0.35
“capital” 0.02
“of” 0.01
“France” 0.57
“is” 0.06

More than half of the new row for “is” comes from “France”. GPT-2 often parks weight it doesn’t need on the first word, which is the 0.35 on “The”.

Where the weights come from

Attention turns every row into three lists of numbers. The query is the question the row asks, the key is what the row says about itself, and the value is what the row passes on when it matches. The row for “is” might ask “which earlier word names a place?”, and the row for “France” might answer “I name a place.”

A score is how well one row’s key answers another row’s query. It is the dot product of the two: multiply them number by number, and add up the products. The pair above scores highly. Softmax then turns a row’s scores into weights that add up to 1, by raising e to each score and dividing by their total. A score that leads by 2 gets about 7 times the weight.

A query, a key, and a value, with the weights they give, make up one head. GPT-2 runs 12 heads side by side, and the weights for “is” above came from one of them. In this stage, attn runs a single head. You’ll add the others in later stages.

The attn command

attn takes three files and a layer number. In this stage’s example:

  • config.json is a JSON object of sizes, using the same names as GPT-2’s config:

    { "n_embd": 1, "n_head": 1, "n_layer": 1, "n_positions": 4, "vocab_size": 2 }
  • model.safetensors holds four weight tables per layer, named with h. and the layer number. For layer 0:

    • h.0.attn.c_attn.weight, with shape [n_embd, 3 * n_embd]
    • h.0.attn.c_attn.bias, with shape [3 * n_embd]
    • h.0.attn.c_proj.weight, with shape [n_embd, n_embd]
    • h.0.attn.c_proj.bias, with shape [n_embd]
  • The layer number is the layer to run: 0. The file holds every layer’s weights, and attn runs one of them.

  • input.json is a JSON array of the rows to mix, one row per position: [[1], [2]].

Multiplying a row by a weight means multiplying matrices: a row of n numbers times a weight of shape [n, m] gives m numbers, where number j is the dot product of the row with column j.

attn turns each input row into an output row of the same length. Compute each position’s output row like this:

  1. Multiply the position’s row by c_attn.weight and add c_attn.bias. Split the result into three equal parts: the query, the key, and the value.
  2. Score the position against itself and every earlier position. A score is the dot product of this position’s query with the other position’s key, divided by the square root of n_embd, the count of numbers in a query.
  3. Softmax the scores into weights.
  4. Add up the scored positions’ values, each multiplied by its weight.
  5. Multiply that sum by c_proj.weight and add c_proj.bias.
One head, step by step

In this example n_embd is 1, so every row, query, key, and value is a single number, and the input is [[1], [2]]. Each step’s result is shown under its number:

// 1. row × c_attn.weight [[1, 1, 1]] + c_attn.bias [0, 0, 0]
position 0    query 1   key 1   value 1
position 1    query 2   key 2   value 2

// 2. query · key / sqrt(1), skipping later positions
position 0    1*1 = 1
position 1    2*1 = 2,  2*2 = 4

// 3. softmax
position 0    [1]                  // a single score always gets weight 1
position 1    [0.119, 0.881]

// 4. weighted average of the values
position 0    1 * 1 = 1
position 1    0.119 * 1 + 0.881 * 2 = 1.881

// 5. × c_proj.weight [[1]] + c_proj.bias [0] leaves both unchanged
output        [[1], [1.881]]

Print one JSON array of rows:

[[1.0], [1.8807970779778822]]
Hints
What does the whole algorithm look like as pseudocode?
// input[i] is the row at position i of input.json, counting from 0

for each position i:
    // 1. query, key, and value, n_embd numbers each
    qkv = input[i] × c_attn.weight + c_attn.bias
    q[i] = qkv[0 : n_embd]
    k[i] = qkv[n_embd : 2 * n_embd]
    v[i] = qkv[2 * n_embd : 3 * n_embd]

for each position i:
    for each position j from 0 to i:      // itself and earlier only
        // 2. how well j's key answers i's query
        score[j] = dot(q[i], k[j]) / sqrt(n_embd)
    // 3. scores to weights that add up to 1
    weight = softmax(score[0], ..., score[i])
    // 4. the weighted average of the values
    out[i] = sum over j of weight[j] * v[j]
    // 5. the output projection
    result[i] = out[i] × c_proj.weight + c_proj.bias
Why divide the scores by the square root of n_embd?

A dot product adds one product per number, so longer queries give larger scores. Large scores make the softmax put almost all the weight on one position. Dividing by the square root of the length keeps the scores in the same range whatever the length.

Tests

The tester will write the three files from the example, then execute your program like this:

$ ./your_program.sh attn model.safetensors config.json 0 input.json

Your program must print:

[[1.0], [1.8807970779778822]]

The tester allows a difference of 0.0001 on each number. It will also run two models whose weights are random numbers between -1 and 1, with rows of four numbers: one for layer 0, and one that reads layer 1 of a two-layer file. The numbers change on every run, and the tester’s log lists every tensor it wrote. Every config.json in this stage has an n_head of 1.

Notes

Original stage mo0

4. Multi-head attention

In this stage, you’ll extend the attn command to split each row into slices that each get their own weights.

Why more than one head?

Your attn gives each row one set of weights. For example, take the sentence “The capital of France is”. More than half of the weight for “is” went to “France”, which leaves little for anything else the row might need.

GPT-2 looks in 12 ways at once. It splits each query, key, and value into 12 slices, called heads, and each head works out its own weights from its own slice. Here are two of GPT-2’s heads for “is”, in the same layer:

Word One head Another head
“The” 0.35 0.63
“capital” 0.02 0.24
“of” 0.01 0.01
“France” 0.57 0.05
“is” 0.06 0.07

The first head is the one you saw before. The second puts about a quarter of its weight on “capital” and almost none on “France”. Each head takes its own weighted average, and the results go side by side to make the new row.

Splitting into heads

config.json says how many heads there are, in n_head. The head size is n_embd / n_head, the count of numbers in each slice. GPT-2 has 768 numbers in a row and 12 heads, so its head size is 64.

The query, key, and value are worked out as before, and so is the multiply by c_proj.weight at the end. The steps between them change:

  1. Split the query, the key, and the value into n_head equal slices, in order. Head 0 gets the first n_embd / n_head numbers of each, head 1 the next, and so on.
  2. For each head, score the position against itself and every earlier position, using only that head’s slices. Divide each score by the square root of the head size, where you divided by the square root of n_embd before.
  3. For each head, softmax its scores into weights, and add up its slices of the values, each multiplied by its weight.
  4. Put the heads’ results side by side, in head order. That gives n_embd numbers again, ready for c_proj.weight.
Two heads, step by step

In this example n_embd is 2 and n_head is 2, so each head gets one number. The weights copy each row into its query, key, and value, and the input is [[1, 0], [0, 1]]. Here is position 1, whose query is [0, 1]:

// head 0 uses number 0 of each query, key, and value
scores        0*1 = 0,  0*0 = 0            // / sqrt(1)
weights       [0.5, 0.5]
average       0.5 * 1 + 0.5 * 0 = 0.5

// head 1 uses number 1
scores        1*0 = 0,  1*1 = 1
weights       [0.269, 0.731]
average       0.269 * 0 + 0.731 * 1 = 0.731

// side by side, then × c_proj.weight, which leaves them unchanged
output row    [0.5, 0.731]

Position 0 has only itself to look at, so each head gives it a weight of 1 and its row stays [1, 0]. Print one JSON array of rows:

[[1.0, 0.0], [0.5, 0.7310585786300049]]

With one head, the same files give [0.330, 0.670] for position 1, because the softmax then runs once over both numbers.

Hints
What does the whole algorithm look like as pseudocode?
size = n_embd / n_head                    // numbers per head

// q[i], k[i], and v[i] are position i's query, key, and value, as before

for each position i:
    for each head h:
        a, b = h * size, (h + 1) * size   // this head's slice
        for each position j from 0 to i:
            score[j] = dot(q[i][a : b], k[j][a : b]) / sqrt(size)
        weight = softmax(score[0], ..., score[i])
        out[i][a : b] = sum over j of weight[j] * v[j][a : b]
    result[i] = out[i] × c_proj.weight + c_proj.bias
Why does the division change to the head size?

The division keeps scores in the same range whatever the length of the query. A head’s score now adds up only the products in its slice, so the length that matters is the slice’s. GPT-2’s heads have 64 numbers, so it divides by 8.

Tests

The tester will write the three files from the example, then execute your program like this:

$ ./your_program.sh attn model.safetensors config.json 0 input.json

Your program must print:

[[1.0, 0.0], [0.5, 0.7310585786300049]]

The tester allows a difference of 0.0001 on each number. It will also run two models whose weights are random numbers between -1 and 1, with two heads and rows of four numbers: one for layer 0, and one that reads layer 1 of a two-layer file. The numbers change on every run, and the tester’s log lists every tensor it wrote.

Notes
  • With an n_head of 1 the only slice is the whole row, so the files your attn already handles give the same output.
  • To see heads on your own sentences, the Transformer Explainer runs GPT-2 in the browser and draws each head’s weights.

Original stage bx7

5. Residual connections

In this stage, you’ll implement the block command to run attention inside a layer norm and a residual add.

Why wrap attention?

attn replaces each row with a weighted average of itself and the rows before it, and that throws something away. In the weights you saw when you built attn, only 0.06 of the new row for “is” came from “is”. The rest came from “France” and “The”, so the row now says what the sentence is about and has nearly forgotten which word it is.

A transformer keeps both. GPT-2 is a stack of 12 identical blocks, and a block adds attention’s output onto the row it started from instead of replacing it. The row keeps what it was, plus what attention found.

Adding onto a row over and over makes its numbers grow. So each block first rescales a copy of the row, a step called layer normalization. It shifts and scales the numbers so their average is 0 and their standard deviation is about 1, then applies a weight and a bias of its own. A row and the same row ten times larger come out almost the same:

row          [2, 4, 6, 8]                 [20, 40, 60, 80]
normalized   [-1.34, -0.45, 0.45, 1.34]   [-1.34, -0.45, 0.45, 1.34]

So attention runs on the normalized copy, and its output is added onto the row the copy came from. A block wraps a second step the same way, which later stages add.

The block command

block takes the same three files and layer number as attn. Along with the four attention tensors, it uses two more. For layer 0 they are:

Tensor Shape
h.0.ln_1.weight [n_embd]
h.0.ln_1.bias [n_embd]

Run these steps on the input rows:

row ─┬─► ln_1 ─► attention ─► + ─► output
     │                        ▲
     └────────────────────────┘
  1. Layer-normalize a copy of each row with ln_1.weight and ln_1.bias.
  2. Run attention on those copies, the same way attn does.
  3. Add the attention output onto the block’s input rows, not onto the copies.

Layer norm is one formula, with 0.00001 from GPT-2’s own definition. The mean and the variance are taken over the row’s numbers, and the variance is the average of (x - mean)^2:

layer_norm(x) = (x - mean) / sqrt(variance + 0.00001) * weight + bias
One block, step by step

ln_1 has weight [1, 1] and bias [0, 0], the attention tensors copy each row into its query, key, and value, and the input is [[1, 2]]:

// 1. layer norm with ln_1
mean          (1 + 2) / 2 = 1.5
variance      (0.5^2 + 0.5^2) / 2 = 0.25
normalized    [-0.5, 0.5] / sqrt(0.25 + 0.00001) = about [-1, 1]

// 2. attention on that copy
// one row attends only to itself, so it gets its own value back
attention     [-1, 1]

// 3. add onto the block's input
output        [1, 2] + [-1, 1] = [0, 3]

Print one JSON array of rows:

[[0.0, 3.0]]
Hints
What does this look like as pseudocode?
layer_norm(row, weight, bias):
    mean = the average of the row's numbers
    variance = the average of (x - mean)^2 over the row's numbers
    for each index i:
        x = (row[i] - mean) / sqrt(variance + 0.00001)
        out[i] = x * weight[i] + bias[i]

normed = layer_norm(each row, ln_1.weight, ln_1.bias)
attended = attention(normed)

for each position i:
    result[i] = row[i] + attended[i]
Tests

The tester will write the same three files as for attn. For this example, the layer is 0, input.json is [[1, 2]], and config.json is:

{ "n_embd": 2, "n_head": 1, "n_layer": 2, "n_positions": 4, "vocab_size": 2 }

It will then execute your program like this:

$ ./your_program.sh block model.safetensors config.json 0 input.json

Your program must print:

[[0.0, 3.0]]

The tester allows a difference of 0.0001 on each number. It will also run three rows of four numbers through a block whose ln_1 and attention weights are random numbers between -1 and 1, once for layer 0 and once for layer 1 of a two-layer file. Those models have two heads.

Notes
  • Divide by the count of numbers in the row when you take the variance. Many built-in variance functions divide by one less, which turns 0.25 into 0.5 for the row [1, 2] and the output into [0.29, 2.71] instead of [0, 3].
  • The file also holds ln_2 and the MLP tensors, which later stages use. They are all zeros here, so you can ignore them for now.

Original stage vb8

6. Transformer block

In this stage, you’ll finish the block command by adding the MLP that follows attention.

Why an MLP?

Attention moves information between rows. The other half of a transformer block does the opposite: it works on each row on its own and never looks at another. That half is an MLP, short for multilayer perceptron, and it holds about two-thirds of a block’s numbers.

It’s two multiplies by a weight with a function called GELU between them. The first widens the row from 768 numbers to 3,072, and the second brings it back.

The MLP is wrapped the way attention is, with a layer norm of its own, so a block normalizes twice:

row ─┬─► ln_1 ─► attention ─► + ─┬─► ln_2 ─► MLP ─► + ─► output
     │                        ▲  │                  ▲
     └────────────────────────┘  └──────────────────┘
The block command

Along with the tensors you already read, a block uses six more. For layer 0:

Tensor Shape
h.0.ln_2.weight [n_embd]
h.0.ln_2.bias [n_embd]
h.0.mlp.c_fc.weight [n_embd, 4 * n_embd]
h.0.mlp.c_fc.bias [4 * n_embd]
h.0.mlp.c_proj.weight [4 * n_embd, n_embd]
h.0.mlp.c_proj.bias [n_embd]

After the layer norm, attention, and residual add you already run, add three more steps:

  1. Layer-normalize a copy of each row with ln_2.weight and ln_2.bias.
  2. Multiply each copy by mlp.c_fc.weight, add mlp.c_fc.bias, and apply GELU to every number. The row is now 4 * n_embd numbers wide.
  3. Multiply by mlp.c_proj.weight, add mlp.c_proj.bias, and add the result onto the rows those copies came from.

GELU is one formula, and its constants are load-bearing. Some libraries offer an exact version that this one approximates, and the two differ by about 0.00015, which is enough to fail the tester:

gelu(x) = 0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x^3)))
One block, step by step

This example continues the one you worked through for the layer norm and the residual add. The layer norms have weight [1, 1] and bias [0, 0], the MLP’s weights keep the first two numbers of the wide row and put them back, and the input is [[1, 2]]:

// the layer norm, attention, and residual add you already run
row           [1, 2] + [-1, 1] = [0, 3]

// 1. layer norm with ln_2, the same rule
normalized    about [-1, 1]

// 2. × c_fc.weight + c_fc.bias, then GELU on every number
wide row      [-1, 1, 0, 0, 0, 0, 0, 0]     // 4 * n_embd numbers
after GELU    [-0.1588, 0.8412, 0, 0, 0, 0, 0, 0]

// 3. × c_proj.weight + c_proj.bias, added onto the row above
output        [0, 3] + [-0.1588, 0.8412] = [-0.1588, 3.8412]

Print one JSON array of rows:

[[-0.15878819, 3.84116958]]
Hints
What do the new steps look like as pseudocode?
gelu(x) = 0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x^3)))

for each position i:
    // row[i] is the row after attention was added onto it
    n = layer_norm(row[i], ln_2.weight, ln_2.bias)
    wide = gelu(each number of (n × mlp.c_fc.weight + mlp.c_fc.bias))
    row[i] = row[i] + (wide × mlp.c_proj.weight + mlp.c_proj.bias)
What does GELU do?

GELU keeps positive numbers close to themselves and pushes negative ones toward 0. Without it, the two multiplies would each be a multiply and an add, and two of those in a row work out to a single multiply and add. The wider middle would add nothing.

Tests

The tester will write the same three files as before, with input.json set to [[1, 2]] and the layer set to 0, then execute your program like this:

$ ./your_program.sh block model.safetensors config.json 0 input.json

Your program must print:

[[-0.15878819, 3.84116958]]

The tester allows a difference of 0.0001 on each number. It will also run three rows of four numbers through a block whose weights are all random numbers between -1 and 1, once for layer 0 and once for layer 1 of a two-layer file.

Notes
  • GPT-2’s MLP is always four times the row’s width, so mlp.c_fc.weight has shape [n_embd, 4 * n_embd]. Reading the width from that shape costs nothing and keeps the code honest if a model ever differs.

Original stage hu4

7. Logits

In this stage, you’ll implement the logits command to score every token as the next one.

Why logits?

The blocks change each row, but they don’t say which token comes next. Logits do. A logit is the model’s raw score for one token as the next token, and a higher logit means a more likely next token.

GPT-2 has 50,257 tokens, so it writes 50,257 logits, one per token. These are the five highest after “The capital of France is”:

Token Logit
” the” -100.25
” now” -100.82
” a” -100.86
” France” -101.21
” Paris” -101.21

The logits are all near -100, and that’s normal. Only the differences between them matter, so ” the” leads ” now” by 0.57.

The logits command

logits reads three files:

  • model.safetensors, with every tensor embed and block read, plus a final layer norm:
    • ln_f.weight, with shape [n_embd]
    • ln_f.bias, with shape [n_embd]
  • config.json, the same format as for attn
  • ids.json, the same format as for embed

Compute the logits like this:

rows = the embedding of the ids, as embed does
for each layer from 0 to n_layer - 1:
    rows = the block's output for rows, as block does

// layer norm with the same rule and 0.00001 as ln_1 in a block
last = layer_norm(the last row of rows, ln_f.weight, ln_f.bias)

for each token t:
    logit[t] = dot(last, row t of wte.weight)

The logits reuse the wte.weight table that embed reads. There is no separate output table.

In this example the ids are [0]. ln_f.bias is [1, -1] and ln_f.weight is [0, 0], so the normalized row is [1, -1]. The token rows are [1, 1] and [1, -1]. The dot products are 1 * 1 + -1 * 1 = 0 and 1 * 1 + -1 * -1 = 2.

Print one JSON array, the scores for the last position:

[0.0, 2.0]
Tests

The tester will write the three files and execute your program like this:

$ ./your_program.sh logits model.safetensors config.json ids.json

Your program must print:

[0.0, 2.0]

The tester allows a difference of 0.001 on each number, or 0.001 times the expected number, whichever is larger. It will also run two models whose weights are random numbers between -1 and 1, each with six tokens and a three-id sequence, where only the last position is scored. One has a single layer, and the other has two.

Original stage wi3

8. Greedy decode

In this stage, you’ll implement the generate command to repeatedly take the highest-scoring token.

Why greedy?

Logits score every possible next token, but writing text means choosing one. Greedy decoding is the simplest choice. It takes the highest score, appends that token, and scores the longer sequence again. It uses no randomness, so the same prompt always continues the same way, and you can check every id it writes.

Here is GPT-2 continuing “The capital of France is”, one step at a time:

Step Picked Runner-up Lead
1 ” the” ” now” 0.57
2 ” capital” ” city” 1.62
3 ” of” “,” 3.87
4 ” the” ” France” 0.33
5 ” French” ” Republic” 0.96
6 ” Republic” ” Empire” 1.32

At step 4, a lead of 0.33 is all that separates ” the capital of the French Republic” from ” the capital of France”.

The generate command

config.json and ids.json are the same format as for logits. tokens.json is a JSON object. In this stage it holds the count:

{ "count": 2 }

Generate the new ids like this:

repeat count times:
    scores = the logits for ids, as logits computes them
    best = the id with the highest score, the lower id on a tie
    append best to ids, and to the new ids
print the new ids as a JSON array

In this example ln_f.bias is [0, 1] and ln_f.weight is [0, 0], so the normalized last row is always [0, 1]. Against the token rows [1, 0] and [0, 1], token 0’s score is 0 and token 1’s score is 1. Both new tokens are token 1:

[1, 1]
Hints
How do I keep the lower id on a tie?

Go through the ids from 0 upward, and replace the best id only when a score is strictly greater than the best so far. An equal score then keeps the earlier, lower id.

Tests

The tester will write the four files and execute your program like this:

$ ./your_program.sh generate model.safetensors config.json ids.json tokens.json

Your program must print:

[1, 1]

The ids have to match exactly. The tester will also run a file where every token has the same score, and a two-layer model with random weights, where the four new ids are not all the same.

Notes
  • The new token’s position is its index in the whole sequence. A prompt of length 3 puts the first new token at position 3.

Original stage hh8

9. Sample a token

In this stage, you’ll add sampling to generate, to pick each new token at random, weighted by its probability.

Why sample?

Greedy decoding always appends the same token, so a prompt can only ever continue one way. Sampling picks a token at random, weighted by its probability, so the same prompt can continue differently on each run.

Temperature divides the logits before the softmax. A temperature below 1 makes the likely tokens even more likely. Here are GPT-2’s probabilities for the first token after “The capital of France is”:

Token Temperature 1 Temperature 0.7
” the” 0.085 0.227
” now” 0.048 0.101
” a” 0.046 0.096
” France” 0.032 0.058
” Paris” 0.032 0.057

Top-p then throws away the least likely tokens. It keeps the most likely ones until their probabilities add up to top_p. With a top_p of 0.9, that’s 1,503 tokens at temperature 1, and 62 at temperature 0.7.

Sampling one token

tokens.json gains two fields:

{ "count": 1, "temperature": 1, "top_p": 1 }

When tokens.json has no temperature, keep taking the highest score as before. The tester still runs those files, with nothing on stdin.

Stdin has one number per new token, each between 0 and 1. Read them as text, one per line. Pick each new token like this:

p = softmax(each logit / temperature)
order = the token ids sorted by p, highest first, the lower id first on a tie
kept = the shortest start of order whose p adds up to at least top_p
divide each kept p by the sum of the kept p, so they add up to 1 again

r = the next number from stdin
total = 0
for each id in kept, in order:
    total = total + p[id]
    if total > r: pick id, and stop

In this example the two tokens have the same score, so the probabilities are 0.5 and 0.5. The sorted order is token 0, then token 1. The running totals are 0.5 and 1. The random number is 0.6, which is past 0.5 and not past 1, so the token is 1.

[1]
Tests

The tester will write the four files, send the random numbers on stdin, and execute your program like this:

$ ./your_program.sh generate model.safetensors config.json ids.json tokens.json

Your program must print:

[1]

The ids have to match exactly. The tester will also run two models with random weights, asking each for four new tokens and sending four random numbers. One has a top_p below 1, and the other has a temperature other than 1.

Notes
  • top_p of 1 keeps every token that has a probability above 0.
  • GPT-2’s logits are all near -100. In 32-bit floats, raising e to a number that low gives 0, and the softmax then divides 0 by 0. Subtract the largest logit from every logit first. The probabilities come out the same, because softmax only depends on the differences between logits.

Original stage df2

10. KV cache

In this stage, you’ll reuse past keys and values in generate instead of recomputing the whole sequence.

Why keep keys and values?

A new token needs its own query, key, and value. The keys and values of the tokens already written do not change, so they can be kept and reused. Scoring a new token by running every earlier token through all of GPT-2’s 12 layers again repeats that work. Keeping the keys and values makes the new ids come out the same, with less arithmetic. This is called a KV cache, short for key-value cache.

For “The capital of France is” and six new tokens, greedy decoding runs 5 + 6 + 7 + 8 + 9 + 10 = 45 rows through each layer. Keeping the keys and values runs 10: the 5 prompt rows once, then one row for each new token except the last, since the last one is never fed back in. That saving matters when you run GPT-2’s real weights later, where an engine that recomputes the whole sequence at every step can run out of time.

The generate command

The command is the same one as greedy decoding. tokens.json again holds a count, and there is no temperature. The ids must match a run that recomputes the whole sequence at every step.

A key and a value are the lists of numbers from step 1 of attention, after c_attn and split into heads. Keep them in a list for each layer and each head:

keys[layer][head], values[layer][head] = empty lists

rows = the prompt's embeddings
run the blocks on rows, appending each row's key and value to the lists

repeat count times:
    pick the next id from the last row's logits
    if that was the last new id, stop
    row = the embedding of that id, at its position in the whole sequence
    for each layer:
        run the block on this one row
        // inside attention, for each head:
        append the row's key and value to keys[layer][head], values[layer][head]
        score the row's query against every key in keys[layer][head]

The softmax and the output projection are unchanged. The layer norms and the MLP work on one row at a time, so they only need the new row.

In this example ids.json is [0, 1, 0] and tokens.json is { "count": 3 }. The model has two tokens, and the rows of wpe.weight differ from each other, so a new token embedded at the wrong position changes what comes out. The ids are:

[0, 1, 1]
Tests

The tester will write the four files and execute your program like this:

$ ./your_program.sh generate model.safetensors config.json ids.json tokens.json

Your program must print:

[0, 1, 1]

The ids have to match exactly. The tester will also run a two-id prompt, where embedding each new token at position 0 instead of at its index in the whole sequence changes the ids, and a two-layer model with random weights, where each layer needs keys and values of its own.

Notes
  • The new token’s position is still its index in the whole sequence. The cache does not change the position row you add.
  • A prompt is cached in order, left to right, before the first new token.

Original stage rq5

11. Run GPT-2

In this stage, you’ll run your generate command on GPT-2’s real weights.

Why run GPT-2?

Every file so far was a tiny model built to check one rule. GPT-2’s real file uses the same tensor names, at full size: 160 tensors holding 124 million weights. Your engine already runs every step GPT-2 runs, so on the real weights it should write the same words GPT-2 does.

For example, take the prompt “The capital of France is”. Its ids are [464, 3139, 286, 4881, 318]. GPT-2 continues it with ” the capital of the French Republic”. Those six ids are:

[262, 3139, 286, 262, 4141, 2066]
Loading 548 MB

The tensors are the ones earlier stages read. wte.weight has shape [50257, 768], and there are 12 layers with 12 heads each. The file also has an h.<layer>.attn.bias tensor in every layer. It is GPT-2’s causal mask, saved with the weights, and you can skip it because your attention already drops the later scores. Those masks are 50 MB of the file’s 548 MB, which is why the file is larger than its weights.

The starter code’s loader already keeps each number as a 32-bit float, so the whole file takes about 550 MB of memory. The test server gives your program 2 GB, so keep the numbers the way the loader returns them, rather than turning each one into a separate object.

For Python

A list of Python floats, for example, would need about 4 GB.

Tests

The tester will link GPT-2’s weights to model.safetensors, write config.json, ids.json, and tokens.json, then execute your program like this:

$ ./your_program.sh generate model.safetensors config.json ids.json tokens.json

config.json is GPT-2’s:

{ "n_embd": 768, "n_head": 12, "n_layer": 12, "n_positions": 1024, "vocab_size": 50257 }

ids.json is [464, 3139, 286, 4881, 318], and tokens.json is {"count": 6}. Your program must print:

[262, 3139, 286, 262, 4141, 2066]

The ids have to match exactly. The tester will also turn your ids back into text and print what your engine wrote, ” the capital of the French Republic”.

This test takes longer than the earlier ones. The tester first downloads GPT-2’s weights, which takes 5 to 15 seconds, and then your engine runs all 12 layers for every token.

For Python

A Python engine that reuses keys and values takes about 45 seconds on a laptop, and can take longer on the test servers. The tester stops your program after 300 seconds, so an engine that recomputes the whole sequence at every step can run out of time.

For languages other than Python

A your language engine finishes in a few seconds.

Notes
  • To run GPT-2 on your own machine, download its weights from Hugging Face into a folder outside your repository, so the 548 MB file never ends up in a commit. Then use the config.json above:

    mkdir -p /tmp/testing && cd /tmp/testing
    curl -L -o model.safetensors https://huggingface.co/openai-community/gpt2/resolve/main/model.safetensors
  • To read your ids as text, download vocab.json from the same page. It maps each token’s text to its id, and a leading Ġ stands for a space. For a prompt whose words are each a single token, look up each word there to build ids.json.

  • Past six tokens, GPT-2’s top two scores can be very close. At the seventh step for this prompt they differ by 0.007, so an engine that uses 32-bit floats and one that uses 64-bit floats may choose different tokens. That doesn’t mean either one is wrong.

Original stage zr7

Back to contents

Source and licence

Stage material by CodeCrafters. Source snapshot · Original licence.

MIT License

Copyright (c) 2022 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.