LLM Inference Engine (chapter 2): Transformer Architecture From Scratch – Tokenization

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:

ComponentEncoder-OnlyDecoder-OnlyEncoder-Decoder
Token embeddingsYesYesYes
Positional encodingYesYesYes
Multi-head self-attentionYesYes (causal)Yes (both sides)
Cross-attentionNoNo (standard GPT/LLaMA)Yes
Feed-forward networkYesYesYes
Layer normalizationYesYesYes
Autoregressive generationNo (not natively)YesYes
RequirementRecommended Architecture
Understand and classify textEncoder-Only
Extract entities and informationEncoder-Only
Generate natural languageDecoder-Only
Build conversational AIDecoder-Only
Translate between languagesEncoder-Decoder
Transform one sequence into anotherEncoder-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 Token
0 <unk>
1 <s>
2 </s>
3 The
4 quick
5 brown
6 fox
7 jumps
8 over
9 the
10 lazy
11 dog
12 .

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:

  1. Execute operations in sequence: The Sequence configuration tells the tokenizer to execute two operations in order: Split followed by ByteLevel.
  2. Identify text boundaries: The Split operation uses a regular expression to identify different text patterns, including English contractions, words, numbers, punctuation, and whitespace.
  3. Recognize contractions: It identifies common English contractions such as 's, 't, 're, 've, 'm, 'll, and 'd, regardless of letter case.
  4. 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.
  5. Split numbers: It divides consecutive numerical characters into groups of up to three digits.
  6. Group punctuation: It groups consecutive punctuation and other non-letter, non-number, non-whitespace characters, optionally including trailing line breaks.
  7. Handle whitespace: It applies separate rules to line breaks, trailing spaces, and other whitespace sequences.
  8. Keep matched pieces: The Isolated behavior ensures that matched pieces are retained as separate outputs rather than discarded.
  9. Convert to byte-level representation: The ByteLevel operation converts the resulting text pieces into a reversible byte-level representation, allowing the tokenizer to handle arbitrary text characters consistently.
  10. Preserve original spacing: add_prefix_space: false prevents the tokenizer from automatically inserting a space at the beginning of the input.
  11. Preserve offsets: trim_offsets: true controls how whitespace is handled when tracking token positions relative to the original input text.
  12. Disable additional regex splitting: use_regex: false prevents the ByteLevel operation from applying another regular-expression splitting pass because the preceding Split operation 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 token The, merge them into one token ĠThe.
  • "Ġ t": If token Ġ is next to token t, merge them into one token Ġt.
  • "Ġ a": If token Ġ is next to token a, merge them into one token Ġa.
  • "h e": If token h is next to token e, merge them into one token he.
  • "i n": If token i is next to token n, merge them into one token in.
  • "Ġ th": If token Ġ is next to token th, 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 tokenizer
FUNCTION 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”

Leave a Reply