Unit 3 of 9

From text to model inputs

  • 50 min
  • Reading, walkthrough, and knowledge check

What you’ll learn

  • Explain how byte-level BPE turns text into token IDs and back, and why the same tokenizer must do both.
  • Predict when token counts run well above word counts: numbers, code, emoji, and many non-English languages.
  • Render a chat template, count its special tokens, and avoid the doubled start token.
  • Calculate the embedding table’s memory for Llama 3.1 8B and explain why a token ID’s size means nothing.
  • Describe how rotary position embeddings and RMSNorm prepare token vectors for each layer.

Why the model never sees your text

A user sends one short question to your Llama 3.1 8B chat service: “What is the capital of France?” That is 6 words. The model receives 42 positions. Asked in Hindi, the same question takes 16 tokens instead of 7 before any of that overhead, and a prompt full of numbers or code costs more than its word count suggests.

Positions are what you pay for. The context limit, the KV cache (128 KiB per token for this model, from the KV cache lesson), prefill time, and per-token billing all count tokens, not words or characters. If you estimate from words, your capacity plan and your bill are both wrong.

This lesson follows text all the way to the first layer: how a tokenizer splits it into pieces and IDs, what a chat template adds, how each ID becomes a vector of 4,096 numbers, and how the model learns where each token sits. By the end you will be able to count tokens correctly, compute the embedding table’s memory, and spot the tokenization bugs that break real deployments.

How a tokenizer splits text

A token is one piece from a fixed vocabulary: a whole common word, part of a word, a digit group, a punctuation mark, or a single byte. The tokenizer splits text into these pieces and replaces each with its token ID, its number in the vocabulary. Llama 3.1 has 128,256 entries: 128,000 ordinary pieces with IDs 0 to 127,999, and 256 special tokens with IDs 128,000 to 128,255.

The sky is blue.The791␣sky13180␣is374␣blue6437.13TokenizationToken3404ization20651234567123451345610961722🚀 (4 bytes)F0 9F94689A24880222
Four inputs through the Llama 3.1 tokenizer, with each piece’s ID underneath. Common words are one token, a longer word splits into familiar parts, digits go in groups of up to three, and an emoji splits into pieces of its 4 bytes.

Notice that the space belongs to the following word: ␣sky is one token, and sky without the space is a different one. Case matters too. In Llama 3.1, Hello is 9906, ␣Hello is 22691, hello is 15339, and HELLO splits into HEL and LO.

Llama 3.1 uses byte-level BPE (byte pair encoding). The vocabulary is learned once, before the model is trained, by a simple procedure:

  1. Start from bytes

    Encode the training text as UTF-8 bytes. The first 256 vocabulary entries are the 256 possible byte values, so any text in any language can always be represented, even a character the tokenizer has never seen.

  2. Merge the most frequent pair

    Count every pair of neighboring pieces and merge the most common pair into a new piece with the next free ID. In Llama 3.1, ID 256 is two spaces, and the next IDs are four spaces, in, and ␣t.

  3. Repeat until the vocabulary is full

    Frequent words end up as single tokens, and rare words stay split into smaller pieces. Llama 3’s tokenizer stores 280,147 merge rules.

  4. Encode new text by replaying the merges

    At inference time the tokenizer first cuts text at spaces, punctuation, and digit groups with a fixed pattern, then applies the learned merges inside each chunk. The pattern is why 1234567 becomes 123, 456, and 7: digits are cut into groups of at most three before any merge runs.

Decoding reverses this: look up each ID’s bytes, join them, and decode the bytes as UTF-8. Because encoding and decoding share one vocabulary and one set of rules, text survives the round trip exactly. That is also why the tokenizer is part of the model. The model learned that ID 13180 means ␣sky; a different tokenizer would hand it valid-looking IDs that mean something else.

Why token counts differ from word counts

For ordinary English prose, Llama 3.1 uses a little more than one token per word. The Zen of Python (the text import this prints) has 144 words and 856 characters and becomes 181 tokens: 1.26 tokens per word, or 4.7 characters per token. Meta reports 3.94 characters per token on its English sample, up from 3.17 for Llama 2’s tokenizer. Other kinds of text are far less efficient:

Real counts from the Llama 3.1 tokenizer (words counted at spaces, no special tokens)
TextWordsTokensWhy
The cat sat on the mat.67Common words are one token each, plus the period.
The Zen of Python144181Typical English prose.
def add(a, b): and return a + b on two lines711Punctuation and indentation become tokens of their own.
123456713Digits go in groups of at most three.
2026-09-2916Each digit group and each dash is a token.
Привет, мир (Russian)25Fewer Cyrillic pieces in the vocabulary.
नमस्ते दुनिया (Hindi)29Many pieces are single characters or parts of them.
🚀13A 4-byte character with no piece of its own.

The pattern follows from how BPE was trained. Text that was common in the tokenizer’s training data got long pieces; everything else falls back to short pieces or raw bytes. Meta built Llama 3’s vocabulary from 100K tokens of OpenAI’s tiktoken tokenizer plus 28K tokens added for non-English languages, which improved many languages but did not make them as cheap as English.

Every token you add costs in three places. It takes a position in the context window (131,072 for Llama 3.1). It takes 128 KiB of KV cache for as long as the request lives. And it adds prefill work. A service that estimates capacity from word counts will overcommit memory as soon as users paste code, tables, or non-English text.

Chat templates and special tokens

A chat model does not receive a list of messages. It receives one sequence of tokens, built by a chat template: a small Jinja program, stored in the checkpoint’s tokenizer_config.json, that turns the messages into text with special tokens marking where each turn starts and ends. The model was trained on exactly this format, so the serving system must reproduce it exactly.

Llama 3.1’s main special tokens
TokenIDMeaning
<|begin_of_text|>128000The start of every sequence.
<|start_header_id|>, <|end_header_id|>128006, 128007Wrap a role name: system, user, assistant, or ipython.
<|eot_id|>128009End of a turn. The Instruct model ends its answers with it.
<|eom_id|>128008End of a message when the model has asked for a tool call.
<|end_of_text|>128001End of a document. The base model stops here.

Special tokens are single tokens with IDs of their own. The tokenizer never produces them by splitting ordinary text into pieces; they enter through the template. Here is what the official Llama 3.1 8B Instruct template produces for the one-question conversation, with add_generation_prompt=True so it ends where the assistant should start writing:

The rendered prompt
<|begin_of_text|><|start_header_id|>system<|end_header_id|>

Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024

<|eot_id|><|start_header_id|>user<|end_header_id|>

What is the capital of France?<|eot_id|><|start_header_id|>assistant<|end_header_id|>

Two details surprise most people. The template always adds a system header, even when you send no system message, and it fills that header with a knowledge cutoff date and a default “Today Date” of 26 Jul 2024 unless you pass another one. And each header ends with a blank line, \n\n, which is one token (ID 271).

start<|begin_of_text|>128000system<|start_header_id|>128006system9125<|end_header_id|>128007\n\n271Cutting Knowledge…20 tokens<|eot_id|>128009user<|start_header_id|>128006user882<|end_header_id|>128007\n\n271What is the…7 tokens<|eot_id|>128009assistant<|start_header_id|>128006assistant78191<|end_header_id|>128007\n\n271special tokenordinary tokenseveral ordinary tokens
The same prompt as tokens. Special tokens (blue) mark the structure; dashed cells stand for runs of ordinary tokens. The 7-token question becomes 42 tokens.

Where the 42 tokens come from

  1. Start of text1
  2. System header: start, role, end, blank line4
  3. Cutoff and date lines20
  4. End of the system turn1
  5. User header4
  6. The question itself7
  7. End of the user turn1
  8. Assistant header, where generation starts4

Result1 + 4 + 20 + 1 + 4 + 7 + 1 + 4 = 42 tokens, 35 of them from the template

The template also decides when generation stops. The Instruct model’s generation_config.json lists three end IDs: 128001, 128008, and 128009. A server that stops only on 128001, the base model’s end token, lets the model run past its <|eot_id|> and write the next turn of the conversation by itself.

Token IDs select rows of the embedding table

The model’s first step is the embedding lookup. The embedding table is a matrix with one row per vocabulary entry and one column per hidden feature: 128,256 × 4,096 for Llama 3.1 8B. Token ID 791 means “take row 791”. A prompt of S token IDs becomes a tensor of shape (S, 4096), and a batch of (B, S) IDs becomes (B, S, 4096).

hidden feature012⋯409500.010.01-0.02-0.020.000.00⋯⋯0.030.03⋮⋮⋮⋮⋮⋮⋮⋮⋮374 ␣is-0.01-0.010.020.020.010.01⋯⋯-0.02-0.02⋮⋮⋮⋮⋮⋮⋮⋮⋮791 The0.020.020.000.00-0.03-0.03⋯⋯0.010.01⋮⋮⋮⋮⋮⋮⋮⋮⋮6437 ␣blue0.000.00-0.01-0.010.020.02⋯⋯0.020.02⋮⋮⋮⋮⋮⋮⋮⋮⋮13180 ␣sky0.030.030.010.01-0.01-0.01⋯⋯-0.03-0.03⋮⋮⋮⋮⋮⋮⋮⋮⋮128255-0.02-0.020.010.010.000.00⋯⋯0.010.01rows selected by the prompt
The embedding lookup for “The sky is blue”. Each ID selects one full row of 4,096 values; nothing is computed. Values are illustrative.

So what does a large ID mean? Nothing about meaning or importance. An ID is an address, like a row number in a spreadsheet. The model never does arithmetic on it; it only uses it to fetch a row. The numbers reflect how the vocabulary was built: bytes got 0 to 255, merges got IDs in the order they were learned, the added multilingual pieces came later, and special tokens sit at the end. If you renumbered the entire vocabulary and moved the table’s rows to match, the model would behave identically.

The table is large even though the lookup is cheap. Llama 3.1 8B also keeps a second matrix of the same shape, the output layer, which turns the final vector back into one score per vocabulary entry. Its config.json sets tie_word_embeddings to false, so the two are stored separately.

Embedding memory for Llama 3.1 8B in BF16

  1. Values in the table128,256 × 4,096 = 525,336,576
  2. Bytes in BF16525,336,576 × 2 = 1,050,673,152 bytes ≈ 1.05 GB
  3. Bytes read per token by the lookup: one row4,096 × 2 = 8,192 bytes (8 KiB)
  4. Output layer, same shape, stored separatelyanother 1.05 GB

Result2.1 GB of the 16.06 GB of weights, 13%, is vocabulary-sized

The lookup gives the same vector to a token wherever it appears. In “the cat saw the dog”, both copies of ␣the start as identical rows. Everything that distinguishes them, including their positions, must come from later steps.

How position and normalization enter

Attention compares tokens with each other, and on its own it has no notion of order: without extra information, “dog bites man” and “man bites dog” contain the same vectors. The model needs each token’s position.

The original transformer added a fixed sinusoidal position vector to each token’s embedding at the input. Llama models use rotary position embeddings (RoPE) instead, and they apply them inside every attention layer rather than at the input. Nothing is added to the embeddings.

Here is the intuition. Picture each head’s 128 query features as 64 pairs, and each pair as a clock hand. Before attention compares a query with a key, RoPE turns every hand by an angle equal to the token’s position times that pair’s speed. The fastest pair turns 1 radian (about 57°) per position; the slowest turns less than a thousandth of a degree. When a query and a key are compared, only the difference between their angles matters, so the score depends on how far apart the two tokens are, not on where they sit in the document.

Llama 3.1 sets the speeds with rope_theta = 500,000 in config.json. Its rope_scaling block (factor 8 and original_max_position_embeddings 8,192) slows the slowest pairs further so the model can use 131,072 positions. Because keys are rotated before they enter the KV cache, a new token’s position must equal the number of tokens already cached, or every score it computes is subtly wrong.

The last preparation step is normalization. Before attention and again before the MLP, every layer rescales each token’s vector with RMSNorm: divide the vector by the root of its mean square, then multiply each feature by a learned weight. Llama 3.1 8B has 65 of these (2 per layer and 1 at the end), each with 4,096 weights and a small rms_norm_eps of 0.00001 that prevents division by zero. The normalized copy goes into the block, while the unnormalized vector carries on alongside it, as the attention lesson shows.

Try it: train a tokenizer and look up embeddings

You need Python 3.9 or later and NumPy. The first script trains a byte-level BPE with 8 merges on a tiny corpus, then encodes and decodes four words:

bpe_demo.py
from collections import Counter

# Train a tiny byte-level BPE: start from bytes, merge the most frequent pair.
corpus = "low lower lowest slow slower newer newest new new new " * 20
words = Counter(corpus.split())
vocab = {bytes([b]): b for b in range(256)}  # IDs 0-255 are the raw bytes
splits = {w: [bytes([b]) for b in w.encode("utf-8")] for w in words}

