Small Language Model Design

Michael BrenndoerferDecember 1, 202631 min read

Count decoder parameters, size KV caches, and allocate training data to fit small language models to real memory and latency budgets.

Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 327Small Language Model Design
Reading the full chapter · 11 sections · 31 min11 sections · 31 min

All 11 sections · 31 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Small Language Model Design

Suppose you need a product-manual assistant to run on a laptop with 4 GB available. Two model files might take up the same space on disk, yet use different amounts of memory once they start generating. One might use a larger vocabulary that shortens the manual passages. The other might allocate fewer key and value heads so those passages take up less cache. You need to account for both before testing task quality.

We'll count the parameters in a decoder in Python, then change its architecture and see where the savings come from. At the end we'll use a separate set of deployment candidates to estimate memory and compare what the hardware budget tells us with what still needs a task or device test. The later chapters in this part take up device optimization, personalization, routing, and evaluation. The transformer block chapter reviews the components we'll count.

What Counts as Small

In the deployment example we'll call 0.5B to 7B parameters small. The application sets the actual boundary. In decimal units, 7B weights at two bytes each require 14 GB before caches and working memory. At an ideal four bits per weight the same count needs 3.5 GB. A 13B model at that ideal packing would need 6.5 GB for weights. These are storage calculations. Quantization groups, metadata, and tensors retained at higher precision can raise the realized memory requirement. See INT4 Quantization for examples of those formats.

Write down the constraints before ranking candidates:

  • Memory. Budget for weights, cache at peak context and concurrency, activations, and process overhead. A model file that fits may still exceed the available working set.
  • Latency. Set a first-token and full-response target on the intended hardware. Loading weights, processing the prompt, and generating the answer make different contributions.
  • Task coverage. List what must work locally and what can be retrieved, sent to another model, or declined. Include the application's language and document slices.
  • Training. If you intend to train or adapt the model, budget for hardware, training tokens, and each training stage separately from inference.

The weight estimate can help rule out a candidate before testing. If the process limit is 4 GB and you model 0.6 GB of non-weight overhead, there is at most 3.4 GB for weights and the KV cache together. A 3.5 GB weight payload plus the fixed reserve totals 4.10 GB, exceeding the budget with zero KV cache. Conversely, a 2 GB file could be a candidate if its actual resident weights, cache, and largest temporary allocations fit at the same time. Compare the peak during prompt ingest and generation separately, since the largest activation allocation and the largest cache need not occur at the same point.

The constraint also determines what counts as the same experiment. A performance measurement at 512 cached tokens can describe a useful short-request slice. A requirement to summarize a long manual section calls for a measurement at the corresponding prompt length. Similarly, a batch serving one user and a batch serving eight requests can share some weight reads while accumulating different cache footprints. Record these settings alongside the parameter count whenever you compare devices or runtimes.

Evaluate the deployment constraint

Compare the smallest candidates that can serve the application under its memory and latency budgets. Decide how much model quality you can give up using the task's evaluation set.

The Parameter Budget

The following accountant models a bias-free decoder with a SwiGLU feed-forward network and two RMS scale vectors in each block. It omits the final normalization and assumes there are no separate learned position embeddings. Under those assumptions, the token matrices grow with vocabulary size and hidden width, while the block weights grow with layer count. An embedding table at fixed vocabulary and width takes an increasing fraction of the total as you remove layers.

Counting Parameters per Component

For the full-attention case, suppose all query, key, and value heads have the same width, with their concatenated width equal to the model's hidden width. The model then spends its counted parameters as follows:

  • Token embedding table. The VV token rows each have width dd, for VdVd weights.
  • Attention. Query, key, value, and output each use a d×dd \times d projection, for 4d24d^2 weights per layer.
  • Gated FFN. The two input projections and one output projection use 3ddff3d d_{\mathrm{ff}} weights per layer. The code sets dff=⌊8d/3⌋d_{\mathrm{ff}}=\lfloor 8d/3\rfloor unless you supply a different size.
  • Output head. An untied output projection adds dVdV weights. A tied head uses the token embedding table transposed for projection to logits.
  • Block normalization. Two vectors of length dd add 2d2d parameters per layer.

With tied embeddings, the following approximation makes the layer and vocabulary terms easy to compare. It drops the small normalization term and ignores rounding the FFN width to an integer:

P=Vd+L(4d2+3ddff+2d)≈Vd+12Ld2.\begin{aligned} P &= Vd + L\left(4d^2 + 3d d_{\mathrm{ff}} + 2d\right) \\ &\approx Vd + 12 Ld^2. \end{aligned}

where:

  • PP is the counted parameter total.
  • VV is the vocabulary size, and dd is the hidden width.
  • LL is the number of blocks.
  • dffd_{\mathrm{ff}} is the intermediate width in each SwiGLU block.

The approximate block term grows quadratically with width at fixed LL, linearly with layer count at fixed dd, and cubically with width if you fix d/Ld/L while scaling both. The embedding term grows linearly with width at fixed VV. Check the actual block design before applying the formula: untied embeddings, grouped-query attention, or a different FFN multiplier change the total.

Why the Embedding Table Matters More at Small Scale

Take a 128,000-token vocabulary. With width 8,192, the table has 1,048,576,000 parameters, about 1.5% of a hypothetical 70B total. With width 2,048, the table has 262,144,000 parameters, about 26% of a hypothetical 1B total. The smaller table is cheaper in absolute terms and takes a larger share of the model.

Reducing a tied vocabulary from 128K to 32K at width 2,048 saves 196.608M weights. Each extra full-attention layer at that width costs about 50.33M under this accountant, so the saved weights could buy three whole layers. Which change helps depends on what strings the tokenizer sees and what functions the model needs to learn. A smaller vocabulary may require more tokens for some inputs, consuming more of the context and cache.

Here is the parameter accountant. The first fixtures use tied embeddings and full attention. Specify head counts when you get to the GQA example.

PythonIn [3]
CollapseExpand
def count_parameters(
    vocab_size,
    d_model,
    n_layers,
    d_ff=None,
    tie_embeddings=True,
    n_heads=1,
    n_kv_heads=None,
):
    """Count the specified projections and two RMS scale vectors per layer."""
    if d_ff is None:
        d_ff = 8 * d_model // 3
    if n_kv_heads is None:
        n_kv_heads = n_heads
    if d_model % n_heads or n_heads % n_kv_heads:
        raise ValueError("Head widths and query groups must be integral")
    d_head = d_model // n_heads
    embeddings = vocab_size * d_model
    output_head = 0 if tie_embeddings else embeddings
    attention = n_layers * (2 * d_model**2 + 2 * d_model * n_kv_heads * d_head)
    ffn = n_layers * 3 * d_model * d_ff
    norms = n_layers * 2 * d_model
    return {
        "embeddings": embeddings,
        "head (extra)": output_head,
        "attention": attention,
        "ffn": ffn,
        "norms": norms,
        "total": embeddings + output_head + attention + ffn + norms,
    }


configs = {
    "32K / 1024 / 24": dict(vocab_size=32_000, d_model=1024, n_layers=24),
    "32K / 2048 / 16": dict(vocab_size=32_000, d_model=2048, n_layers=16),
    "128K / 2048 / 14": dict(vocab_size=128_000, d_model=2048, n_layers=14),
    "128K / 3072 / 26": dict(vocab_size=128_000, d_model=3072, n_layers=26),
    "128K / 4096 / 32": dict(vocab_size=128_000, d_model=4096, n_layers=32),
}
breakdown = {
    name: count_parameters(**config) for name, config in configs.items()
}
ConsoleOut [4]
CollapseExpand
vocab / width / layers     total  embed %   ffn %  attn %
32K / 1024 / 24            0.33B     9.8%   60.1%   30.1%
32K / 2048 / 16            0.87B     7.5%   61.6%   30.8%
128K / 2048 / 14           0.97B    27.1%   48.6%   24.3%
128K / 3072 / 26           3.34B    11.8%   58.8%   29.4%
128K / 4096 / 32           6.97B     7.5%   61.6%   30.8%

The rows at width 2,048 have different depths and parameter totals. The 16-layer, 32K-vocabulary fixture uses about 871M weights, with 7.5% in embeddings. The 14-layer, 128K-vocabulary fixture uses about 967M, with 27.1% in embeddings. The comparison shows how vocabulary and depth affect allocation under this accounting scheme.

VisualizationOut [6]
CollapseExpand
Stacked shares highlight the wide vocabulary at width 2,048.
Illustrative shares of counted parameters for the five tied, full-attention configurations. At width 2,048 the 128K-vocabulary configuration spends a larger share of its budget on embeddings than the 32K-vocabulary configuration. The normalization segment is very small at this scale.

You can use the parameter plot in two passes. The formula VdVd tells you that the embedding count at fixed vocabulary and width is independent of depth. The two rows at width 2,048 change the vocabulary and depth together. At that width the 128K table has exactly four times as many parameters as the 32K table. Their embedding shares differ by about 3.6 times because each share divides its table size by a different total, which includes both the token table and the blocks. Second, compare the 128K rows across widths. Their token tables grow with width, while the attention and FFN projections also grow within each layer. This is why the widest 128K row assigns a smaller fraction to embeddings than the narrowest 128K row, despite using a larger absolute token table.

When you use the accountant on another architecture, work from the shapes of the saved tensors. For example, if you see a combined input projection of a SwiGLU block, count its two intermediate-width slices along with the contraction back to model width. If token embeddings and output weights appear under different names, check whether the implementation shares storage and training parameters before counting a second copy. The same parameter graph can be serialized in different ways, so these checks distinguish trainable weights from the bytes in a particular exported file.

Capacity Allocation: Depth, Width, and Ratio

To compare a deeper model with a wider model, first choose what you want to hold fixed. A fixed parameter budget is useful for comparing model files. A fixed cache budget is useful when context and concurrency matter. These budgets constrain different combinations of depth, width, and head count, so an architecture that fits the first may exceed the second.

MobileLLM studies this trade-off below a billion parameters. Its authors compare depth and width and build models using deep-and-thin layouts, shared embeddings, and grouped-query attention. They also study sharing a block's weights across adjacent steps without increasing the parameter count. The block still runs at each step, so this strategy saves stored weights while retaining those sequential operations. It is a candidate to measure when parameter memory is scarce.

Use the accountant to propose configurations before training:

  • Depth and width. Compare 24 layers at width 1,024 with 12 at width 1,536, holding the tied vocabulary at 32K. The first has about 335M counted weights, while the second has about 389M. They illustrate why comparing layer counts alone can confound the shape change with a change in total size.
  • FFN width. At fixed layer count and hidden width, lowering the intermediate width by 1,024 saves three times 1,024 times the hidden width per layer. Reallocate some of the savings to depth if that is the hypothesis you want to test. Both candidates need to be evaluated on the same held-out tasks.
  • Head counts. For a cache-limited deployment, use the target maximum context when checking whether either candidate fits. Adding layers grows the cache with each additional layer. The number of KV heads and their widths can change the cost per layer.

There are two useful matched comparisons here. To study representation on a fixed task, choose shapes with similar stored parameter counts and keep the tokenizer, training data, and exposures fixed. To study deployment, select shapes that all fit the real device and compare them at the same context, batch size, and output length. Similar file sizes do not by themselves imply similar times to first token or decode rates. Measuring both comparisons helps identify which part of the budget is responsible for the difference.

Use the deployment budget as a separate constraint

The Chinchilla study estimates how model size and training tokens should change together under a fixed training-compute budget. A deployment comparison also needs device memory, latency, and task results. The scaling-law chapter covers the original training objective.

Allocating Training Data at Small Scale

A tokenizer and a training mixture spend the same training budget in different ways. Count token exposures first. If a 250B-token corpus is traversed four times without any change to the samples, the run sees 1T token exposures regardless of the parameter count. The number of exposures can also be held fixed while you change the mixture or collect more unique documents. State which of those changes you are making before comparing runs.

Muennighoff et al. report negligible changes to loss for up to four epochs of repeated data compared with unique data at fixed compute in their experiments. Returns fell as they increased repetition further. Use the result to motivate an experiment with repetition, since the usable number of repeats depends on the corpus, compute budget, and target metric. See Data-Constrained Scaling for details.

Three dataset decisions matter when you allocate the exposures:

  • Deduplication. Near duplicates can concentrate training on the same patterns and can contaminate evaluation if copies cross splits. Lee et al. report that models trained on deduplicated corpora emit memorized text less often in their setup. Check train/evaluation overlap as well as duplication within training.
  • Domain curation. Textbooks Are All You Need reports pass@1 of 50.6% on HumanEval and 55.5% on MBPP for the 1.3B-parameter phi-1, trained for code using filtered and synthetic material. These scores describe two code benchmarks. Compare filters on your own task slices and examine which inputs each filter drops. Quality Filtering gives examples of controls you can tune.
  • Mixtures and stages. SmolLM2 reports training its 1.7B model on approximately 11T tokens, adjusting a mixture that includes web, math, and code data across stages. Keep a record of the sources, exposure counts, and change points in your own mixture so you can reproduce a gain or trace a regression.

