Edge AI · A 15-Day Engineering Path
Course home 简体中文
DAY 14

LLM Performance and Infrastructure

Trace single-machine TTFT and ITL into cluster data movement, topology, and SLOs

Suggested reading: about 20 min

Learning goal

Use reproducible experiments to localize device inference bottlenecks, then understand how training parallelism, KV scheduling, Prefill/Decode disaggregation, and serving SLOs extend the same ledger to clusters.

Chapter keywords

KeywordExplanationESP32 engineering analogy
TTFTThe time from request submission to the first returned token.Like the delay from the first interrupt to the first valid status message.
p95The tail-latency percentile that 95% of requests do not exceed.Like the latency budget for the slowest small fraction of field events.
GoodputUseful work completed within correctness and SLO constraints, rather than raw peak throughput.Count only CRC-valid frames delivered before their deadline, not late or corrupt traffic.
PD disaggregationPlacing prefill and decode in worker pools that can be scheduled and scaled independently.Like separating batch preprocessing and real-time tasks onto cores, while still paying queue and copy costs.

Bridge from the previous chapter

Day 13 proved which backends a request actually traversed. This chapter upgrades that correctness baseline into a cross-scale performance ledger, extending device measurements into cluster communication, state scheduling, and service objectives.

HOW WE GOT HERE

Historical development

Large-scale LLM infrastructure was not produced by faster GPUs alone. The chip track continually changes the ratios among compute, memory, and interconnect; the system track uses sharding, I/O-aware algorithms, and request scheduling to turn that hardware into a usable service. Read the tracks together.

Chips and interconnects

2012

GPU deep learning demonstrates the scaling value of throughput computing

AlexNet used GPUs to train a large convolutional network and helped establish general-purpose parallel accelerators as the deep-learning workhorse. The systems problem quickly expanded from one kernel to feeding and synchronizing many devices.

Original AlexNet paper ↗
2017

TPUs and Tensor Cores create dedicated matrix-multiply paths

The TPU paper shows a systolic array and on-chip buffers organized around neural inference. At the same time, Tensor Cores accelerated mixed-precision matrix operations, pushing models and kernels to co-design around specialized paths.

Original TPU paper ↗
2018

Mixed precision turns number format into a systems lever

FP16 computation with FP32 accumulation and loss scaling reduced bandwidth and storage pressure while preserving useful training behavior. BF16, FP8, and quantization continue the model-hardware co-design direction.

Original mixed-precision training paper ↗
2020s

HBM and scale-up links jointly define an accelerator domain

Single-device capacity and bandwidth cannot independently solve very large models. HBM plus intra-node fabrics let accelerators share fine-grained layer work at lower cost, making topology affinity a parallel-planning input.

Official NCCL user guide ↗
Today

Rack-scale AI systems co-design fabric, power, and cooling

Accelerators are no longer interchangeable PCIe cards. In-rack networks, switches, CPUs, storage tiers, power, and cooling bound sustainable throughput together, so comparisons must be tied to a workload and complete configuration.

Official MLPerf Training results and rules ↗

Parallel algorithms and serving systems

2012

Parameter servers decouple model state from workers

DistBelief demonstrated parameter services and asynchronous methods for training deep networks across many machines, establishing an early frame for data parallelism, fault handling, and cluster scheduling.

Original DistBelief paper ↗
2019

Megatron scales tensor parallelism inside Transformer layers

Megatron-LM systematically partitions attention and MLP matrices and composes tensor, pipeline, and data parallelism, exposing the relationship between parallel dimensions and physical topology.

Original Megatron-LM paper ↗
2020

ZeRO removes replicated data-parallel state

ZeRO progressively partitions optimizer state, gradients, and parameters, exchanging communication for substantial memory capacity and providing a foundation for FSDP-style implementations.

Original ZeRO paper ↗
2022

FlashAttention reduces HBM traffic with I/O-aware tiling

It does not approximate attention. It reorganizes exact computation around on-chip storage capacity and avoids intermediate matrix traffic, proving that equal algorithmic complexity does not imply equal hardware cost.

Original FlashAttention paper ↗
2023–today

After PagedAttention, KV becomes a cluster scheduling object

vLLM pages KV to reduce fragmentation and enable sharing. Prefix-aware routing, tiered caching, and prefill/decode disaggregation then bring state location, transfer, and SLOs into the serving control plane.

Original vLLM and PagedAttention paper ↗
Why it still matters today: The chip track supplies bandwidth, capacity, and topology limits; the system track decides how to partition models, place state, queue requests, and recover. Any architecture showing only one misses a critical path: parallel algorithms obey interconnects, scheduling must know where KV lives, and capacity conclusions obey SLOs.
BUILD INTUITION FROM A FAMILIAR SYSTEM

Illustrated analogy

Investigating a high-speed train that is always late

Passengers feel only total journey time—end-to-end latency. Security screening resembles pre-processing, waiting for the first departure resembles TTFT, and the intervals between stations resemble inter-token latency. The average arrival may look normal while a handful of severe storm delays form p95. Raising the train's maximum speed accomplishes little if ticket checks, track changes, or station entry dominate. Running every carriage's air conditioning at full power can also increase energy per passenger and trigger thermal limits. Real optimization reconciles the timetable, route trace, and power meter.

Station wait Queuing, tokenization, pre-processing, and context allocation
First departure Prefill completing and returning the first token: TTFT
Station-to-station rhythm Decode inter-token latency and tokens/s
Storm speed limit Long tails caused by latency, power, temperature, and thermal throttling

Where the analogy stops: Train segments are usually approximately serial, while inference can pipeline, copy asynchronously, or batch multiple requests. The sum of single-request stages also does not directly predict high-concurrency throughput. The analogy highlights segmentation and tails but cannot replace trace timestamps, hardware counters, and queueing models.

Chapter walkthrough

Write the experiment contract before starting the timer

A comparable benchmark fixes at least the model and hash, quantization format, runtime commit, threads and CPU affinity, prompt-token count, output limit, sampling, concurrency, power supply, and cooling. Warm up first, run enough repetitions, and retain raw samples. If two tests use different input lengths or temperatures, their p95 and tokens/s are not directly comparable. Save these fields as a machine-readable manifest so firmware or model upgrades can rerun the test automatically.

Diagnose TTFT and generation speed separately

TTFT includes queuing, templating, tokenization, context setup, prefill, and the first sampling round. Steady-state decode mainly reflects incremental reads of weights and KV, small matrix operations, and sampling. A long prompt raises the former; a long context and bandwidth pressure slow the latter. Place monotonic-clock timestamps on the same request and report prompt tokens/s, the inter-token-latency distribution, and output tokens/s rather than one total duration.

Let a bottleneck hypothesis drive the next observation

Low CPU utilization does not prove that compute is abundant: threads may be waiting on memory, a lock, GPU synchronization, or network backpressure. Use a trace to find the longest stage and then state a falsifiable hypothesis. If bandwidth is suspected, change quantization or context and observe speed and bytes moved; for compute, vary core count or frequency; for copies, record partition boundaries. Change one variable at a time so the evidence can distinguish correlation from causation.

Draw the data-movement hierarchy before discussing compute

A kernel's hottest scalar may remain in a register, while a thread block reuses tiles in on-chip SRAM or shared memory. Weights, activations, and KV cache primarily occupy HBM. Cross-accelerator tensors traverse PCIe or a dedicated scale-up fabric; cross-node collectives traverse NICs and switches; checkpoints finally reach local NVMe or remote object and parallel file systems. Moving outward generally offers more capacity but raises latency, energy, and contention. Arithmetic intensity asks how much computation is performed for every byte moved, and attention, MoE dispatch, and embedding lookup can have radically different limits. A useful engineering diagram labels every edge with bytes, frequency, contenders, and topology instead of saying only that the GPU is fast. HBM capacity determines whether state fits, HBM bandwidth caps many token-by-token kernels, the intra-node fabric shapes TP collectives, and the scale-out network shapes DP, EP, and recovery. Peak FLOPS becomes useful throughput only when operands arrive in time, kernel shapes use the machine well, and communication can be hidden.

Six parallel dimensions cut different axes of the same training graph

Data parallelism replicates the model, partitions the input batch, and reduces gradients after backward. Tensor parallelism cuts matrices or attention heads inside a layer, so each layer may need an all-reduce or reduce-scatter/all-gather pair; that fine-grained critical path prefers a low-latency, high-bandwidth scale-up domain. Pipeline parallelism assigns contiguous layers to stages, moves boundary activations, and feeds microbatches through the pipeline; bubbles and stage imbalance are its central costs. Context parallelism partitions a long sequence and exchanges the keys, values, or intermediates required for attention. Expert parallelism distributes MoE experts and moves routed tokens with all-to-all dispatch and combine; routing skew lets a few experts stall everyone. FSDP/ZeRO partitions parameters, gradients, and optimizer states: gather parameters for computation, reduce-scatter gradients afterward, then release full replicas. These are not mutually exclusive toggles. Production jobs combine dimensions in a device mesh, but every dimension adds layout transitions, failure surface, and tuning choices.

Online inference has two phases, two latency families, and growing state

Prefill processes prompt tokens in parallel and often forms large matrix multiplies; it strongly influences Time To First Token. Decode emits a small number of tokens per iteration but repeatedly reads layer weights and historical keys and values; memory bandwidth and scheduling overhead often dominate, while Inter-Token Latency determines streaming feel. KV cache avoids recomputing attention for old tokens, but capacity grows with concurrency, context length, layers, KV heads, head dimension, and dtype. PagedAttention maps a logically contiguous sequence to physical blocks, reducing external fragmentation and enabling controlled sharing. Prefix caches reuse identical leading blocks, but hits depend on normalized templates, tenant isolation, and routing locality. Continuous batching admits and retires requests at decode iterations, eliminating empty slots left by static batches while turning queuing, preemption, and fairness into first-class decisions. Throughput must be reported under a TTFT/ITL SLO; tokens produced after a request's deadline are not useful serving capacity.

Close capacity planning with SLOs, observability, and failure drills

At ingress, record input and output token counts, model and tokenizer versions, sampling parameters, tenant, deadline, and trace ID. The router records its selection reason, prefix hit, and queue estimate. Workers expose TTFT, per-token ITL, batch width, KV block use, preemption, OOM, and errors. Network telemetry covers collective or point-to-point bytes, congestion, and retries. Capacity models must separate short chat, long-context, batch, and multi-turn traffic because average arrival rate hides the impact of long prompts on prefill and KV. Load tests should replay arrival processes and length distributions, then report p50, p95, p99, and SLO goodput. Drills should kill workers, throttle networks, fill KV capacity, corrupt a checkpoint shard, and roll through an incompatible runtime change. Peak benchmark numbers become operational evidence only when the service rejects, degrades, rolls back, and leaves an auditable trace under these conditions.

PLACE PROJECTS IN THE RIGHT LAYER

Infrastructure map and cross-scale lessons

Technical status verified on:

This representative open-source map is organized by responsibility, not as a performance ranking. Versions, hardware support, and APIs change; return to the linked official docs or repositories and retest with your model, topology, and SLO.

Training sharding and parallelism

  • PyTorch FSDP2 / DTensor ↗

    Problem
    Express parameter and tensor sharding on a device mesh while reducing fully sharded training redundancy.
    Core mechanism
    Keep parameters as sharded DTensors, all-gather before computation, reduce-scatter after backward, and compose two-dimensional meshes.
    Scope and boundary
    It does not choose network topology, checkpoint policy, or model-parallel dimensions; peak memory still depends on prefetch and activations.
  • Megatron Core ↗

    Problem
    Compose TP, PP, CP, EP, and DP for large Transformers.
    Core mechanism
    Partition matrices, layers, sequences, and experts around Transformer structure, with schedules and communication-overlap paths.
    Scope and boundary
    Performance depends on supported models, layout, and accelerator topology; example throughput does not transfer to another cluster.
  • DeepSpeed ↗

    Problem
    Provide ZeRO, pipeline, mixed-precision, and broader training or inference systems capabilities.
    Core mechanism
    Shard model states and coordinate communication, offload, and execution schedules.
    Scope and boundary
    Broad feature coverage does not make every combination optimal; pin versions and validate contracts with model code.

Communication and kernels

  • NCCL / RCCL ↗

    Problem
    Execute topology-aware collectives across GPUs.
    Core mechanism
    Select ring, tree, and transport paths and expose all-reduce, all-gather, reduce-scatter, and related primitives.
    Scope and boundary
    A communication library cannot fix a poor upper-level partition. RCCL is the corresponding AMD implementation; consult each hardware support matrix.
  • Triton / FlashAttention ↗

    Problem
    Reduce custom-operator effort and attention's intermediate HBM traffic.
    Core mechanism
    Compile tiled kernels; FlashAttention uses I/O-aware tiling for exact attention.
    Scope and boundary
    Shape, dtype, architecture, and compiler version affect gains; one faster kernel is not end-to-end throughput.
  • DeepEP / NIXL ↗

    Problem
    Handle advanced data planes such as MoE token dispatch and cross-tier or cross-node movement.
    Core mechanism
    DeepEP optimizes expert all-to-all; NIXL abstracts transfers of objects such as KV across heterogeneous memory tiers.
    Scope and boundary
    They move different objects and replace neither general collectives, routing control planes, nor consistency protocols.

Model-serving runtimes

  • vLLM ↗

    Problem
    Improve KV utilization and dynamic request throughput for generation serving.
    Core mechanism
    PagedAttention, continuous batching, prefix cache, parallel modes, and connectors.
    Scope and boundary
    Feature toggles are not universal gains; validate TTFT, ITL, tail latency, and device memory for the workload.
  • SGLang ↗

    Problem
    Organize structured generation programs and high-throughput model serving.
    Core mechanism
    Connect front-end language and reuse with back-end scheduling, attention kernels, and distributed serving.
    Scope and boundary
    APIs and backends evolve quickly; validate tokenizer, sampling, and output semantics during migration.
  • TensorRT-LLM ↗

    Problem
    Build optimized LLM engines and serving paths on NVIDIA platforms.
    Core mechanism
    Graph optimization, specialized kernels, quantization, parallel execution, and in-flight batching.
    Scope and boundary
    Platform coupling and engine artifact management are costs; never compare vendor results outside their environment.

Distributed serving orchestration

  • llm-d ↗

    Problem
    Organize KV-aware routing, tiered caching, and disaggregated serving on Kubernetes.
    Core mechanism
    Connect gateway scheduling, vLLM, KV indices, and point-to-point transfer to select workers using cache and load.
    Scope and boundary
    It is not another attention runtime. Components evolve quickly; production deployments must pin versions and drill failures.
  • Dynamo ↗

    Problem
    Build composable distributed inference data planes and KV-aware serving pipelines.
    Core mechanism
    Organize routing, workers, KV transfer or offload, and separated prefill/decode execution.
    Scope and boundary
    Reference configurations are not universally optimal across models; extra hops and state coordination enter the SLO budget.

Source mechanism, engineering lesson, and boundary

Source mechanismEngineering lessonScope and boundary
Data-movement hierarchyPlace weights, activations, gradients, KV, and checkpoints on their actual memory and network tiers.Capacity alone is insufficient; measure access frequency, contention, and tails.
Multidimensional parallelismKeep frequent fine-grained communication on the fastest topology and cross nodes with coarser exchanges.The best mesh changes with model shape, sequence length, and cluster topology.
Paged KV and disaggregationMake state location and ownership scheduling inputs and define failed-transfer semantics.Cache hits and phase separation help only under the target workload.
SLO goodputPlan capacity around useful training tokens or requests completed before deadlines.Average tokens/s says nothing about tails, fairness, or recovery.
WATCH THE DATA MOVE

Interactive process

One request through a disaggregated prefill/decode cluster

Follow tokens, KV blocks, and scheduling metadata along different paths; every stage can change TTFT, ITL, or cache locality.

Step 1 / 6

Admission and tokenization · prompt + tenant + deadline → token IDs

Enforce quotas, apply a versioned chat template, and estimate prompt and output budgets

Watch for

A wrong tokenizer or template breaks semantics, capacity estimates, and prefix hits together

Loop / return condition: A multi-turn session enters routing again with a stable prefix and may skip part of prefill on a hit. Completion, cancellation, eviction, or version changes must atomically release KV ownership and invalidate the corresponding routing index.

View the complete static diagram
request → queue → prefill → decode → stream
             │ TTFT      │ ITL / KV
chip memory ↔ scale-up ↔ scale-out ↔ storage
             └── topology + parallelism + SLO ──┘

Code or command example

record(model, quant, prompt_tokens, output_tokens, hardware, temperature)
measure(TTFT, ITL_p50, ITL_p95, tokens_per_s, joules_per_token)
# At cluster scale, add collectives, KV occupancy, goodput, and recovery

Hands-on lab

Fix model, quantization, prompt, and output length. Run one cold and ten warmed local trials, recording TTFT, ITL p50/p95, RSS, power, and temperature. Then place one request on a chip-memory→scale-up→scale-out→storage map. For TP, PP, sharded training, or PD disaggregation, label every new communication edge and the metric it may improve or worsen.
Lab notes and export

Engineering pitfall

Avoid this mistake: Reporting peak tokens/s alone or treating one parallel/disaggregated strategy as universally faster. Results must bind model, precision, sequence, concurrency, topology, thermal state, and SLO; boundary communication can erase local gains.

Knowledge check

Answer all three multiple-choice questions, then submit. Answers stay hidden until submission.

1. Which definition best describes Time to First Token?
2. Why is tensor parallelism normally confined to a fast local interconnect domain?
3. Which case is most likely to make prefill/decode disaggregation slower than colocation?

LEARN TOGETHER

Discuss this chapter on GitHub

Sign in with GitHub to ask a question, share measurements, or compare implementations. Comments are stored in this course's GitHub Discussions.

The embedded comments need JavaScript. You can also open the GitHub discussion area directly: Open GitHub Discussions ↗

Further reading

Bridge to the next chapter

The final chapter closes model packages, runtimes, heterogeneous backends, MCU/host safety boundaries, energy, fallback, OTA, and observability into a deliverable edge-LLM product.

Next: Day 15 · Shipping Edge LLMs