Hardware-Aware Model Optimization

Michael BrenndoerferDecember 1, 202635 min read

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

Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 328Hardware-Aware Model Optimization
Reading the full chapter · 11 sections · 35 min11 sections · 35 min

All 11 sections · 35 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Hardware-Aware Model Optimization

Memory bandwidth, kernels, quantization formats, sparsity, and co-design for phones, browsers, and edge devices.

At 16 bits per parameter, a billion parameters require two billion bytes of raw weight storage. That is 2 GB in decimal units or about 1.86 GiB in binary units. On a phone, the weights compete for memory with the application and the rest of the system. Once the model fits, a second question determines how fast it can answer. How many bytes must cross the memory bus for each generated token? When a batch-one decode repeatedly reads large weight matrices from DRAM, moving those bytes can cost more time than the multiply-adds. The examples below let you estimate that cost, then check whether quantization and a different kernel change it.

Hardware-aware optimization matches a language model to a target’s memory hierarchy, instruction set, and thermal envelope. Start with a roofline estimate to see which resource could limit the workload. Then use the actual weight layout, scale overhead, and cache size to narrow the options. The worked example uses a small decoder, and its bandwidths and operation rates are inputs to a model. Use them to check the arithmetic before replacing them with measurements from your device.

Packed four-bit weights can save bandwidth when a kernel consumes the packed representation efficiently. If the runtime expands the entire tensor before the hot loop, where the expanded tensor lives determines which traffic savings remain. The same question applies to sparse weights. Check the path that runs, including the transfers it performs.

Why Hardware, Not Just Size, Defines Feasibility

The same model can fit on several targets and still have very different response times. Available memory sets the capacity constraint. Bandwidth, compute throughput, and runtime support set separate constraints on latency. For a phone with shared DRAM, the share of bandwidth available to inference can also change with concurrent activity.

The bandwidth wall

Consider one batch-one decode step through a dense layer with a matrix of NN weights. A matrix-vector product uses NN multiply-adds. If its weights come from DRAM and each is read once, the weight traffic is the stored matrix payload. The rest of the step can also read the KV cache and write intermediate tensors.

tmemory≥Bweights+BKVBWeff.t_{\mathrm{memory}} \ge \frac{B_{\mathrm{weights}} + B_{\mathrm{KV}}}{BW_{\mathrm{eff}}}.

Here BweightsB_{\mathrm{weights}} and BKVB_{\mathrm{KV}} are the respective numbers of weight and cache bytes that cross the measured memory interface in one decode step. BWeffBW_{\mathrm{eff}} is an upper estimate of achievable bandwidth at that interface, in bytes per second. Dividing bytes by bytes per second gives seconds. This term estimates a lower bound on the time needed for those transfers. A bandwidth-limited step can run close to it when omitted transfers and overhead are small.

Name the memory interface when you estimate bandwidth. A DRAM roofline counts traffic between DRAM and the cache hierarchy. Cache hits can reduce the bytes that cross that interface. Contention and access patterns can change how many bytes per second a kernel can transfer there. In the first example, all devices use illustrative inputs and the same assumed bandwidth fraction.

PythonIn [3]
CollapseExpand
# Illustrative peak memory bandwidth values in decimal GB/s.
# These inputs are scenario assumptions, not measurements or device specifications.
devices = {
    "Phone profile A": 68.0,
    "Phone profile B": 25.0,
    "Unified-memory profile": 200.0,
    "Laptop profile": 60.0,
    "Datacenter GPU profile": 3350.0,
    "Browser profile": 40.0,
}

# Apply the same illustrative fraction to all bandwidth profiles.
effective_fraction = 0.75
ConsoleOut [4]
CollapseExpand
Device class                     Peak GB/s    Effective GB/s
Phone profile A                         68              51.0
Phone profile B                         25              18.8
Unified-memory profile                 200             150.0
Laptop profile                          60              45.0
Datacenter GPU profile                3350            2512.5
Browser profile                         40              30.0

The first comparison uses a 1.1-billion-parameter model and assumes a 4.25-bit weight payload per parameter, including metadata. The code converts that payload to GiB and converts the bandwidth from decimal GB/s to GiB/s before dividing.

PythonIn [5]
CollapseExpand
params_billion = 1.1
bits_per_weight = 4.25
weight_gib_example = (params_billion * 1e9 * bits_per_weight / 8) / (1024**3)