Knowledge distillation gives you a further option when a teacher can generate labels for the target task. Check the generated labels against originals and validated answers. For example, if you teach a student to answer from passages, set aside examples where the teacher could produce a plausible answer from prior knowledge despite having no evidence in the passage. The student can otherwise learn the teacher's failure along with the desired behavior. The experiments on recursive training studied generation after generation of training on model outputs. Keeping original data and auditing synthetic labels are distinct choices from replacing the data recursively.

One way to make a data experiment interpretable is to fix the tokenizer, total token exposures, and model configuration, then change a single mixture rule. Compare manual-answer accuracy, code benchmarks, and general text loss separately if those are goals. A curated run can improve one metric while losing coverage on another slice. If you also change the tokenizer, log the exposures after tokenization so the nominal corpus size in documents does not disguise a change in training tokens.

Instruction examples belong to the training stage they actually enter. A task-formatted example in continued pretraining and the same example in supervised fine-tuning may use different loss masks and mixture weights. Keep development and test questions outside that loop, including paraphrases or copied manual passages when they reveal the answers. It is much easier to compare a candidate when the evaluation protocol identifies which questions it saw, which it only sees during deployment, and which documents retrieval is allowed to return.

Architecture Choices That Buy Budget

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.

Capability Boundaries Below Frontier Scale

The parameter and cache calculations tell you which configurations can enter a deployment test. The task evaluation tells you what to delegate to each of them, because the same model can succeed on a short extraction and fail on a request that requires combining several passages.

What Small Models Do Well

Start with tasks that offer a clear success condition:

  • Narrow instructions. Classification, extraction, and rewriting give you defined classes or expected edits. Count errors on rare labels and on requests the model should decline.
  • Answers grounded in short passages. Ask for a reply and the span that supports it. Measure retrieval separately by checking how often the needed passages are supplied.
  • Structured outputs and tool calls. A decoder constrained to a supported JSON grammar can enforce syntax. Tests for field values, permitted actions, and permissions still matter. A syntactically valid reply can cite the wrong passage or pass the wrong ID.
  • Domain specialization. A narrow dataset can target the phrasing, schema, and terminology of a single task. Use held-out requests from that domain, including variants in user phrasing.
  • Local workloads. If a model stays on the device, an application can process requests without sending them to a remote inference server. Check the whole request path, including retrieval, logs, and any escalation, against that privacy requirement.

A format check narrows the set of valid outputs, which can make a small model easier to deploy. Where a classifier must return one of ten labels, constrain the output to those labels and measure which it picks. An application that grades every recognized label as correct will miss the behavior that matters.

What Small Models Fake or Fail

A fluent reply can hide an error. Include tests with evidence of the error that a grader or a program can inspect:

  • Several dependent steps. Use problems with verifiable intermediate states or final outputs. A polished rationale alone is insufficient evidence of the correct derivation. See Reasoning Limitations.
  • Knowledge outside the training or retrieval scope. Check how the model behaves when the supporting passage is absent. Retrieval can supply facts, and the application still has to detect missing or conflicting evidence.
  • Long-context synthesis. Test gathering evidence across positions and integrating conflicting passages separately from retrieving one marked item. The configured window specifies what fits, while the synthesis evaluation measures what the model uses.
  • Multilingual text, code, and unusual symbols. Compare tokenizer lengths, truncation, and model errors across slices of real input.
  • Unexpected input and proposed actions. Test unknown queries, unsupported requests, and unavailable tools. Record wrong answers, false escalation, and the cases where the system correctly requests clarification.

Measure each failure mode under the same quantization, decoding, and context settings you plan to deploy. If switching to the local model increases failures on one slice, make that slice a candidate for a better evidence path or explicit escalation.

Sub-Capabilities and the "Buy vs. Route" Decision

Make a choice for each capability the product needs:

  1. Buy it in-size. Allocate model weights and training data to the task, then measure it with the deployed model.
  2. Borrow it from a teacher. Use teacher outputs as training examples where you can audit the signal or verify answers.
  3. Route it out. Escalate to a larger model or a person when the latency, privacy, and cost budgets allow.
  4. Ground it with retrieval. Supply external evidence at inference when the user needs facts that can be looked up.

