Continuing the work from LLM Inference Engine (Chapter 1): From Model Weights to Concurrent Requests, we will focus here on building a Transformer architecture from scratch. Constructing a Transformer requires a solid understanding of mathematics, especially matrix operations such as matrix multiplication, matrix addition, and matrix transposition. Make sure you still remember how to perform these operations. If not, that’s okay—we will review them while implementing these foundational operations in code.
Before starting, there is an important detail to pay attention to. The Transformer architecture has three variants: Encoder–Decoder, Encoder-only, and Decoder-only. What we learned in “Attention Is All You Need” – Paper Explained is the Encoder–Decoder architecture, which was the very first design and can be considered the original Transformer architecture. However, researchers found that, depending on the NLP task (described here: AI Prerequisites: What You Need to Know Before Learning LLMs), an encoder-only or decoder-only architecture is sufficient and can achieve better performance. Below is a comparison of the three variants:
| Component | Encoder-Only | Decoder-Only | Encoder-Decoder |
|---|---|---|---|
| Token embeddings | Yes | Yes | Yes |
| Positional encoding | Yes | Yes | Yes |
| Multi-head self-attention | Yes | Yes (causal) | Yes (both sides) |
| Cross-attention | No | No (standard GPT/LLaMA) | Yes |
| Feed-forward network | Yes | Yes | Yes |
| Layer normalization | Yes | Yes | Yes |
| Autoregressive generation | No (not natively) | Yes | Yes |
| Requirement | Recommended Architecture |
|---|---|
| Understand and classify text | Encoder-Only |
| Extract entities and information | Encoder-Only |
| Generate natural language | Decoder-Only |
| Build conversational AI | Decoder-Only |
| Translate between languages | Encoder-Decoder |
| Transform one sequence into another | Encoder-Decoder |
An important observation: Decoder-only architectures such as LLaMA can perform many tasks traditionally associated with encoder models through prompting and in-context learning. This is the reason why decoder-only models have become so popular in modern generative AI.
1. Decoder-only Transformer Architecture
The Decoder-only Trasnformer Architecture looks like so:
DECODER-ONLY TRANSFORMER (LLaMA)
=================================
Input Text
|
v
Tokenizer
|
v
Token IDs
|
v
+------------------------+
| Token Embedding | <--- token_embd.weight
+------------------------+
|
v
+------------------------+
| |
| Transformer Block 0 | <--- blk.0.* weights
| |
+------------------------+
|
v
+------------------------+
| |
| Transformer Block 1 | <--- blk.1.* weights
| |
+------------------------+
|
v
...
|
v
+------------------------+
| |
| Transformer Block N | <--- blk.N.* weights
| |
+------------------------+
|
v
+------------------------+
| Final Norm | <--- output_norm.weight
+------------------------+
|
v
+------------------------+
| LM Head | <--- output.weight
+------------------------+
|
v
Output Logits
|
v
Token Sampling
|
v
Generated Token
Weights are read from the GGUF file (the model file), while the number of Transformer blocks is read from the GGUF metadata. This architecture is specific to Llama, as an example. Other models might be slightly different and will be described in their GGUF files.
2. How to build it?
2.1. Matrix Operations
2.1.1. Matrix Addition
Example:
A = | 1 2 | B = | 5 6 | | 3 4 | | 7 8 |A + B = | 1+5 2+6 | | 3+7 4+8 | = | 6 8 | | 10 12 |
2.1.2. Matrix Multiplication
Example:
A = | 1 2 | B = | 5 6 | | 3 4 | | 7 8 |AB = | 1×5 + 2×7 1×6 + 2×8 | | 3×5 + 4×7 3×6 + 4×8 | = | 19 22 | | 43 50 |
2.1.3. Matrix Transposition
Example:
A = | 1 2 3 | | 4 5 6 |Aᵀ = | 1 4 | | 2 5 | | 3 6 |
2.1.4. Element-wise Multiplication
Example:
A = | 1 2 | B = | 5 6 | | 3 4 | | 7 8 |A ⊙ B = | 1×5 2×6 | | 3×7 4×8 | = | 5 12 | | 21 32 |
2.2. Tokenizer & Token IDs
Tokenization is the process of splitting an input sequence, commonly referred to as a user’s prompt, into smaller units called tokens. Each token has a corresponding Token ID and is defined in model’s vocabulary. In a GGUF file, the vocabulary is stored in the tokenizer.ggml.tokens metadata array. Each entry represents a token supported by the model. We can inspect this vocabulary using a GGUF reader such as Python’s gguf library:
The simplest form of tokenization is to turn a sentence into an array of its words by splitting the sentence at whitespace. Unlike ordinary word segmentation by whitespace, tokenization does not necessarily split text into complete words. A token can represent a complete word, a subword, a punctuation mark, a sequence of whitespace characters, or even an individual character.
2.2.1 Example
For example, suppose the model has the following simplified vocabulary:
ID Token0 <unk>1 <s>2 </s>3 The4 quick5 brown6 fox7 jumps8 over9 the10 lazy11 dog12 .
Given the prompt:
"The quick brown fox jumps over the lazy dog."
The tokenizer might produce the following token sequence:
["The", " quick", " brown", " fox", " jumps", " over", " the", " lazy", " dog", "."]
Notice that whitespace can also be represented as part of a token. The actual tokenization depends on the model’s tokenizer configuration and vocabulary.
When converting tokens into Token IDs, each token is replaced with its corresponding numerical identifier:
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
This numerical sequence is what the Token Embedding block receives as input.
2.2.2. How to tokenize a user’s prompt
Each model is published with a tokenizer.json file that specifies the segmentation algorithm for an inference engine to implement. For example, the specifications for Llama 3 look like this:
"pre_tokenizer": {
"type": "Sequence",
"pretokenizers": [
{
"type": "Split",
"pattern": {
"Regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
},
"behavior": "Isolated",
"invert": false
},
{
"type": "ByteLevel",
"add_prefix_space": false,
"trim_offsets": true,
"use_regex": false
}
]
},
This specifications mean that the inference engine must split user promts by following steps:
- Execute operations in sequence: The
Sequenceconfiguration tells the tokenizer to execute two operations in order:Splitfollowed byByteLevel. - Identify text boundaries: The
Splitoperation uses a regular expression to identify different text patterns, including English contractions, words, numbers, punctuation, and whitespace. - Recognize contractions: It identifies common English contractions such as
's,'t,'re,'ve,'m,'ll, and'd, regardless of letter case. - Group letters into words: It groups consecutive Unicode letters into word-like pieces, optionally including one preceding character that is neither a letter nor a number.
- Split numbers: It divides consecutive numerical characters into groups of up to three digits.
- Group punctuation: It groups consecutive punctuation and other non-letter, non-number, non-whitespace characters, optionally including trailing line breaks.
- Handle whitespace: It applies separate rules to line breaks, trailing spaces, and other whitespace sequences.
- Keep matched pieces: The
Isolatedbehavior ensures that matched pieces are retained as separate outputs rather than discarded. - Convert to byte-level representation: The
ByteLeveloperation converts the resulting text pieces into a reversible byte-level representation, allowing the tokenizer to handle arbitrary text characters consistently. - Preserve original spacing:
add_prefix_space: falseprevents the tokenizer from automatically inserting a space at the beginning of the input. - Preserve offsets:
trim_offsets: truecontrols how whitespace is handled when tracking token positions relative to the original input text. - Disable additional regex splitting:
use_regex: falseprevents the ByteLevel operation from applying another regular-expression splitting pass because the precedingSplitoperation has already established the boundaries.
The algorithm described above is called pre-tokenization. Next, the Llama 3 model expects a merge step. The specifications for the merge step are also defined in tokenizer.json, under the model.merges key. This is also called the merge rules table, which contains rules for merging split tokens when they appear adjacent to each other. The input to the merge step is the output of the pre-tokenization step. For example, a merge rules table can look like so:
{ "model": { "type": "BPE", "dropout": null, "unk_token": null, "continuing_subword_prefix": null, "end_of_word_suffix": null, "fuse_unk": false, "byte_fallback": false, "ignore_merges": false, "vocab": { "!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "...": ... }, "merges": [ "Ġ t", "Ġ a", "h e", "i n", "Ġ th", "ĠThe", "..." ] }}
Each entry in the merges list defines a rule that tells the tokenizer which two adjacent tokens can be combined into one larger token. For above example, it means: (here, Ġ represents a leading space.)
"ĠThe": If tokenĠis next to tokenThe, merge them into one tokenĠThe."Ġ t": If tokenĠis next to tokent, merge them into one tokenĠt."Ġ a": If tokenĠis next to tokena, merge them into one tokenĠa."h e": If tokenhis next to tokene, merge them into one tokenhe."i n": If tokeniis next to tokenn, merge them into one tokenin."Ġ th": If tokenĠis next to tokenth, merge them into one tokenĠth.
After the merge step, tokens are looked up in the vocabulary table to obtain their IDs. The resulting array, IDs, is the numerical representation of the user’s prompt, and the matrix operations begin with this array.
A vocabulary is essentially a lookup table that maps each token to a unique token ID. In Llama 3, for example, the vocabulary is stored in the model.vocab section of its tokenizer.json file. Each entry consists of a token string and its corresponding integer ID. A simplified vocabulary might look like this:
{ "model": { "vocab": { "hello": 15339, "world": 1917, "Ġhello": 3306, "Ġworld": 1917, "!": 0 } }}
Note: This is an illustrative example, not Llama 3’s actual vocabulary entries or token IDs. The Ġ character is commonly used in byte-level BPE tokenizers to represent a preceding space.
Chain the Pre-Tokenization, Merges, and Vocabulary Lookup steps together; the overall process is as follows:
INPUT PROMPT
"The quick brown fox jumps over the lazy dog."
|
v
+-----------------------------+
| PRE-TOKENIZATION STEP |
| |
| How should the text be |
| split into initial pieces? |
+-----------------------------+
|
v
PRE-TOKENIZED PIECES
["The", " quick", " brown", " fox",
" jumps", " over", " the", " lazy",
" dog", "."]
|
v
+-----------------------------+
| MERGE STEP |
| |
| Which adjacent pieces |
| should be merged according |
| to the BPE merge rules? |
+-----------------------------+
|
v
FINAL TOKENS
["The", " quick", " brown", " fox",
" jumps", " over", " the", " lazy",
" dog", "."]
|
v
+-----------------------------+
| VOCABULARY LOOKUP |
| |
| Find the numerical ID |
| corresponding to each |
| token in the vocabulary. |
+-----------------------------+
|
v
TOKEN IDs
[ID_1, ID_2, ID_3, ID_4, ...]
Here is a pseudocode that illustrates tokenization process:
FUNCTION initialize_tokenizer(gguf_file): metadata = read_gguf_metadata(gguf_file) vocabulary = metadata["tokenizer.ggml.tokens"] tokenizer_type = metadata["tokenizer.ggml.model"] pre_tokenizer = metadata["tokenizer.ggml.pre"] merges = metadata["tokenizer.ggml.merges"] tokenizer = CREATE_TOKENIZER( tokenizer_type, pre_tokenizer, vocabulary, merges ) RETURN tokenizerFUNCTION tokenize(prompt, tokenizer): tokens = tokenizer.encode(prompt) token_ids = [] FOR token IN tokens: token_ids.append(token.id) RETURN token_ids
3. Next Challenge
Here, we convert the user’s prompt in human language into an array of token IDs. This array serves as the input for the next step: token embedding. This is where matrix operations begin.
Next Challenge: How To Perform Token Embedding?
Let subscribe to know when next steps are available.

5 thoughts on “LLM Inference Engine (chapter 2): Transformer Architecture From Scratch – Tokenization”