GNGiseldo Neo and Alana NeoBooks
Language Models with Python9 / 16

Assembling the Complete Model (GPT Style)

Integration of all the components developed previously to create a functional decoder-only architecture ready to generate text.

This chapter integrates a decoder-only Transformer, the paradigm used by models in the GPT and Llama families. Unlike the original encoder-decoder Transformer, this organization is geared toward autoregressive modeling: predicting each next token using only the preceding context.

9.1 High-Level Architecture

The architecture contains learned embeddings, a stack of decoder blocks, and a final projection that maps the internal representations back to the vocabulary space.

9.1.1 Architecture Diagram

The diagram shows the path from token IDs to logits. Note the normalization before the sublayers (pre-norm), common in modern implementations because it favors the stability of deep networks.

Diagram

9.2 Integrating the Components

To assemble the model, we integrate the components defined in previous chapters. The architecture is defined by hyperparameters: dmodeld_{model} (embedding dimension), NlayersN_{layers} (depth), NheadsN_{heads} (attention heads), and VV (vocabulary size).

9.2.1 A. Embedding Layer

This is the model’s input: it converts discrete indices into dense vectors and incorporates position information. * Token Embeddings: A lookup table of size (V,dmodel)(V, d_{model}). * Positional Embeddings: A lookup table of size (ContextLen,dmodel)(ContextLen, d_{model}). In GPT, these are typically learned parameters rather than fixed sinusoidal functions. * Combination: The two embeddings are summed element-wise.

9.2.2 B. Decoder Block

Most of the computation happens here. Each block contains normalization, self-attention with a causal mask, a feed-forward network, and two residual connections. The mask guarantees that position tt attends only to positions up to tt, preserving the autoregressive objective.

9.2.3 C. Output Head

After passing through NN blocks:

  1. Final normalization: stabilizes the final hidden states.
  2. Linear projection: maps dmodeld_{model} to VV, the vocabulary size.
  3. Weight sharing: optionally, the projection uses the same matrix as the input embeddings, reducing parameters.

9.3 Implementation Logic

Below is a structural representation of the complete model using a PyTorch-like class structure. This demonstrates how the components interact in code.

import torch
import torch.nn as nn
from torch.nn import functional as F

class GPT(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config

        # 1. Embeddings
        self.token_embedding = nn.Embedding(config.vocab_size, config.n_embd)
        self.position_embedding = nn.Embedding(config.block_size, config.n_embd)
        self.drop = nn.Dropout(config.dropout)

        # 2. Stack of Decoder Blocks
        # Assuming 'Block' is a class defined in previous chapters
        self.blocks = nn.ModuleList([
            Block(config) for _ in range(config.n_layer)
        ])

        # 3. Final Normalization
        self.ln_f = nn.LayerNorm(config.n_embd)

        # 4. Output Head
        self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)

        # Weight tying: embedding weights == output head weights
        self.token_embedding.weight = self.head.weight

        self.apply(self._init_weights)

    def _init_weights(self, module):
        """ Initialize weights (typically normal distribution with small std) """
        if isinstance(module, nn.Linear):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                torch.nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(self, idx, targets=None):
        # idx shape: (Batch, Seq_Len)
        B, T = idx.shape

        # Create position indices: [0, 1, 2, ..., T-1]
        pos = torch.arange(0, T, dtype=torch.long, device=idx.device)

        # Forward pass through embeddings
        tok_emb = self.token_embedding(idx) # (B, T, n_embd)
        pos_emb = self.position_embedding(pos) # (T, n_embd)
        x = self.drop(tok_emb + pos_emb)

        # Forward pass through transformer blocks
        for block in self.blocks:
            x = block(x)

        # Final Norm
        x = self.ln_f(x)

        # Project to vocabulary
        logits = self.head(x) # (B, T, vocab_size)

        loss = None
        if targets is not None:
            # Flatten for CrossEntropyLoss
            # logits: (B*T, vocab_size), targets: (B*T)
            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))

        return logits, loss

9.4 Training Forward Pass versus Generation

It is crucial to distinguish how this model operates during training versus generation.

9.4.1 Parallel Training

During training, the entire correct sequence is available. For input [A, B, C], the target is [B, C, D]. The causal mask makes it possible to compute simultaneously the predictions of B given A, of C given AB, and of D given ABC, without revealing the future. The cross-entropy is computed over all valid positions.

9.4.2 Sequential Inference

During generation, the future is unknown. We start from [A], select B from the logits, append the token, and repeat with [A,B]. The cycle ends when <EOS> is generated or the configured limit is reached. A key-value cache avoids recomputing all of the prefix’s attention at each step.

9.5 Integration Summary

The GPT-style model combines embeddings, causal blocks, and a vocabulary head into an entirely differentiable path. During training, it learns regularities useful for predicting the next token; during inference, it applies that same function repeatedly to produce a continuation.

Causality test

Change the last token of a sequence and run the model in evaluation mode. The logits of the earlier positions should remain the same, apart from small numerical differences. If they change, the mask is allowing leakage from the future.

9.6 Dense Models and Mixture of Experts

In the dense Transformer, all tokens pass through the same FFN in each block. A Mixture of Experts (MoE) layer contains several FFNs and a router that chooses a small subset for each token. In this way, the total number of parameters can grow without all of them being activated on every pass.

Diagram

The router produces scores and selects, for example, the two most relevant experts. The output combines these results with normalized weights. The model remains differentiable along the selected routes, but training needs auxiliary terms to prevent almost all tokens from being sent to the same experts.

MoE separates available parameters from parameters active per token. This can increase capacity while keeping compute cost under control, but it adds communication between devices, load balancing, and per-expert capacity limits. A model with more total parameters is not automatically slower or better; the comparison must consider active parameters, memory, and architecture.

9.7 Accounting for the Complete Path

For IDs with shape (B,T)(B,T), the embeddings produce (B,T,d)(B,T,d). The stack preserves this shape, as does the final normalization, and the language head generates (B,T,V)(B,T,V). In training, all positions contribute in parallel. In generation, normally only the logits of the last position decide the new token.

Configuration is part of the checkpoint

Number of layers, dimension, heads, KV groups, vocabulary, position type, and normalization must accompany the weights. Matrices with compatible shapes can still represent semantically incompatible architectures.