# Decode tok/s bound by bandwidth alone (weights only, ignore KV cache).
decode_toks_per_s = {}
for name, peak in devices.items():
    eff = peak * effective_fraction
    # Convert decimal GB/s to GiB/s, then divide by the weight footprint.
    decode_toks_per_s[name] = eff * (1e9 / (1024**3)) / weight_gib_example
ConsoleOut [6]
CollapseExpand
Approx weight footprint: 0.54 GiB

Device class                     Upper-bound tok/s
Phone profile A                               87.3
Phone profile B                               32.1
Unified-memory profile                       256.7
Laptop profile                                77.0
Datacenter GPU profile                      4299.5
Browser profile                               51.3

The weights total about 0.544 GiB. At the assumed effective bandwidth of 51 GB/s, the weight-only ceiling is about 87 tokens per second. The example excludes several costs:

  • KV traffic.
  • Activations.
  • Dispatch.
  • Compute time.

Its result is a bound under the model assumptions, separate from any measured phone throughput.

The ceiling changes in direct proportion to the chosen bandwidth:

  • The largest input is 134 times the smallest, so their modeled rates have the same ratio.
  • The factor comes from the two bandwidth inputs and holds the model and effective fraction fixed.

The chart compares the modeled decode ceilings across six device classes:

  • Phone profile B: 25 GB/s peak.
  • Browser profile: 40 GB/s peak.
  • Laptop profile: 60 GB/s peak.
  • Phone profile A: 68 GB/s peak.
  • Unified-memory profile: 200 GB/s peak.
  • Datacenter GPU profile: 3350 GB/s peak.
PythonIn [7]
CollapseExpand
ceiling_order = sorted(decode_toks_per_s, key=decode_toks_per_s.get)
ceiling_values = [decode_toks_per_s[target] for target in ceiling_order]
ceiling_positions = list(range(len(ceiling_values)))
VisualizationOut [8]
CollapseExpand
Six horizontal dot positions compare modeled weight-only token rates.
Weight traffic sets the modeled decode ceiling for each illustrative bandwidth. All points use the same 4.25-bit payload and 75% of the stated peak bandwidth, so token rates span two orders of magnitude from mid-range phones to datacenter GPUs.

In the 51 GB/s scenario, dividing 51 GB per second by 0.584375 GB of weight reads per token gives about 87 tokens per second. The quotient stays the same if you convert both quantities to binary units. In a benchmark, measure bytes and elapsed time over the same decode steps. A smaller payload can still take longer to process if the kernel spends more time unpacking it.

The calculation reads the whole stored weight payload once per token. A deployment may have some weights resident in faster memory or reuse a tile across several sequences. Longer contexts can also increase KV traffic. KV Cache Memory develops the cache budget separately.

Effective Bandwidth

Effective bandwidth is the transfer rate achieved or assumed attainable at a named memory interface for a specific workload. For a planned estimate, state its source. For validation, divide measured bytes that cross the same interface by the relevant elapsed time.

Arithmetic intensity and the roofline

The roofline places a compute ceiling and a bandwidth ceiling on a workload. It uses operational intensity II, operations per byte transferred at the selected memory boundary. The figure uses operation counts rather than FLOPs because the illustrative arithmetic engine is specified in integer operations per second. Williams, Waterman, and Patterson, §3

I=operationsbytes transferred.I = \frac{\text{operations}}{\text{bytes transferred}}.

Let FF be the compute ceiling in operations per second for the kernel’s arithmetic type, and BB the bandwidth ceiling in bytes per second at the chosen boundary. At intensity II the bandwidth-limited rate is IBI B. The ceilings intersect at the ridge F/BF/B, in operations per byte. Performance PP is bounded by the smaller ceiling.

P≤min⁡(F,  IB).P \leq \min(F,\; I B).

For a projection with one input token, count one multiply and one add per weight. In the weight-only model, two operations per weight divided by 0.5 bytes per four-bit weight gives four operations per byte. An eight-bit payload would give two operations per byte under the same assumptions. If a prompt has TT tokens and the projection reuses the weights across those tokens, the simplified intensity is 4T4T, before counting scale metadata, activation movement, and other traffic.