These choices combine. The assistant below can retrieve manuals, constrain a local model to the response schema, and escalate requests with insufficient evidence. A larger model is another candidate in that system. Its availability does not make an unsupported answer correct.

Worked Example: Choosing a Configuration for a Deployed Assistant

Suppose you are building an English customer-support assistant for a single product. It needs to run on a laptop with 4 GB available to the process, retrieve from a few thousand manual passages, and produce a JSON reply with response and followup_question fields. For an interactive chat interface, you will measure time to the first token as well as time to the full response.

We use three illustrative candidates, each with one 4,096-token sequence, fp16 KV cache, and ideally packed 4-bit weights. The example reserves 0.6 GB for other costs such as quantization metadata, activations, tokenizer, and runtime. This fixed reserve is an assumption. An actual format and runtime need their own memory measurements. The candidates' parameter counts and head settings are independent fixtures for deployment, rather than rounded aliases for the earlier architecture examples.

PythonIn [10]
CollapseExpand
candidates = [
    dict(
        name="0.5B q4",
        params=500_000_000,
        n_layers=24,
        n_kv_heads=8,
        d_head=128,
    ),
    dict(
        name="3B q4",
        params=3_000_000_000,
        n_layers=26,
        n_kv_heads=8,
        d_head=128,
    ),
    dict(
        name="7B q4",
        params=7_000_000_000,
        n_layers=32,
        n_kv_heads=8,
        d_head=128,
    ),
]
deployment_context_tokens = 4096
device_budget_gb = 4.0


def deployed_memory_gb(
    params,
    n_layers,
    n_kv_heads,
    d_head,
    context=deployment_context_tokens,
    bits=4,
    overhead=0.6,
):
    weights_gb = params * bits / 8 / 1e9
    kv_gb = kv_cache_bytes(context, n_layers, n_kv_heads, d_head) / 1e9
    return {
        "weights": weights_gb,
        "kv_cache": kv_gb,
        "overhead": overhead,
        "total": weights_gb + kv_gb + overhead,
    }


budgets = {
    candidate["name"]: deployed_memory_gb(
        **{key: value for key, value in candidate.items() if key != "name"}
    )
    for candidate in candidates
}
ConsoleOut [11]
CollapseExpand
candidate    weights   KV cache   reserve    total   fits?
0.5B q4       0.25G      0.40G     0.60G    1.25G     yes
3B q4         1.50G      0.44G     0.60G    2.54G     yes
7B q4         3.50G      0.54G     0.60G    4.64G      no

At 4,096 tokens the 0.5B and 3B fixtures use about 1.25 and 2.54 GB respectively. The 7B fixture uses about 4.64 GB. Its ideally packed weights and assumed reserve already total 4.10 GB, so reducing only its context or KV head count cannot make it fit under these assumptions.

The figure uses the same memory calculation to show how much each component contributes and how far each candidate is from the device limit.

VisualizationOut [13]
CollapseExpand
Stacked memory bars for three candidates against a 4 GB limit line.
Calculated working memory for one 4,096-token session with ideally packed 4-bit weights, an fp16 cache, and a fixed reserve. The 7B configuration exceeds 4 GB.

Run the two candidates that fit on the same set of product questions. Keep retrieval results and the constrained decoder fixed as you measure supported answers, correct abstention, and valid field contents. Compare the 0.5B and 3B models on examples that need facts from more than one passage as well as single-passage lookup. The memory estimate leaves both in contention. Select the smaller candidate if it meets the defined quality and latency targets.

For the manual assistant, collect cases spanning one short source sentence, several nearby sentences, and passages from separate sections. Have a held-out set where a question cannot be answered from retrieval. Check whether the retrieved text contains the exact fact needed, whether the response obeys the schema, whether the answer is supported, and whether the escalation is correct. These checks distinguish a missing document from a retrieval ranking miss and from a generation error.

Define the behavior when the manual and the user's wording disagree. If a request asks how to use a feature unavailable in the current version, the expected response might identify the version mismatch and ask a follow-up. Record it as an example of correct refusal to provide instructions for that version even when the reply is fluent and schema-valid. Use the same behavior contract for both model candidates, and include that path when measuring end-to-end latency.

