Putting the Architecture Together
local graph
Chapter 16 — Putting the Architecture Together
Section titled “Chapter 16 — Putting the Architecture Together”Part IV introduced its innovations one at a time. This chapter assembles them. We combine Multi-head Latent Attention and Mixture-of-Experts into a single block, stack those blocks into a complete model, and trace DeepSeek-V3 — the canonical instance of this architecture — by its actual configuration. The most striking result is how little changes from the baseline GPT of Chapter 10: the block structure is identical, and only the contents of its two sublayers are swapped. That is the payoff of having built everything modularly.
16.1 The Modern Block: MLA plus MoE
Section titled “16.1 The Modern Block: MLA plus MoE”The frontier decoder block is the pre-norm block of Chapter 8 with two substitutions: MLA in place of plain multi-head attention, and an MoE layer in place of the dense feed-forward network. One detail from DeepSeek-V3 matters: the first few layers keep a dense FFN (MoE routing is unstable in the earliest layers, where representations are still raw), and the remainder are MoE. A single layer-index check captures this.
class ModernBlock(nn.Module): def __init__(self, cfg, layer_idx): super().__init__() self.norm1 = RMSNorm(cfg.d_model) self.attn = MLA(cfg.d_model, cfg.n_heads, cfg.d_head, cfg.d_latent) self.norm2 = RMSNorm(cfg.d_model) if layer_idx < cfg.n_dense: # first few layers: dense FFN self.ffn = SwiGLU(cfg.d_model, cfg.hidden) else: # the rest: Mixture-of-Experts self.ffn = MoE(cfg.d_model, cfg.moe_hidden, cfg.n_experts, cfg.n_active, cfg.n_shared)
def forward(self, x): x = x + self.attn(self.norm1(x)) # MLA, pre-norm + residual x = x + self.ffn(self.norm2(x)) # MoE (or dense), pre-norm + residual return xPython — model.py: the frontier decoder block (MLA + MoE)
Place this block next to the one in Chapter 8 and the diff is exactly two lines — the attention and FFN classes. Everything Part III established about the block (pre-norm, RMSNorm, the residual stream) is untouched. The innovations live inside the two sublayers, precisely as promised.
16.2 The Complete Model
Section titled “16.2 The Complete Model”Stacking the blocks into a full model reuses the assembly of Chapter 10 verbatim — embed, run the blocks, normalize, project to logits — because the model’s outer shape never changed. (RoPE is applied inside MLA, threading the precomputed frequencies as in Chapter 10; omitted here for brevity. The optional MTP modules of Chapter 13 attach after the final block.)
class FrontierLM(nn.Module): def __init__(self, cfg): super().__init__() self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) self.blocks = nn.ModuleList( ModernBlock(cfg, i) for i in range(cfg.n_layer)) self.norm = RMSNorm(cfg.d_model) self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
def forward(self, idx, targets=None): x = self.tok_emb(idx) for block in self.blocks: x = block(x) # MLA + MoE blocks logits = self.lm_head(self.norm(x)) loss = None if targets is not None: loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1)) return logits, lossPython — model.py: the assembled DeepSeek-style model
Figure 16.1 shows the assembled architecture with DeepSeek-V3’s dense-then-MoE layer structure and the attached MTP module.
flowchart BT
A["token ids"] --> B["token embedding"]
B --> C["<b>3 × dense block</b><br/>MLA + SwiGLU FFN"]
C --> D["<b>58 × MoE block</b><br/>MLA + Mixture-of-Experts<br/>(256 experts, 8 active, +1 shared)"]
D --> E["final RMSNorm"]
E --> F["LM head"]
F --> G["logits"]
E -.-> M["MTP module<br/>(training / speculation)"]
style M stroke-dasharray: 4 4
Figure 16.1. The DeepSeek-V3 architecture. The first three blocks use a dense feed-forward network; the remaining 58 are MoE. Every block uses MLA for attention. A multi-token-prediction module attaches near the output for training and speculative decoding.
16.3 DeepSeek-V3 by the Numbers
Section titled “16.3 DeepSeek-V3 by the Numbers”An architecture becomes concrete in its configuration file. Table 16.1 lists DeepSeek-V3’s actual hyperparameters — the values you would find in its config.json — and they map directly onto the cfg fields in the code above. This is the spec sheet of a frontier open model.
| Parameter | Value | Parameter | Value |
|---|---|---|---|
| Layers | 61 | Routed experts | 256 |
| Hidden dim | 7,168 | Active experts | 8 |
| Attention heads | 128 | Shared experts | 1 |
| MLA KV latent | 512 | Expert hidden | 2,048 |
| MLA query latent | 1,536 | Dense FFN hidden | 18,432 |
| Dense layers (first) | 3 | Vocabulary | ~129,000 |
| Total parameters | 671B | Context length | 128K |
| Active per token | 37B | Train precision | FP8 |
Table 16.1 — DeepSeek-V3 configuration
Values reflect DeepSeek-V3’s released configuration. Note the ratio that defines it: 671B total but only 37B active — and a 512-dimensional MLA latent standing in for what would otherwise be thousands of cached key/value dimensions per token.
16.4 From Baseline GPT to Frontier Model
Section titled “16.4 From Baseline GPT to Frontier Model”We can now state precisely what separates the GPT we built in Chapter 10 from a frontier model. Table 16.2 is the complete diff — and it is short. The outer model, the block structure, the training loop, the tokenizer, and the data pipeline are all unchanged. Five targeted substitutions, each built in its own chapter, do the entire job.
| Component | Chapter 10 GPT | Frontier (DeepSeek-style) | Built in |
|---|---|---|---|
| Attention | MHA, full KV cache | MLA, compressed latent cache | Ch 12 |
| Feed-forward | dense SwiGLU | fine-grained MoE + shared expert | Ch 11 |
| Objective | next-token only | + multi-token prediction | Ch 13 |
| Long context | dense attention | sparse attention (DSA) | Ch 14 |
| Precision | BF16 | FP8 | Ch 18 |
| Block / model shape | unchanged — pre-norm RMSNorm block, residual stream, embed→blocks→head (spans both columns) | Ch 8, 10 |
Table 16.2 — What changed from the Chapter 10 GPT to a frontier architecture
Code reference — deepseek-ai/DeepSeek-V3 (inference/model.py: class Transformer; config.json)
DeepSeek-V3’s Transformer class is the production form of FrontierLM — assembling MLA, the dense-then-MoE block schedule, MTP, and weight tying — and config.json holds the exact values of Table 16.1. With this chapter’s code in hand, that file reads as a direct elaboration of what you have built.
Part IV complete You can now read the architecture of any current open model and, more importantly, build one: a DeepSeek-style model is the Chapter 10 GPT with MLA, MoE, and MTP dropped into a block whose shape never changed. The remaining parts of the book make this architecture trainable at scale (Part V), aligned and useful (Part VI), and efficiently served and honestly evaluated (Part VII), before you assemble your own in the final capstone.
The model is designed. Now it must be trained — and training a 671-billion-parameter model in FP8 across thousands of GPUs is its own discipline, full of its own hard-won engineering. That is the subject of Part V, beginning with the pretraining loop at scale.
16.5 Worked Example: Counting the Parameters
Section titled “16.5 Worked Example: Counting the Parameters”With the full model assembled, a revealing exercise is to ask where its parameters actually live — the accounting explains both the memory footprint and why mixture-of-experts models report such large totals. The budget breaks into four buckets:
| Component | Scales with | Share of total |
|---|---|---|
| Token embeddings | vocab × d_model | small but non-trivial |
| Attention (MLA) blocks | layers × d_model² | modest |
| MoE expert FFNs | layers × experts × d_model | the vast majority |
| Output (LM) head | vocab × d_model | small (often tied) |
Table 16.3 — Where the parameters live in an assembled MoE model
The dominant term, by a wide margin, is the expert feed-forward networks: with hundreds of experts per layer, they hold the overwhelming share of the 671 billion parameters in a model like DeepSeek-V3. This is precisely why the active-versus-total distinction of Section 45.6 exists — the experts are where the capacity sits, and routing means only a handful of them run per token. The embeddings and output head, often tied to share one weight matrix, are comparatively small but grow with vocabulary size, which is one reason tokenizer design (Chapter 5) is not free. Running this count on your own configuration turns an abstract architecture into a concrete memory budget — the first number you need before training or serving anything.
The experts are the model’s mass In a mixture-of-experts model the expert FFNs hold almost all the parameters, which is why total parameter counts are huge while active counts stay small. Embeddings and a tied output head are minor by comparison — the capacity lives in the experts.
16.6 The Configuration File as Architecture
Section titled “16.6 The Configuration File as Architecture”A striking feature of modern model code is that the architecture is defined not in the code but in a configuration — a few dozen numbers that fully specify the model, read by generic code that builds whatever they describe. The entire structure assembled in this chapter reduces to a dictionary like this:
config = { "hidden_size": 6144, "num_layers": 78, "num_attention_heads": 48, "vocab_size": 154880, "num_experts": 256, "experts_per_token": 8, "kv_lora_rank": 512, "first_k_dense": 3,} # these numbers fully specify the model (Chapter 44)Python — model/config.py: the architecture as data (cf. GLM-5.2)
Every one of these numbers is a lever pulled in an earlier chapter. num_experts and experts_per_token set the mixture-of-experts capacity and sparsity (Chapter 11); kv_lora_rank sizes the MLA latent and thus the KV cache (Chapter 12); first_k_dense chooses how many early layers stay dense (Section 44.8); vocab_size drives the embedding and output head (Section 16.5). The code that consumes the config is deliberately generic — it builds a transformer to whatever specification it is handed — so the config is the architecture, its DNA in a few dozen integers. This is why reading a frontier model’s released configuration (as Chapter 44 does for GLM-5.2) tells you almost everything about its design, and why architectural experimentation is often a matter of changing numbers in a file rather than rewriting code.
The architecture is a few dozen numbers Generic code builds whatever the config describes, so the model’s design lives in a dictionary of integers — experts, layers, latent rank, vocab. Read the config and you have read the architecture; change a number and you have changed the model.
16.7 Tied Embeddings
Section titled “16.7 Tied Embeddings”The assembled model has two large matrices that look suspiciously similar in shape: the input embedding, which maps each token id to a vector (vocabulary × hidden), and the output projection, which maps the final hidden vector to logits over the vocabulary (hidden × vocabulary). A common and effective trick is to tie them — use the same matrix for both, transposed — rather than learning two separate ones.
The motivation is partly economy and partly principle. On economy: the embedding and output matrices are among the largest in the model, especially for a big vocabulary (Section 16.5), so sharing one matrix instead of two can remove a substantial slice of the parameter count — which matters most for smaller models, where the embeddings are a large fraction of the total. On principle: the input representation of a token and the output representation that predicts it are naturally related — the geometry that makes two tokens similar as inputs tends to make them similar as predictions — so tying the matrices bakes in a sensible inductive bias and often improves quality rather than merely saving space. Whether to tie depends on the model: very large models with huge hidden dimensions sometimes benefit from untied embeddings that can specialize the two roles, but for a great many models tied embeddings are a simple, near-free improvement. It is one more illustration of the theme running through this chapter — that thoughtful parameter sharing, like the shared expert (Section 11.7) or the reused MTP heads (Section 13.5), is a recurring source of efficiency in these architectures.
One matrix for input and output Tying the input embedding and output projection shares one large matrix instead of two, saving parameters and encoding the sensible bias that a token’s input and output representations are related. Often a near-free quality gain, especially for smaller models.