A prompt gives a matrix-matrix kernel a reuse opportunity:

  • A loaded weight can contribute to several token positions before its tile is evicted.
  • Reuse can move the projection toward the compute ceiling, depending on tiling and on what else must cross the interface.
  • Attention, KV reads, and activations can move the actual workload away from this simplified model.

Use the same assumed operation and bandwidth ceilings for the two projections in this comparison. That isolates the effect of weight reuse. A runtime benchmark should compare the sustained rate of the actual kernels and operand formats it dispatches.

PythonIn [9]
CollapseExpand
# Hypothetical matched compute and memory ceilings for the example projections.
phone_compute_tops = 30e12  # compatible operations/s, assumed
phone_bw_bytes = 68e9  # bytes/s

machine_balance = phone_compute_tops / phone_bw_bytes  # ops per byte

# Decode: two operations per weight and half a raw byte per weight.
intensity_decode_4bit = 2 / 0.5  # 4-bit = 0.5 bytes/weight
# Prefill: matrix-matrix with prompt length P in the M dimension
# intensity grows ~ with P (weights reused P times)
prefill_intensities = {}
for P in [64, 512, 2048]:
    prefill_intensities[P] = 2 * P / 0.5
ConsoleOut [10]
CollapseExpand
Machine balance (phone): 441 ops/byte
Decode intensity (4-bit): 4 ops/byte
prefill seq=64    intensity=     256 ops/byte
prefill seq=512   intensity=    2048 ops/byte
prefill seq=2048  intensity=    8192 ops/byte

The ridge for these ceilings is about 441 operations per byte. The modeled decode projection is below it at 4. The 512-token prefill projection is above it at 2,048. Borrow the two positions as a diagnostic for the modeled projections. The estimate leaves out the traffic and arithmetic that distinguish a full forward pass from a single projection.

PythonIn [11]
CollapseExpand
import numpy as np

roof_intensities = np.logspace(0, 4, 401)
roof_rates = np.minimum(phone_compute_tops, phone_bw_bytes * roof_intensities)
decode_i = intensity_decode_4bit
prefill_i = prefill_intensities[512]
decode_roof_ops = min(phone_compute_tops, phone_bw_bytes * decode_i)
prefill_roof_ops = min(phone_compute_tops, phone_bw_bytes * prefill_i)
VisualizationOut [12]
CollapseExpand
Log-log roofline with separate markers for decode and 512-token prefill.
The idealized roofline rises with intensity up to the compute ceiling, then flattens. Decode at about 4 ops/byte sits far left of the ridge (memory-bound), while 512-token prefill at about 2048 ops/byte sits right of it (compute-bound).
Roofline Model

The roofline uses the smaller of the bandwidth and compute ceilings as an upper bound. Moving a point relative to the ridge can guide optimization. A benchmark tests whether the real kernel follows the assumed ceilings.

Memory hierarchy on a phone

An on-device kernel uses several levels of memory. The amounts, access paths, and ownership differ by chip.

  • Registers hold the values used directly by arithmetic instructions.
  • Caches can keep tiles near the execution units. Residency depends on tile size, the program’s access pattern, and other activity.
  • System DRAM holds larger tensors and can be shared with other device workloads.
  • Accelerator-local scratch memory can hold tiles of weights or activations if the kernel and compiler can schedule those tiles there.

If a weight matrix is larger than the available fast memory and must be streamed from DRAM, fewer transferred bytes raise the modeled bandwidth ceiling. Skipping arithmetic while leaving all weight bytes on that path may have little effect on an already bandwidth-limited step.

Residency is useful when the same tile is needed repeatedly. The kernel can reuse it from local storage if the tile fits and stays live across the relevant operations. A packed file can still expand when loaded, and a full tensor that lives in a shared allocation can move through cache tile by tile. For example, take a tile used by two sequences in one batched operation. Loading it once saves one read at the measured boundary if both sequences can consume it while it remains available. Fit, lifetime, and scheduling all matter. Compare that account with the memory counters for the actual batch.

Parallel hardware can hide some individual access latency by scheduling ready work while other work waits for memory. The available parallelism and the power budget differ across devices. Keeping accesses contiguous and reusing tiles help use whatever memory system the target provides.

Quantization Formats for Devices

A quantized representation combines stored weight values with the information needed to decode them. This section compares a simple group-wise integer representation across hypothetical hardware paths. The fastest option depends on the packing and the execution kernel. TinyChat is one concrete implementation that pairs four-bit weights with device-specific packing and fused kernels. Lin et al., AWQ

