Small Language Model Design › Architecture Choices That Buy Budget

Michael BrenndoerferDecember 1, 20266 min read
Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 327Small Language Model Design › Architecture Choices That Buy Budget
Reading section 6 of 11 · Architecture Choices That Buy Budget · 6 minSection 6 of 11 · 6 min

Section 6 of 11 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The full-attention accountant gives you a starting point. Now we can estimate how three changes affect it. Grouped-query attention saves projection weights and cache entries. Tying saves a token matrix. Changing the vocabulary can change the number of tokens in a given input.

Grouped-Query Attention

In grouped-query attention, several query heads share each key-value head. The key and value projections together shrink in proportion to nkv/nhn_{\mathrm{kv}}/n_h, while the query and output projections remain full width. With fixed query width dd and head width dhead=d/nhd_{\mathrm{head}}=d/n_h, the total attention projection count per layer is (2+2nkv/nh)d2(2 + 2n_{\mathrm{kv}}/n_h)d^2. Under multi-head attention, nkv=nhn_{\mathrm{kv}}=n_h recovers 4d24d^2.

Each cached token stores a key and a value for each KV head at each layer. For a batch of sequences with equal cached lengths and no sharing of cached prefixes, the total size in bytes is:

C=2BTLnkvdheads.C = 2 B T L n_{\mathrm{kv}} d_{\mathrm{head}} s.

where:

  • CC is the KV cache payload in bytes.
  • BB is the batch size, and TT is the number of cached tokens per sequence.
  • LL is the number of layers, each with its own cached keys and values.
  • nkvn_{\mathrm{kv}} is the number of key-value heads, and dheadd_{\mathrm{head}} is their width.
  • ss is the bytes per cache value, equal to 2 in fp16. The leading factor of 2 counts keys and values separately.

One 1,000-token sequence in a 24-layer model with 32 KV heads of width 96 uses about 295 MB at fp16. With four KV heads it uses about 37 MB. In a 26-layer model with all other settings fixed, the corresponding values are about 319.5 MB and 39.9 MB. The footprint grows with the number of retained positions. GQA reduces the number of independent projections, so the query heads can still attend to the same set of positions but see keys and values shared within groups.

The GQA paper studies uptraining multi-head checkpoints and reports that its grouped-query variants approach multi-head quality with inference speed comparable to multi-query attention in its experiments. Matching the head settings by formula is enough for a byte calculation. Accuracy and throughput on your device require separate tests. The KV cache chapter gives further memory examples.

Weight Tying

Tying saves one matrix of size VdVd when the input row and output logit for each token can use the same learned vector. In training, the contributions from input use and output use accumulate on that shared parameter. The two contributions can differ in magnitude and direction. Press and Wolf reported lower validation and test perplexity with tying for their large Penn Treebank language model, alongside a smaller parameter count. Test a separate output projection when the remaining parameter budget permits it and your task has a reason to benefit from a different projection.

The Vocabulary as a First-Class Decision

When comparing vocabularies, tokenize the same documents with each candidate. Measure token counts and the fraction of inputs truncated at your context limit, separately for the languages, code, and structured records the application uses. Track any fallback encoding that expands unusual strings into more tokens. The tokenizer determines both how many learned rows you need and what fraction of a document fits in the available context. Ahia et al. measure large differences in token counts for equivalent content across languages and deployed tokenizers. The tokenizer training chapter shows how to train one for your corpus.

Let's hold the width at 3,072 and the depth at 26, then apply all three changes. We compare the weight count and the FP16 cache for one sequence. The following examples share the same 32 query heads of width 96, use either 32 or four KV heads, and use the same SwiGLU rule as the earlier fixtures.

PythonIn [7]
CollapseExpand
def kv_cache_bytes(
    context_tokens, n_layers, n_kv_heads, d_head, bytes_per=2, batch_size=1
):
    """Return bytes for equal-length sequences with no shared cache entries."""
    return (
        2
        * batch_size
        * context_tokens
        * n_layers
        * n_kv_heads
        * d_head
        * bytes_per
    )


variants = {
    "MHA, 128K, untied": dict(
        vocab_size=128_000,
        d_model=3072,
        n_layers=26,
        tie_embeddings=False,
        n_heads=32,
        n_kv_heads=32,
    ),
    "GQA, 32K, tied": dict(
        vocab_size=32_000,
        d_model=3072,
        n_layers=26,
        tie_embeddings=True,
        n_heads=32,
        n_kv_heads=4,
    ),
}
params = {name: count_parameters(**config) for name, config in variants.items()}


def variant_cache_mb(config, context_tokens):
    return (
        kv_cache_bytes(
            context_tokens,
            config["n_layers"],
            config["n_kv_heads"],
            config["d_model"] // config["n_heads"],
        )
        / 1e6
    )


kv_context_tokens = 4096
ConsoleOut [8]
CollapseExpand
MHA, 128K, untied: 3.731B weights, 319.488 MB cache per 1,000 tokens
GQA, 32K, tied: 2.613B weights, 39.936 MB cache per 1,000 tokens

At width 3,072, tying the original 128K token matrices saves 393.216M weights, and trimming the tied vocabulary from 128K to 32K saves another 294.912M. GQA saves about 429.392M projection weights across 26 layers. Added together, the changes account for the roughly 1.118B-parameter difference. The cache shrinks by a factor of eight because only the KV head count changes among the terms in the cache calculation.

VisualizationOut [9]
CollapseExpand
Two panels compare 3.731 with 2.613 billion weights and 1,309 with 164 MB of KV cache.
Total counted weights and per-sequence fp16 KV cache at 4,096 tokens for two 26-layer configurations. Head sharing cuts the cache by a factor of eight; tying and vocabulary trimming further lower the parameter count.

The same calculation answers a context question. At the specified 26 layers and 32 KV heads, one 4,096-token sequence uses about 1,309 MB of cache. The four-head alternative uses about 164 MB. Doubling the stored positions or the number of equal-length sequences doubles those payloads in the formula. The head change buys a smaller payload per token, but it has no effect on how the tokenizer divides a product code into pieces. Measure the lengths separately before converting a context target such as 'two manual pages' into a number of tokens.

The model's maximum supported context and the application's memory-constrained context can differ. A runtime can also use padding, blocks, eviction, cache quantization, or shared prefixes. The payload formula is the place to start a budget; the measured process peak includes allocator behavior and whatever the runtime keeps between requests. Record the cache dtype independently of the weight dtype. A four-bit model file can have an fp16 cache, as it does throughout the deployment example.

Account for peak working memory

For deployment, include quantized weights, peak KV cache, activation workspace, and process overhead. Long prompts and concurrent sessions can shift the largest cost from model weights to the cache. Use the maximum supported workload when checking the budget.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy