Hardware-Aware Model Optimization › A Worked, Runnable Bandwidth and Format Analysis

Michael BrenndoerferDecember 1, 20264 min read
Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 328Hardware-Aware Model Optimization › A Worked, Runnable Bandwidth and Format Analysis
Reading section 7 of 11 · A Worked, Runnable Bandwidth and Format Analysis · 4 minSection 7 of 11 · 4 min

Section 7 of 11 · 4 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

This example sizes the modeled tensors in several formats, estimates two components of inference time, and leaves room to add your measured runtime allocations. The output is an accounting worksheet for a small decoder, using the given inputs in place of a device benchmark.

The hypothetical decoder has these properties:

  • 22 layers.
  • A hidden width of 2,048.
  • 16 query heads and 4 KV heads.
  • A two-projection feed-forward network of width 5,632.
  • One tied vocabulary matrix.

The arithmetic ignores biases and normalization parameters and assumes equal-width attention heads. It uses sequence lengths in tokens directly, without running a tokenizer or generating replies.

PythonIn [23]
CollapseExpand
# Assumptions for a small decoder-only model.
config = {
    "n_layers": 22,
    "d_model": 2048,
    "d_ff": 5632,
    "n_heads": 16,
    "n_kv_heads": 4,  # GQA: KV cache is n_kv_heads wide, not n_heads
    "vocab_size": 32000,
    "tie_embeddings": True,
}


def param_count(cfg):
    d = cfg["d_model"]
    d_ff = cfg["d_ff"]
    L = cfg["n_layers"]
    # Per layer: Q/K/V and output projections, then a two-projection ungated FFN.
    qkv = d * (d + 2 * cfg["n_kv_heads"] * (d // cfg["n_heads"]))
    o = d * d
    mlp = 2 * d * d_ff
    per_layer = qkv + o + mlp
    emb = cfg["vocab_size"] * d
    lm_head = 0 if cfg["tie_embeddings"] else cfg["vocab_size"] * d
    return L * per_layer + emb + lm_head


n_params = param_count(config)
ConsoleOut [24]
CollapseExpand
Model parameters: 0.80B

The modeled phone profile uses 68 GB/s of peak bandwidth and an illustrative 75% fraction. FP16 stores unscaled 16-bit values. Each integer format uses packed values plus one 32-bit scale per full group. Count the cache and other allocations separately.

PythonIn [25]
CollapseExpand
DEVICE_BW_GB = 68.0
EFF_FRACTION = 0.75


def weight_gib(n_params, bits, group_size=None):
    stored_bits = (
        bits if group_size is None else effective_bits(bits, group_size)
    )
    return n_params * stored_bits / 8 / (1024**3)


formats = {
    "FP16": (16, None),
    "INT8 g128": (8, 128),
    "INT4 g128": (4, 128),
    "INT4 g32": (4, 32),
}
sizes = {
    name: weight_gib(n_params, bits, group)
    for name, (bits, group) in formats.items()
}

Estimate raw KV payload for one sequence at several context lengths. Each layer keeps both keys and values, each with width equal to the number of KV heads times the dimension of one head. Cache quantization may also need metadata, and memory allocators may reserve extra space. The function counts the payload alone.

PythonIn [26]
CollapseExpand
def kv_cache_gib(cfg, seq_len, kv_bits=8):
    d = cfg["d_model"]
    head_dim = d // cfg["n_heads"]
    # K and V, each [n_layers, n_kv_heads, seq, head_dim]
    elems = 2 * cfg["n_layers"] * cfg["n_kv_heads"] * seq_len * head_dim
    return elems * kv_bits / 8 / (1024**3)
ConsoleOut [27]
CollapseExpand
Format         Weights GiB   Ceiling tok/s
FP16                  1.50            31.7
INT8 g128             0.77            61.5
INT4 g128             0.40           119.4
INT4 g32              0.47           101.5
KV cache @ 512 tok (INT8): 0.011 GiB
KV cache @ 2048 tok (INT8): 0.043 GiB
KV cache @ 4096 tok (INT8): 0.086 GiB

At the same assumed bandwidth, INT4 g128 has about 1.94 times the weight-only ceiling of INT8 g128. The larger group has less scale overhead than g32. The worked decoder has about 0.398 GiB of INT4 g128 weights and 88 MiB of raw eight-bit KV values at 4,096 tokens. Their combined modeled payload is about 0.484 GiB. Add runtime buffers, cache metadata, and allocator headroom before comparing against a real memory limit. KV quantization is a separate decision. Liu et al., KIVI

For prefill, estimate the arithmetic time for the transformer layers’ dense projections. Use the same nominal operation ceiling as the roofline but assume 40% arithmetic utilization. This component scales linearly with prompt length in the model. Attention’s sequence-dependent work, vocabulary logits, and device transfers lie outside the estimate.

PythonIn [28]
CollapseExpand
# Effective projection rate for the compatible arithmetic mode in the example.
projection_ops_per_second = 0.4 * phone_compute_tops


def prefill_seconds(cfg, seq):
    vocab_matrix_params = cfg["vocab_size"] * cfg["d_model"]
    vocab_matrices = 1 if cfg["tie_embeddings"] else 2
    layer_params = param_count(cfg) - vocab_matrices * vocab_matrix_params
    projection_ops = 2 * layer_params * seq
    return projection_ops / projection_ops_per_second


prefill_ms = {}
for seq in [256, 512, 1024]:
    prefill_ms[seq] = prefill_seconds(config, seq) * 1e3
ConsoleOut [29]
CollapseExpand
Dense layer projections for 256 tokens: 31.5 ms (modeled)
Dense layer projections for 512 tokens: 63.0 ms (modeled)
Dense layer projections for 1024 tokens: 126.0 ms (modeled)

Benchmark time to first token and intervals between generated tokens separately. The first includes the work before the model emits an answer token, such as tokenization and prompt processing. The second reflects the subsequent decode path and any scheduling between outputs. The projection-only timing above estimates one contributor to the first metric.

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