The format trade-off space

Compare formats on the dimensions that affect deployment.

  • Bits per weight: fewer stored bits can reduce bytes streamed per token if the runtime reads the packed format at the measured boundary. Extra metadata or transfers can offset the saving.
  • Representational fidelity: how much model quality you lose, measured by perplexity or task accuracy.
  • Unpacking cost: the instructions needed to turn packed weights back into something the multiplier can consume.
  • Kernel coverage: whether existing optimized kernels (device-specific) implement that format.

A runtime may have efficient implementations for some bit widths and group sizes. If there is no specialized path for a chosen representation, measure the generic path and any fallback. The smaller file and the faster kernel can belong to different choices.

Integer formats and scale overhead

Take a symmetric integer format with bb bits per weight and one 32-bit scale for each full group of gg weights. To estimate the stored payload, amortize the scale over the group.

beff=b+32gb_{\text{eff}} = b + \frac{32}{g}

Here beffb_{\mathrm{eff}} counts bits per stored weight, including that scale. With b=4b=4, group 32 uses 5 bits per weight and group 128 uses 4.25. The calculation assumes complete packed groups. A format with a stored zero point, padding, or alignment can take more space. A larger group spreads each scale over more values, and its effect on quantization error depends on the weight distribution and the fitting rule.

PythonIn [13]
CollapseExpand
def effective_bits(b, group_size, scale_bits=32, zero_point=False):
    overhead = scale_bits / group_size
    if zero_point:
        overhead += b / group_size  # one packed b-bit zero point per full group
    return b + overhead


effective_bit_table = {}
for g in [16, 32, 64, 128, 256]:
    effective_bit_table[g] = (effective_bits(4, g), effective_bits(8, g))

Multiply the parameter count by the effective bits per weight, then divide by eight for bytes. For 1.1 billion parameters, 4.25 bits gives 584,375,000 bytes, about 0.544 GiB. The ideal four-bit payload alone would use 550,000,000 bytes, about 0.512 GiB. Runtime buffers and cache storage enter the memory budget separately.

The next chart holds the weight count fixed and compares FP16, INT8 with groups of 128, and INT4 with groups of 32 or 128. FP16 uses 16 bits per weight. For INT4, reducing the group size from 128 to 32 raises the payload by about 18%. To find how many weights fit in a budget, divide the available bytes by the average stored bytes per weight. Check how the format packs or pads a partial group, and account for alignment if scales occupy a separate array.

PythonIn [14]
CollapseExpand
# Effective bits including 32-bit scale overhead, for a fixed model size and group size.
footprint_params = 1.1e9  # illustrative billion-class model
footprint_rows = [
    ("FP16", None),
    ("INT8 g128", 128),
    ("INT4 g128", 128),
    ("INT4 g32", 32),
]
footprint_gib = {}
for fmt_name, fmt_group in footprint_rows:
    if fmt_group is None:
        bits = 16.0
    elif fmt_name.startswith("INT8"):
        bits = effective_bits(8, fmt_group)
    else:
        bits = effective_bits(4, fmt_group)
    footprint_gib[fmt_name] = footprint_params * bits / 8 / (1024**3)
VisualizationOut [15]
CollapseExpand
Horizontal bars compare weight footprint in GiB across four quantization formats.
Same parameter count, four storage choices. Effective bits translate into GiB of weights that must fit alongside the KV cache and runtime buffers. FP16 is nearly four times the INT4 g128 footprint, and group size of 32 raises INT4 cost by about 18% over group 128.

Scale overhead changes most at small group sizes. The next chart shows INT4 and INT8 over the same range. For INT8, reducing the group size from 128 to 32 raises the payload from 8.25 to 9 bits per weight, an increase of about 9%.

PythonIn [16]
CollapseExpand
plot_group_sizes = sorted(effective_bit_table)
plot_int4_bits = [effective_bit_table[g][0] for g in plot_group_sizes]
plot_int8_bits = [effective_bit_table[g][1] for g in plot_group_sizes]
VisualizationOut [17]
CollapseExpand
Two lines show effective bits per weight, including scales, falling as group size grows.
A 32-bit scale adds the same absolute overhead to INT4 and INT8 at a given group size. The overhead per stored weight falls as the group grows, dropping from 2 extra bits at group 16 to about 0.125 bits at group 256.

Float formats: FP8, FP16, BF16

Floating-point formats allocate bits differently between range and precision. Check the formats the target runtime can execute for the operations in your model.

Choose a format the device and runtime accelerate for the required operators. Validate quality on your task with the actual executable path, including its accumulation precision and casts.

Mixed formats: W4A16, W8A8, W4A8

Weight and activation precision are separate choices. The notation uses W for weights and A for activations.

  • W4A16 uses four-bit weights and 16-bit activations. A suitable kernel can read compact weights and unpack them while computing.
  • W8A8 uses eight-bit weights and activations. For the same number of weights, its raw weight payload is twice that of a four-bit encoding. Scales, zero points, and packing can change the total ratio.
  • W4A8 pairs four-bit weights with eight-bit activations. This requires a kernel that implements the combination and any necessary scaling.

Two questions separate the modes:

  • For a memory-limited decode path, ask how much weight traffic the format removes and what it adds to the kernel.
  • For prompt processing, test whether the runtime can reuse weight tiles and use the activation arithmetic mode efficiently.

Benchmark both modes on the intended model and prompt lengths.

Weight Packing and Kernel Co-Design

The weight layout needs to match how the kernel reads and unpacks it. The model producer and kernel author agree on such details as group size, alignment, byte order, and where scales live.

When unpacking erases the savings

An INT4 kernel needs to recover the represented values or work directly with their encoded form. A separate unpack pass can read the compressed weights, write a larger temporary tensor, and make the dot product read that temporary again. A fused kernel can keep intermediate values in registers or scratch memory where the hardware and layout allow it.

A packed path can combine these operations in one kernel. A useful sequence is the following.

  1. Arrange packed weights so the kernel loads complete tiles.
  2. Use vector instructions or a specialized arithmetic kernel that can consume the representation.
  3. Apply each scale to the contributions from its own group.

The toy sets separate rates for memory transfer and unpack work. It uses packed weight traffic in both INT4 cases and varies only the assumed unpack operations per weight. The model assumes full overlap and takes the longer of the two components. The helper can add fixed overhead. It omits expanded temporary reads and writes, multiply-add time, scale traffic, and dispatch. Comparing actual kernels would also require measuring their scheduling and any vector instructions.

PythonIn [18]
CollapseExpand
# Toy model of per-token matrix-vector decode time (arbitrary units).
N_WEIGHTS = 100_000_000  # 100M weight elements
BW_BYTES_PER_UNIT = 4e9  # bytes per time unit in our toy machine
UNPACK_OPS_PER_UNIT = 8e9  # unpack ops per time unit


def decode_time(bits, unpack_per_weight, fixed_overhead=0.0):
    bytes_moved = N_WEIGHTS * bits / 8
    unpack_ops = N_WEIGHTS * unpack_per_weight
    t_mem = bytes_moved / BW_BYTES_PER_UNIT
    t_unpack = unpack_ops / UNPACK_OPS_PER_UNIT
    return max(t_mem, t_unpack) + fixed_overhead


# One modeled unpack operation per weight, overlapped with weight traffic.
t_int4_one_op = decode_time(4, unpack_per_weight=1.0)
# Fewer effective unpack operations, modeled as one per eight weights.
t_int4_one_op_per_eight = decode_time(4, unpack_per_weight=1.0 / 8.0)
# INT8 baseline: no unpack, 8 bits per weight.
t_int8_baseline = decode_time(8, unpack_per_weight=0.0)
ConsoleOut [19]
CollapseExpand
INT8, no modeled unpack work: 0.0250 units
INT4, one unpack op/weight: 0.0125 units
INT4, one unpack op/eight weights: 0.0125 units
Modeled time ratio, INT8 to lower-work INT4: 2.00x
Modeled time ratio, higher-work INT4 to lower-work INT4: 1.00x

The two INT4 examples both take 0.0125 time units because moving the packed bytes sets the same floor. The INT8 baseline, with no modeled unpack work, takes 0.025. At two unpack operations per weight, the INT4 curve reaches that baseline. Above two, INT4 takes longer under the model. The break-even depends on the assumed memory and unpack rates.

Sweep the modeled unpack work while holding weight count and bandwidth fixed. The INT8 baseline becomes faster once the INT4 curve crosses it.

PythonIn [20]
CollapseExpand
import numpy as np

unpack_sweep = np.linspace(0.0, 3.0, 121)
int4_time_sweep = [decode_time(4, cost) for cost in unpack_sweep]
int8_time_sweep = np.full_like(unpack_sweep, t_int8_baseline)
VisualizationOut [21]
CollapseExpand
The INT4 timing line starts flat, then rises through the flat INT8 baseline.
In this toy model, INT4 beats INT8 at low unpack work and loses above the crossing. The flat section reflects the time needed to move the packed bytes, and the crossing shows where modeled unpack work erases the byte savings.

The packing layout

Packing 4-bit weights means two weights per byte. If group size is 32, a group occupies 16 bytes plus a 4-byte scale. Device kernels can use several layouts:

  • Packed nibbles put two four-bit values in one byte. A mask and a shift can recover the low and high codes.
  • Lane-oriented packing groups codes according to how the target vector kernel consumes them. The exact interleaving and shuffle cost depend on the layout.
  • Scale placement keeps a group’s metadata easy to find when its weights are loaded. A kernel may store scales beside the packed blocks or in a separate array.

The target runtime decides how this maps to code:

  • WebGPU compute shaders can unpack packed buffer values before multiplication.
  • On Android, use the documented acceleration path for the specific runtime and device. Android 15 deprecated NNAPI, so treat it as a legacy path when testing an existing application.

Then trace one block through the fast path: check which bits encode its weights, where the scale is loaded from, and whether the unpacked values spill to memory. If a format uses signed weights, apply its defined decoding rule before interpreting the four-bit codes as numbers. Tracing also helps spot a mismatch between a model exporter and a kernel. W3C, WGSL Android, NNAPI Migration Guide

Kernel availability as a first-class constraint

Before settling on a format, find out which kernel the runtime actually dispatches. A compatible serialization format can still take a generic path for a particular tensor shape. Check the following.

  • Does the runtime have a fused kernel for W4A16 with this group size?
  • Does the device's NPU support the format at all, or does it fall back to CPU with a slow path?
  • Is the unpack fused, or does the runtime spend cycles on it?
  • Does the runtime support the model's activation functions fused (e.g., SwiGLU) or does it materialize intermediates?

Record the runtime version, variant, actual kernel, prompt size and batch width for each measurement. A smaller representation can be slower if it uses a fallback. Timing the full request also captures transitions between kernels and between devices.

Sparsity on Devices

A sparse representation can avoid storing zeros. Executing fewer arithmetic operations also requires an appropriate sparse kernel or a graph whose tensor shapes have changed. Selected NVIDIA TensorRT configurations can use structured-sparse tactics. For some input shapes, TensorRT still chooses a dense tactic. NVIDIA, TensorRT Structured Sparsity

Structured vs unstructured

  • Unstructured sparsity zeros individual weights. Compressed storage can save space. Skipping their multiplications requires a representation and execution path that exploit the zeros.
  • Shape-changing pruning removes whole channels, heads, or blocks and updates connected tensors. It reduces the modeled work of affected dense operators. Runtime depends on the resulting shapes and kernels.
2:4 Structured Sparsity

A 2:4 pattern permits at most two nonzero values in each group of four along the required axis. This pattern preserves the original matrix dimensions and has different execution requirements from removing complete channels. Check the operand types and grouping rules of the sparse kernel. NVIDIA, cuSPARSELt Sparsity Types

The bandwidth interaction

Compressing a sparse tensor reduces DRAM traffic when the runtime streams the compressed representation at that boundary. The payload includes values and position metadata. Expanding it into a dense DRAM tensor before the hot loop can remove the expected per-step traffic reduction.

The following cases separate storage from execution. Shape-changing pruning removes dimensions and may require updates to connected layers. A fixed-pattern representation leaves the dimensions in place and encodes the positions of the surviving values. Two models described as having the same sparsity can exercise different instructions because of that difference. Report the pattern, the stored format, and the actual kernel when comparing them.

  • Compressed values with a matching sparse kernel can reduce traffic and work.
  • Zero values in a dense tensor still occupy the same payload and pass through an ordinary dense kernel.
  • Shape-changing pruning can use smaller dense tensors. Measure how the new shapes map to the runtime. Structured Pruning

When comparing candidates, keep the quality target fixed:

  • Dense low-bit.
  • Compressed sparse.
  • Smaller dense.

Sparsity has a deployment cost when it changes the format or requires a different kernel.

A quick sparse-vs-dense check

Consider a toy encoding for exactly two stored slots in each group of four. There are six possible position pairs, so a fixed-width index needs at least three bits per group. With two four-bit values and that index, the packed payload is (2⋅4+3)/4=2.75(2\cdot4+3)/4=2.75 bits per original weight. That saves 31.25% relative to the four-bit dense payload. This example omits scales, alignment, and other metadata, and it describes its own encoding.

PythonIn [22]
CollapseExpand
def bytes_per_weight_dense(bits):
    return bits / 8


def bytes_per_weight_2to4(bits, block=4, keep=2, index_bits=3):
    # keep nonzero values + index bits per block
    return (keep * bits + index_bits) / block / 8


sparse_dense_results = {}
for bits in [4, 8]:
    dense = bytes_per_weight_dense(bits)
    sparse = bytes_per_weight_2to4(bits)
    sparse_dense_results[bits] = (dense, sparse)

The same assumed layout uses 4.75 bits per original weight with eight-bit values, a 40.625% reduction relative to dense INT8. Compare either result against the storage and kernel cost of changing bit width instead. A production sparse format can have a different encoding or alignment.

Browser and WebAssembly Targets

The browser exposes execution through its APIs and implementation. Check what the same model uses on the browsers and devices you intend to support. The availability of an API also differs from the availability of one optimized kernel.

  • WebGPU exposes GPU compute. WGSL’s FP16 arithmetic depends on the optional shader-f16 feature. Check the adapter features and buffer limits before choosing a shader and weight packing. W3C, WGSL
  • WebAssembly with SIMD supports 128-bit vector operations. A runtime can use them for packed arithmetic when its compiled kernel implements the format. WebAssembly 2.0
  • WebNN defines an interface for neural inference hardware acceleration, including implementations that target a GPU or dedicated ML accelerator. Test the graph and options on the implementation you ship. W3C, WebNN §2.2.4
  • A CPU path can help with coverage and debugging if your application provides one. Measure it separately from the accelerator path.

Use the actual browser, adapter, and model to measure throughput and test whether the weights and cache fit. Include staging copies and runtime buffers in the memory estimate.

End-to-end token rate is the useful comparison across browser and native paths. Keep the sampling settings, sequence lengths, and evaluation inputs fixed where possible. The application can also profile loading, prompt processing, and subsequent decode separately. If an adapter cannot allocate the tensor buffers, changing the launch configuration alone cannot make that buffer layout fit. A smaller model, a representation with a smaller resident payload, or a runtime that partitions tensors differently changes the memory side of the comparison.

A Worked, Runnable Bandwidth and Format Analysis

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.

Co-Design for Phones, Browsers, and Edge

Choose the architecture, representation, and runtime together. Estimate capacity and traffic first, then use the actual kernels to check which resource is limiting each workload.

Architecture choices that are device-friendly

Architecture choices change both traffic and kernel shapes.

  • Grouped-query attention shares one set of keys and values across query heads in a group. At fixed head dimension and context length, reducing the KV-head count reduces the raw KV payload in proportion. The original paper reports its quality comparison for specific trained models. Ainslie et al., GQA
  • Layer geometry changes kernel shapes. Test narrower or wider projections with the same evaluation protocol if the architecture is still open to change.
  • Operator fusion can keep intermediate values within a kernel. If the runtime implements an activation and its adjacent operations as separate kernels, measure any additional intermediate traffic.
  • Tied embeddings share the input and output weights. At vocabulary size 32,000 and width 2,048, this removes one 65,536,000-parameter matrix from the separate-storage budget.

These choices change both model behavior and executed shapes. Evaluate the resulting model on the same tasks before attributing an improvement to hardware co-design.

Thermal and power envelopes

Sustained load may change a device’s available performance as it heats. Record the device state and benchmark over a representative workload duration. Android’s thermal guidance describes monitoring available thermal headroom. Android Thermal API

  • Measure both the initial response and sustained generation under a workload that resembles actual use.
  • Compare the latency and task quality of the candidate formats after warm-up.
  • Where the runtime offers several execution paths, measure elapsed time and energy for each.

Record how rate changes over the intended session, including its warm-up and steady state where present. Repeat the comparison under a comparable starting thermal condition.

The co-design checklist

Work through the model and runtime in this order.

  1. Pick the target and runtime. Record the hardware, operating system, and runtime version.
  2. Choose the format the runtime accelerates. Query the runtime's supported operators and fused kernels before deciding bit-width.
  3. Size the model against caps. Weights + KV cache + runtime buffers must fit the per-app memory limit with headroom.
  4. Verify the executed kernel. Inspect dispatch or profiling evidence. Low bandwidth alone cannot identify a fallback.
  5. Benchmark sustained, not burst. Run for the duration a real user would.
  6. Time the full local path. Include tokenization, prompt processing, decode, and sampling.

A kernel timing starts after some preparation and ends before some output processing. Profile those operations separately when they account for a meaningful share of the requested latency. Keep the denominator explicit. Generated tokens divided by the elapsed decode interval measures a different quantity from generated tokens divided by time for the whole request. If concurrent requests share a batch, report individual response speed and the aggregate rate as separate measurements. The same aggregate figure can hide differences in how quickly each request receives tokens.

Limitations & Impact

The calculations assume particular operands, access patterns, and operation rates. Treat their outputs as starting points when planning what to measure. Record the prompt and output length for each timing, and start the clock at the boundary you are claiming to measure. For a comparison of two quantized formats, reserve the same request-level settings and include the effect of model warm-up and repeated use. If the faster variant produces a different answer distribution, compare task outcomes before declaring the trade worthwhile.

The simplified weight-only ceiling omits traffic and time from the rest of the application. Two practices help quantify the gap:

  • Use the actual device, runtime version, prompt and generation lengths, and background load when benchmarking.
  • Record the amount of memory in use and the sustained rate as well as the peak rate.

Combined optimizations can change which resource is limiting. For example, once quantization lowers weight traffic, unpacking or KV reads can account for a larger share. Adding sparsity can also select a different kernel. Measure the combined format under the same conditions instead of multiplying separate speedups.

Quality is an acceptance criterion. Compare the quantized model with an appropriate baseline on the tasks and languages your application serves. For a long-context application, include long contexts in that evaluation.

Local inference can remove a request-time network dependency when the model, inputs, and runtime are already available on the device. Whether data stays local depends on the application’s full data flow. Check networking, fallbacks, and any telemetry separately from the inference kernel.

On-device adaptation changes the memory budget when training introduces activations, gradients, or optimizer state. Hybrid routing changes the measurement again by adding network latency and remote work. Keep those workloads separate from the inference-only calculations in this chapter.

Summary

Start with the model, runtime, and device you intend to deploy. Check each limit in the units that match the workload.

  • Decode traffic. Count weight and cache bytes at the interface you model. Use effective bandwidth to estimate the transfer-time floor.
  • Roofline. Compare the intensity of a kernel with the compute-to-bandwidth ridge under consistent operation and byte counts.
  • Stored bits. Account for the weight payload and group metadata. Allow separate space for the KV cache and runtime buffers.
  • Runtime support. Check that the actual dispatched kernel supports the chosen format and tensor shape.
  • Unpacking. Measure the cost of making stored weights usable by the arithmetic kernel.
  • Sparsity. Count the position metadata and check whether the executed kernel consumes sparse data or a smaller dense shape.
  • Deployment. Measure the complete path at representative workloads and temperatures. Check the task quality of each candidate.

Use the cost model to choose what to profile first. Use the observed latency, memory, and quality to decide which configuration to ship.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about hardware-aware model optimization.

Hardware-Aware Model Optimization

Question 1 of 80 of 8 completed
In the illustrated weight-only decode ceiling, why does the estimate use the stored bytes crossing the memory interface rather than the raw parameter count alone?
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

Small Language Model Design

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

31 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026hardwareaware, author = {Michael Brenndoerfer}, title = {Hardware-Aware Model Optimization}, year = {2026}, url = {https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Hardware-Aware Model Optimization. Retrieved from https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment
MLAAcademic
Michael Brenndoerfer. "Hardware-Aware Model Optimization." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment>.
CHICAGOAcademic
Michael Brenndoerfer. "Hardware-Aware Model Optimization." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Hardware-Aware Model Optimization'. Available at: https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Hardware-Aware Model Optimization. https://mbrenndoerfer.com/writing/hardware-aware-model-optimization-quantization-edge-deployment
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy