Hardware-Aware Model Optimization › Why Hardware, Not Just Size, Defines Feasibility

Michael BrenndoerferDecember 1, 202610 min read
Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 328Hardware-Aware Model Optimization › Why Hardware, Not Just Size, Defines Feasibility
Reading section 2 of 11 · Why Hardware, Not Just Size, Defines Feasibility · 10 minSection 2 of 11 · 10 min

Section 2 of 11 · 10 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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