for step in range(8):
    pairs = Counter()
    for w, n in words.items():
        parts = splits[w]
        for a, b in zip(parts, parts[1:]):
            pairs[a, b] += n
    (a, b), count = pairs.most_common(1)[0]
    vocab[a + b] = len(vocab)  # the next free ID
    for w in words:
        parts, merged = splits[w], []
        while parts:
            if len(parts) > 1 and (parts[0], parts[1]) == (a, b):
                merged.append(a + b)
                parts = parts[2:]
            else:
                merged.append(parts[0])
                parts = parts[1:]
        splits[w] = merged
    new = (a + b).decode()
    print(f"merge {step + 1}: {new:<6} -> ID {vocab[a + b]} ({count} uses)")

for w in ["new", "newest", "slow", "lowly"]:
    parts = [bytes([b]) for b in w.encode("utf-8")]
    for piece in sorted(vocab, key=vocab.get):  # replay merges in ID order
        if len(piece) < 2:
            continue
        i = 0
        while i < len(parts) - 1:
            if parts[i] + parts[i + 1] == piece:
                parts[i:i + 2] = [piece]
            else:
                i += 1
    ids = [vocab[p] for p in parts]
    pieces = [p.decode() for p in parts]
    print(f"{w!r}: {pieces} -> {ids} -> {b''.join(parts).decode()!r}")
You should see
merge 1: lo     -> ID 256 (100 uses)
merge 2: low    -> ID 257 (100 uses)
merge 3: ne     -> ID 258 (100 uses)
merge 4: new    -> ID 259 (100 uses)
merge 5: lowe   -> ID 260 (60 uses)
merge 6: lower  -> ID 261 (40 uses)
merge 7: st     -> ID 262 (40 uses)
merge 8: newe   -> ID 263 (40 uses)
'new': ['new'] -> [259] -> 'new'
'newest': ['newe', 'st'] -> [263, 262] -> 'newest'
'slow': ['s', 'low'] -> [115, 257] -> 'slow'
'lowly': ['low', 'l', 'y'] -> [257, 108, 121] -> 'lowly'

The frequent word new became a single token. newest needed two pieces and slow reused low. lowly never appeared in training, yet it still encodes, into low and two single bytes, and decodes back exactly. That fallback to bytes is what lets a real tokenizer handle any text. Every new ID is the next free number after 255, which is the whole story behind ID sizes.

The second script checks three claims from this lesson: the lookup is row selection, renumbering the vocabulary changes nothing, and a lookup equals multiplying a one-hot vector by the table without doing the math:

embedding_demo.py
import numpy as np

rng = np.random.default_rng(0)
vocab_size, hidden = 6, 4
table = rng.standard_normal((vocab_size, hidden)).round(2)  # one row per token ID

ids = np.array([[3, 1, 3]])  # batch of 1, three positions; ID 3 appears twice
vectors = table[ids]  # the lookup is row selection
print("IDs shape:", ids.shape, "-> vectors shape:", vectors.shape)
print("position 0 == position 2:", np.array_equal(vectors[0, 0], vectors[0, 2]))

# Renumber the whole vocabulary and move the rows to match.
new_id = rng.permutation(vocab_size)  # old ID -> new ID
new_table = np.empty_like(table)
new_table[new_id] = table
renumbered = new_table[new_id[ids]]  # look up the new IDs in the new table
print("same vectors after renumbering:", np.array_equal(renumbered, vectors))

one_hot = np.eye(vocab_size)[ids]  # (1, 3, 6)
print("one-hot @ table equals lookup:", np.allclose(one_hot @ table, vectors))

rows, width, bytes_per_value = 128_256, 4_096, 2  # Llama 3.1 8B in BF16
size = rows * width * bytes_per_value
print(f"Llama 3.1 8B table: {rows * width:,} values, {size / 1e9:.2f} GB")
print(f"bytes read per token: {width * bytes_per_value:,}")
You should see
IDs shape: (1, 3) -> vectors shape: (1, 3, 4)
position 0 == position 2: True
same vectors after renumbering: True
one-hot @ table equals lookup: True
Llama 3.1 8B table: 525,336,576 values, 1.05 GB
bytes read per token: 8,192

The one-hot product gives the same answer, but for Llama 3.1 8B it would cost 2 × 128,256 × 4,096, about 1.05 billion FLOPs per token, to fetch 8 KiB. That is why every framework implements embeddings as a lookup.

The third script rotates an 8-feature query and key the RoPE way, using neighboring features as pairs, and shows that the score depends only on the distance between positions:

rope_demo.py
import numpy as np

def rotate(vec, position, base=500_000.0):
    """Turn each feature pair by position times that pair's frequency."""
    pairs = vec.reshape(-1, 2)
    freqs = base ** (-np.arange(len(pairs)) * 2 / vec.size)
    angle = position * freqs
    cos, sin = np.cos(angle), np.sin(angle)
    x, y = pairs[:, 0], pairs[:, 1]
    return np.stack([x * cos - y * sin, x * sin + y * cos], axis=1).reshape(-1)

rng = np.random.default_rng(1)
q, k = rng.standard_normal(8), rng.standard_normal(8)
for q_pos, k_pos in [(5, 3), (105, 103), (5, 0)]:
    score = rotate(q, q_pos) @ rotate(k, k_pos)
    print(f"query at {q_pos:>3}, key at {k_pos:>3}: score {score:+.4f}")
same_length = np.isclose(np.linalg.norm(rotate(q, 7)), np.linalg.norm(q))
print("rotation keeps the length:", same_length)
You should see
query at   5, key at   3: score -1.1497
query at 105, key at 103: score -1.1497
query at   5, key at   0: score -0.4872
rotation keeps the length: True

To see the real Llama 3.1 tokenizer, install transformers, accept the license on the model’s Hugging Face page, and log in with hf auth login. Then run:

llama_tokenizer.py
from transformers import AutoTokenizer

# Needs `pip install transformers` and access to the gated meta-llama repository.
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
for text in ["The sky is blue.", "1234567", "नमस्ते दुनिया"]:
    ids = tok(text, add_special_tokens=False)["input_ids"]
    print(len(ids), ids, tok.convert_ids_to_tokens(ids))

messages = [{"role": "user", "content": "What is the capital of France?"}]
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
print(repr(prompt))
print(len(tok(prompt, add_special_tokens=False)["input_ids"]))
print(len(tok(prompt)["input_ids"]))  # adds a second <|begin_of_text|>

You should see 5, 3, and 9 tokens with the IDs shown in this lesson, the rendered prompt from the template section, and then 42 and 43. If the last two numbers are equal, your tokenizer is not adding a start token by default; if the first is not 42, you have a different template version, so check which revision of the model you downloaded.

The last script needs only NumPy. It shows why byte counts, not character counts, feed a byte-level tokenizer, what happens when a character’s bytes are split, and what RMSNorm does to a token’s vector:

bytes_and_rmsnorm.py
import numpy as np

# A byte-level tokenizer starts from UTF-8 bytes, not characters.
for text in ["Hi", "café", "tiny 🚀"]:
    data = list(text.encode("utf-8"))
    print(f"{text!r}: {len(text)} characters, {len(data)} bytes {data}")

rocket = "🚀".encode("utf-8")
print("first 2 bytes alone:", rocket[:2].decode("utf-8", errors="replace"))
print("all 4 bytes:", rocket.decode("utf-8"))


def rms(v):
    return np.sqrt(np.mean(v * v))


def rms_norm(x, weight, eps=1e-5):
    rms = np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps)
    return x / rms * weight


rng = np.random.default_rng(0)
x = rng.normal(0, 3, 4096).astype(np.float32)  # one token's hidden vector
weight = np.ones(4096, dtype=np.float32)  # learned per feature; starts at 1
y = rms_norm(x, weight)
print(f"RMS before {rms(x):.4f}, after {rms(y):.6f}")
print("10 times the input, same output:", np.allclose(rms_norm(10 * x, weight), y))
tiny = np.full(4096, 0.001, dtype=np.float32)
print(f"tiny vector, RMS 0.001, after norm: {rms(rms_norm(tiny, weight)):.4f}")
You should see
'Hi': 2 characters, 2 bytes [72, 105]
'café': 4 characters, 5 bytes [99, 97, 102, 195, 169]
'tiny 🚀': 6 characters, 9 bytes [116, 105, 110, 121, 32, 240, 159, 154, 128]
first 2 bytes alone: �
all 4 bytes: 🚀
RMS before 2.9931, after 0.999999
10 times the input, same output: True
tiny vector, RMS 0.001, after norm: 0.3015

café is 4 characters but 5 bytes, because é takes two, and the rocket takes four. Decoding only the rocket’s first two bytes gives the replacement character �, the same symptom a streaming server shows when it decodes one token at a time. RMSNorm brings the vector’s RMS from about 3 to 1, and scaling the input by 10 changes nothing, so every layer sees inputs of the same size. The result is 0.999999 rather than exactly 1 because of the epsilon, which only matters for vectors that are already tiny: one with an RMS of 0.001 comes out at 0.3015 instead of 1.

Common mistakes

Symptoms, their usual cause, and the fix
SymptomLikely causeFix
Requests fail the context limit although the text looks shortCounts came from words or characters, or ignored the template.Render the template, then count with the deployed tokenizer.
Answers are slightly worse and the prompt starts with 128000 twiceThe rendered template was tokenized with special tokens added again.Use add_special_tokens=False on rendered text.
The model keeps writing, then answers its own next questionThe server stops only on 128001, not on <|eot_id|> (128009).Stop on every ID in the model’s generation_config.json.
A user’s message ends the turn early or changes rolesLiteral text such as <|eot_id|> in user input was turned into the real special token.Strip or escape special-token strings in user content, or tokenize it with split_special_tokens=True.
Streamed output shows � in the middle of wordsA character’s bytes were split across tokens and decoded one token at a time.Decode incrementally and hold back incomplete UTF-8 sequences.
Output is fluent-looking nonsense after swapping tokenizersThe tokenizer does not match the checkpoint, so IDs point at the wrong rows.Always load the tokenizer files from the same model revision as the weights.

How real systems handle tokenization

Serving engines treat the tokenizer as part of the model. They load tokenizer.json, tokenizer_config.json (which holds the chat template), and generation_config.json from the checkpoint, and an OpenAI-compatible chat endpoint applies the template on the server, so clients send messages rather than raw prompts. Tokenization runs on the CPU while the GPU runs the model; for very long prompts that CPU time shows up in time to first token.

Rules of thumb for capacity planning with Llama 3.1: about 1.3 tokens per English word, about 4 characters per token for English prose, and much more for code, numbers, and many other languages. Add the template overhead (35 tokens for a one-message conversation with the default system header) and the maximum output length, then multiply by 128 KiB per token for the KV cache.

Go deeperDetails that break real deployments

Byte-to-character mapping. Byte-level BPE vocabularies store each byte as a printable character so pieces can be saved as text. That is why tokenizer files show a space as Ġ and a newline as Ċ: Ġsky is sky. The rocket emoji’s first piece prints as ðŁ, its bytes F0 and 9F. Decoding maps the characters back to bytes before building text.

Which features form a RoPE pair. The demo pairs neighboring features (0 and 1, 2 and 3), as Meta’s reference code does. Hugging Face Transformers and vLLM pair feature i with feature i + 64 instead (the “rotate half” or GPT-NeoX layout) and permute the query and key weights when converting checkpoints to match. Load weights in one layout and rotate in the other, and the model runs with correct shapes and wrong outputs.

Template versions. A checkpoint’s chat template can change between revisions, and inference engines let you override it. Two deployments of the same weights with different templates give different answers and different token counts. Pin the model revision, and log the rendered prompt for a sample of requests.

Cheat sheet

  • Text becomes pieces, pieces become IDs, IDs select rows of the embedding table.
  • Llama 3.1: 128,256 vocabulary entries, 128,000 ordinary and 256 special (IDs 128,000 and up).
  • Count tokens with the deployed tokenizer after the chat template; never estimate from words for code, numbers, or non-English text.
  • One user question of 7 tokens becomes 42 tokens with Llama 3.1’s template. Tokenize rendered prompts with add_special_tokens=False.
  • Stop generation on every end ID in generation_config.json: 128001, 128008, and 128009 for Llama 3.1 Instruct.
  • A token ID is an address. Its size says nothing about meaning or importance.
  • Embedding table: 128,256 × 4,096 × 2 bytes ≈ 1.05 GB, plus an untied output layer of the same size.
  • RoPE rotates queries and keys by position inside every attention layer; RMSNorm rescales each token’s vector before every block.

Walkthrough

Follow a prompt from text to the first layer

Request traceReady

Knowledge check

What does token ID 900 being larger than token ID 12 imply?

Choose one answer

Sources and further reading

Finished this unit?