Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

5.1 Sparse vs Dense Models

An engineer budgets 74 GB for the weights of DeepSeek-V3 because its report says 37 billion parameters are active per token. The multiplication is right for two bytes per parameter. Why would the main model alone need about 1.34 TB at that same precision? The report gives a second number, 671 billion parameters in the main model. A different token can call on a different set of weights [3].

Follow one token through the layer

Consider the word bank at the end of “We sat on the river bank” and “For a loan, I visited the bank.” A causal decoder has already seen the words before bank when it chooses a route at that position. Earlier layers can give the token different hidden vectors in these two contexts. A dense feed-forward network (FFN) applies the same matrices to both vectors and can produce different outputs. A sparsely gated mixture of experts (MoE) also uses the vector to choose which FFNs to execute. The shared attention layer still runs.

An expert is a learned network identified by an index. The designer need not assign it a subject such as finance. Shazeer et al. used conditional computation in a recurrent language model before sparse Transformers became common [1]. In Mixtral 8x7B, each layer’s router chooses two of its eight expert FFNs for each token [2]. Across a batch, different pairs can collectively use all eight.

Calculate a top-2 route

Let xx be one token’s hidden vector, z=xWgz=xW_g the router logits, and SS the indices of the kk largest logits. In the Mixtral-style gate used here, expert ii receives weight wiw_i. The selected outputs Ei(x)E_i(x) have the same shape and are added coordinate by coordinate [2].

wi={exp⁡(zi)∑j∈Sexp⁡(zj)i∈S,0i∉S,y=∑i∈SwiEi(x).w_i=\begin{cases} \frac{\exp(z_i)}{\sum_{j\in S}\exp(z_j)} & i\in S,\\ 0 & i\notin S, \end{cases} \qquad y=\sum_{i\in S}w_iE_i(x).

Suppose the river example has logits [3, 2, 0, −1]. With k=2k=2, experts 0 and 1 receive weights about 0.731 and 0.269. If their first output coordinates are 2 and −2, the combined coordinate is about 0.924. Switch to the loan example below. The logits change, but we keep the four example coordinates fixed so you can isolate what the gate does.

Where does “bank” go?

Change the words before “bank” to change its router scores. The logits and expert outputs are illustrative values chosen for this exercise.

Context
Experts to run (k)

We sat on the river bank.

ExpertLogitWeightValue
E030.7312
E120.269-2
E200.0006 (if run)
E3-10.00010 (if run)
Weighted output coordinate (unitless)0.924

Softmax uses only the selected logits. Values marked “if run” belong to skipped experts and contribute zero. The sum uses unrounded weights.

Budget the weights before estimating latency

Suppose a model has 200 million shared weights used by every token and eight routed experts with 100 million weights each. Count the following quantities separately.

QuantityCalculationWhat it tells you
Total weights200M + 8 × 100M = 1BAll weights together occupy 2 GB at two bytes each.
Weights active for one top-2 token200M + 2 × 100M = 400MThe dense projections on that path determine much of its arithmetic.
Distinct weights used by two tokens choosing disjoint pairs200M + 4 × 100M = 600MThe shared weights count once in storage even though both tokens use them.

These are decimal GB of weights only. Budget KV cache, activations, communication buffers, allocator overhead and any quantization metadata separately. The 1.34 TB opening figure makes the same uniform two-byte assumption. The released checkpoint also includes 14B multi-token prediction parameters, which the publisher counts separately. Its actual file sizes depend on the stored precision [6]. Experts can be distributed across devices or loaded from host memory. Offloading trades device capacity for transfer time, as Eliseev and Mazur demonstrate with Mixtral [4].

For a matrix-vector multiply, one multiply-add per used weight costs about two floating-point operations. Turning an active-parameter count into a latency estimate also requires knowing how many tokens reuse each matrix, whether experts sit on different devices, and how long dispatch takes. In a 2026 preprint, Alfarizy et al. compared OLMoE and dense models with llama.cpp on an M2 Pro and a Jetson Orin Nano. Their dense Llama-3.2-1B baseline decoded faster than OLMoE on both devices, with a larger gap on the Jetson. That result covers one MoE family and those configurations. On your hardware, measure prompt processing and decoding separately, at the context lengths and concurrency you intend to serve [5].

Dispatch only the selected rows in PyTorch

CPU forward-pass example. This uses supplied logits, four small linear experts and two tokens in FP32. A full MoE block would learn the router and nonlinear FFNs. The example omits training, capacity limits and cross-device dispatch. Indexing matters here because one token can receive two contributions.

import torch
from torch import nn


def dispatch(x, logits, experts, k):
    # x: [tokens, width], logits: [tokens, experts]
    scores, choices = logits.topk(k, dim=-1)
    weights = scores.softmax(dim=-1)
    combined = torch.zeros_like(x)
    for expert_id, expert in enumerate(experts):
        token, slot = torch.where(choices == expert_id)
        if token.numel():
            values = expert(x[token])
            combined.index_add_(0, token, weights[token, slot, None] * values)
    return combined, choices, weights


# Two contextual representations of "bank", four toy expert projections.
x = torch.tensor([[1., 1.], [1., -1.]])
logits = torch.tensor([[3., 2., 0., -1.], [0., -1., 2., 3.]])
experts = nn.ModuleList(nn.Linear(2, 2, bias=False) for _ in range(4))
with torch.no_grad():
    for expert, scale in zip(experts, [2., -2., 6., 10.]):
        expert.weight.copy_(scale * torch.eye(2))
    y, choices, weights = dispatch(x, logits, experts, k=2)
    print(choices.tolist())       # [[0, 1], [3, 2]] at k=2
    torch.testing.assert_close(weights.sum(dim=1), torch.ones(2))
    print(y[:, 0].tolist())  # approximately [0.9242, 8.9242]

In torch.where, token identifies a row of the input and slot identifies a column in that row’s top-kk result. A weight belongs to a particular token and slot. index_add_ sends each weighted output back to its source row and sums contributions from different experts. Try changing k to 1 or 4 in both the widget and the function call. Which change alters the result more for the river example?

For a batch of TT tokens that each select two distinct experts without dropping any assignments, the per-expert counts must sum to 2T2T. If one expert receives all TT tokens, every token still has a second route. The busy expert can slow down its peers even when everything fits in memory. Routing algorithms examines how training changes that distribution, and expert parallelism follows the tokens across devices.

Quizzes

Quiz 1: Two tokens choose the same two experts. How many distinct weights do they use in the 1B example? They use 400M distinct weights. Both tokens still require their own outputs. A batched matrix multiplication may reuse the weights while computing both.

Quiz 2: Why does multiplying by the full softmax weights and simply dropping the other outputs change this example? The retained weights would generally sum to less than one. This gate normalizes over the selected experts, so discarding the other terms without renormalization also shrinks the output.

Quiz 3: A top-2 router sends 100 tokens to expert 0. Does that mean all other experts are idle? No. Those 100 tokens each have another distinct destination. Inspect all 200 assignments and their device placement before attributing a latency spike to one expert.

References

  1. Shazeer, N., et al. (2017). Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.
  2. Jiang, A. Q., et al. (2024). Mixtral of Experts, §2.1.
  3. DeepSeek-AI. (2024). DeepSeek-V3 Technical Report.
  4. Eliseev, A., and Mazur, D. (2023). Fast Inference of Mixture-of-Experts Language Models with Offloading.
  5. Alfarizy, A., et al. (2026). Does Mixture-of-Experts Actually Help Inference on Consumer and Edge Hardware? An Empirical Study (v3).
  6. DeepSeek-AI. DeepSeek-V3 model card, Model Downloads.