You can estimate one part of decode latency before measuring hardware. Suppose every generated token requires reading the stored weights and the whole KV cache once from memory, and the effective bandwidth is 200 GB/s. Divide the modeled traffic by that bandwidth. This scenario assumes one sequence at a 4,096-token cache, just like the memory check.

PythonIn [14]
CollapseExpand
def decode_ms_per_token(amounts, bandwidth_gbs=200):
    """Convert the modeled weights and cache traffic to milliseconds."""
    return 1000 * (amounts["weights"] + amounts["kv_cache"]) / bandwidth_gbs
ConsoleOut [15]
CollapseExpand
0.5B q4: 3.26 ms/token (306 tokens/s in the traffic model)
3B q4: 9.68 ms/token (103 tokens/s in the traffic model)
7B q4: 20.18 ms/token (50 tokens/s in the traffic model)

The calculation gives about 3.26, 9.68, and 20.18 ms per token for the three candidates. These rates describe that traffic assumption, with no allowance for compute, kernel launches, or retrieval. Cache reuse, batch execution, and the attention implementation can also change the traffic itself. Measure actual peak memory and both first-token and full-response latency on the intended device. Even at a measured 30 tokens/s, a 60-token decode takes two seconds before accounting for time spent retrieving passages and processing the prompt.

Limitations of the Small-Model Approach

A good result on the product-manual test supports a deployment choice for those questions. Three changes can invalidate the choice:

  1. The knowledge base changes. A new product and its terminology may move the request away from training and from the retriever's index. Track grounding and answerable coverage after an update. Keep an escalation path for requests without evidence.
  2. Tasks require different steps. A model that extracts the warranty period from one paragraph may need to compare several passages to handle exceptions. Measure the dependency lengths and evidence positions in the actual workload, and consider a verifier for outputs with consequences.
  3. Curation becomes harder to repeat. A revised mixture can depend on data rights, access to a teacher, and the cost of human verification. Document source versions so you can reproduce the training set and separate gains due to a changed model from gains due to changed data.

Local execution can reduce network round trips and keep inference requests on the device. The total benefit depends on the whole application, including where retrieval happens and how often requests are escalated. If local handling is mandatory, count abstentions and timeouts in your task evaluation rather than filtering out the cases the model cannot complete.

Measure on the busiest supported workload

Check peak memory at target context and concurrency, record task quality and latency on the intended device, and decide how the application handles answers it cannot verify.

Summary

  • Count embeddings, the output head, attention, FFNs, and normalization using the architecture you intend to train. At fixed width, tying and trimming a vocabulary save different copies or rows of the token matrix.
  • Compare depth and width under a named budget. Track unique data, exposures, and training stages separately when testing curation and repetition.
  • Use the number of key-value heads and the peak context to size the cache. Combine that cost with actual quantized weights and process working memory.
  • Use memory and latency estimates to choose which candidates to test. Verify task quality, retrieval, schema fields, and escalation before deciding which candidate serves the workload.

The next chapter maps these budgets to hardware. The later chapters look at adapting a model to a device or user, routing requests to other models, and testing the resulting system.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about small language model design, parameter budgeting, and deployment memory estimation.

Small Language Model Design

Question 1 of 80 of 8 completed
Using the chapter's approximate tied-embedding formula, which term grows quadratically with hidden width at fixed layer count?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 14

On-Device Adaptation and Personalization

Build a private personalization loop with local retrieval and LoRA adapters on a frozen base model. Learn update budgets, gates, and safe deletion.

29 min read
Language AI Handbook · Vol. 14

Hybrid Edge-Cloud Inference

Design hybrid edge-cloud inference with routing, partitioning, and fallback. Learn latency accounting, privacy gates, and cost control for LLM apps.

42 min read
Language AI Handbook · Vol. 14

Hardware-Aware Model Optimization

Optimize LLM inference for phones, browsers, and edge devices using memory bandwidth, roofline analysis, quantization formats, and kernel co-design.

35 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026smalllanguage, author = {Michael Brenndoerfer}, title = {Small Language Model Design}, year = {2026}, url = {https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Small Language Model Design. Retrieved from https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment
MLAAcademic
Michael Brenndoerfer. "Small Language Model Design." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment>.
CHICAGOAcademic
Michael Brenndoerfer. "Small Language Model Design." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Small Language Model Design'. Available at: https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Small Language Model Design. https://mbrenndoerfer.com/writing/small-language-model-design-parameter-budget-deployment
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy