Настоящий материал представляет собой обзор главы 15 книги Chris Fregly, «AI Systems Performance Engineering: Optimizing Model Training and Inference Workloads with GPUs, CUDA, and PyTorch», O'Reilly Media, 2026 (Copyright © 2026 Flux Capacitor, LLC).
Прямые цитаты из книги выделены отдельными блоками с пометкой «Цитата из книги». Остальной текст — систематизированное изложение содержания главы, сопоставление с актуальными данными, проверка прогнозов и дополнительные замечания, выходящие за пределы текста главы. Цитаты приводятся в ограниченном объёме в целях обзора и критического анализа.
Глава 15 книги Fregly посвящена продвинутым методам оптимизации для высокопроизводительного многоузлового инференса больших языковых моделей (LLM) на современных GPU NVIDIA. Модели продолжают масштабироваться до сотен миллиардов и триллионов параметров, а архитектуры вроде смеси экспертов (MoE) делают распределённый инференс необходимостью, а не опцией.
«LLM продолжают масштабироваться до огромного числа параметров. В частности, появление MoE-моделей, которые комбинируют множество специализированных подсетей («экспертов») со встроенным механизмом гейтирования, подняло размеры параметров до сотен миллиардов или триллионов. И хотя для каждого входа активируется лишь часть параметров, выполнение инференса на таких моделях требует распределения нагрузки по множеству GPU».
В главе рассматривается полный спектр техник для многоузлового инференса: от архитектурного разделения фаз предзаполнения и декодирования до стратегий параллелизма, спекулятивного декодирования, ограниченного вывода, динамической маршрутизации экспертов, управления KV-кэшем и обеспечения отказоустойчивости. Ключевая идея: производительность многоузлового инференса определяется не только вычислительной мощностью GPU, но и качеством коммуникаций, балансировкой нагрузки и эффективным использованием памяти.
Процесс инференса современных LLM состоит из двух принципиально разных фаз: предзаполнения (prefill) и декодирования (decode). Разделение этих стадий на отдельные вычислительные пулы позволяет масштабировать каждую из них независимо.
На этапе предзаполнения модель обрабатывает весь входной промпт за один прямой проход, формируя KV-кэш для всех токенов промпта. Эта стадия характеризуется высокой арифметической интенсивностью и является compute-bound.
На этапе декодирования модель выполняет авторегрессионную генерацию, предсказывая каждый следующий токен с использованием закэшированных KV-представлений. Эта стадия является memory-bandwidth-bound.
Prefill и Decode работают параллельно, обмениваясь KV-кэшем по выделенному каналу
Традиционно системы инференса размещают обе стадии на одних узлах, что приводит к интерференции: длинное предзаполнение блокирует GPU и задерживает генерацию токенов для других запросов. Система DistServe, применив разделение, сообщила о росте полезной пропускной способности до 7,4× по количеству запросов, обслуженных в рамках ограничений TTFT и TPOT, при ужесточении SLA по задержке до 12,6×.
Библиотека NVIDIA NIXL минимизирует накладные расходы на передачу KV-кэша, автоматически выбирая пути NVLink/NVSwitch, RDMA или через хост на основе топологии. NIXL интегрируется с Dynamo, vLLM и TensorRT-LLM.
NIXL обеспечивает прямой GPU-to-GPU трансфер KV-кэша между prefill и decode движками
Разделение предзаполнения и декодирования на отдельные пулы GPU устраняет интерференцию и позволяет независимо масштабировать каждую фазу. NIXL обеспечивает эффективную передачу KV-кэша через NVLink, NVSwitch или RDMA.
Для развёртывания разделённого инференса используется Kubernetes с отдельными deployment'ами для prefill и decode. vLLM Router и llm-d обеспечивают оркестрацию.
Следите за утилизацией NVLink и NIC во время передачи KV. Цель — перекрыть передачу и вычисления с помощью отдельных потоков и событий.
Эффективное обслуживание массивных MoE-моделей требует нескольких форм параллелизма из-за ограниченной памяти GPU.
| Стратегия | Основа разделения | Плюсы | Минусы |
|---|---|---|---|
| Тензорный (TP) | Внутри слоя (матрицы весов) | Почти линейное ускорение compute-bound слоёв; перекрытие all-reduce | Частые коммуникации; нужен NVLink/NVSwitch |
| Конвейерный (PP) | Разные слои на разных GPU | Масштабирование памяти по слоям; микробатчинг | Пузыри конвейера; сложнее в реализации |
| Экспертный (EP) | Разные MoE-эксперты на разных GPU | Практически неограниченный размер модели | Высокие накладные all-to-all; дисбаланс |
| Данных (DP) | Репликация всей модели | Почти линейное масштабирование; простота | Не улучшает задержку; умножает память |
| Контекстный (CP) | Токены последовательности между GPU | Ускорение для длинного контекста | Специальные алгоритмы внимания; коммуникации |
Экспертный параллелизм (EP) специфичен для MoE-архитектур. Каждый эксперт размещается на отдельной GPU, а гейтирующая сеть направляет токены к активированным экспертам. Это требует паттерна all-to-all коммуникации на каждом слое MoE.
Для предотвращения перегрузки экспертов используется коэффициент ёмкости (capacity factor), обычно 1,2–1,5× от средней нагрузки. Токены сверх этого направляются резервному эксперту.
Каждый GPU получает только токены для размещённых на нём экспертов
Комбинация TP, PP, EP и DP позволяет обслуживать модели любого размера. Экспертный параллелизм — ключ к масштабированию MoE-моделей. Коэффициент ёмкости и репликация горячих экспертов предотвращают дисбаланс.
Группы TP держите внутри NVLink-домена. PP — минимально для размещения модели. EP максимизируйте для распределения экспертов. DP — для пропускной способности.
Профилируйте Nsight Systems для поиска дисбаланса. Используйте иерархические all-to-all и двойную буферизацию для сокращения коммуникационных накладных расходов.
Одна из фундаментальных проблем инференса LLM — последовательная природа декодирования. Спекулятивное декодирование решает эту проблему, генерируя несколько токенов за один шаг.
Спекулятивное декодирование объединяет небольшую быструю «черновую» модель с более крупной «целевой» моделью. Черновик предлагает k токенов, целевая модель проверяет их одним батчем.
Draft-модель предлагает k токенов, target-модель верифицирует их одним батчем
EAGLE работает на уровне признаков, а не токенов, используя одношаговую экстраполяцию промежуточного представления целевой модели. EAGLE-2 добавляет контекстно-зависимое дерево черновиков. EAGLE-3 предпочитает прямое предсказание токенов с объединением многослойных признаков.
Medusa модифицирует архитектуру модели, добавляя несколько лёгких голов, которые параллельно предсказывают несколько токенов. Medusa-2 достиг ускорения 2,8–3,6×.
При самоспекулятивном декодировании целевая модель генерирует черновик, пропуская некоторые слои, а затем проверяет его полным проходом. Это устраняет необходимость в отдельной черновой модели.
Спекулятивное декодирование сокращает последовательное узкое место, генерируя несколько токенов за один проход. EAGLE, Medusa и самоспекулятивные методы дают ускорение 2–3,6×.
vLLM, SGLang и TensorRT-LLM поддерживают спекулятивное декодирование из коробки. Черновая модель должна использовать тот же токенизатор.
Выбирайте метод, балансирующий сложность развёртывания и выигрыш. Для интерактивных приложений сокращение задержки на несколько миллисекунд оправдывает сложность.
Ограниченное декодирование (constrained decoding) изменяет процесс выбора токенов так, что на каждом шаге допускаются только валидные токены. Это необходимо для структурированного вывода (JSON, грамматики).
Недостаток — дополнительная задержка на принудительное соблюдение ограничений. Современные движки компилируют грамматики и предвычисляют валидные токены, снижая накладные расходы до низких однозначных процентов.
При использовании управляемого декодирования TensorRT-LLM бэкенд XGrammar обеспечивает поддержку JSON-схем и CFG на GPU. Некоторые конфигурации могут переключаться на более медленные бэкенды и вызывать чрезмерные задержки первого запроса. Держите грамматики компактными.
Ограниченное декодирование добавляет задержку, но компиляция грамматик и интеграция масок в GPU-ядро минимизируют накладные расходы.
Для простых JSON-схем современные движки достигают накладных расходов в низкие однозначные проценты. Профилируйте конкретную схему.
Избегайте чрезмерно строгих ограничений. Альтернатива — постобработка выводов, но это не всегда производительно.
Эффективное обслуживание MoE-моделей требует интеллектуальной маршрутизации токенов к экспертам с балансировкой нагрузки.
Иерархическая стратегия маршрутизации: сначала внутриузловой all-to-all через NVSwitch/NVLink, затем межузловой для оставшихся токенов. Двойная буферизация перекрывает коммуникацию с вычислениями.
Коэффициент ёмкости ограничивает число токенов на эксперта. Репликация горячих экспертов распределяет нагрузку.
Capacity factor 1.5 позволяет экспертам обрабатывать +50% токенов перед переливом
Адаптивная маршрутизация корректирует решения гейта в реальном времени на основе текущей нагрузки. Мониторинг утилизации экспертов через Prometheus/Grafana позволяет динамически перенаправлять токены.
Коэффициент ёмкости, репликация горячих экспертов и адаптивная маршрутизация критичны для пропускной способности MoE-инференса. Иерархические all-to-all и двойная буферизация сокращают коммуникационные накладные расходы.
Для MoE настраивайте кластер для оптимизации all-to-all. Подтвердите GPUDirect RDMA для межузловых путей.
Профилируйте утилизацию линков. Держите первый all-to-all внутри стойки (NVLink), между стойками — только остаточные токены.
KV-кэш — один из главных потребителей памяти GPU. Для модели с размером скрытого слоя h, L слоями и длиной последовательности n объём KV-кэша в FP16 составляет:
KV size = 2 × n × h × L × 2 bytes
Для модели с h=8192, L=80, n=128000 (контекст 128K) объём KV-кэша достигает ~320 ГБ — многократно превышает память одной GPU.
Перевод KV-кэша из FP16 в FP8 сокращает память вдвое с минимальной потерей качества. INT4 сокращает в 4×, но требует калибровки.
H2O (Heavy-Hitter Oracle) сохраняет KV-кэш только для «тяжёлых» токенов. Sliding window attention ограничивает внимание фиксированным окном w предыдущих токенов.
vLLM реализует PagedAttention, разбивая KV-кэш на блоки фиксированного размера. SGLang использует RadixAttention с radix-деревом для эффективного поиска общих префиксов.
Квантование KV-кэша (FP8), методы eviction (H2O, sliding window) и кэширование префиксов (PagedAttention, RadixAttention) существенно сокращают потребление памяти и ускоряют декодирование.
LMCache и NIXL обеспечивают кросс-узловое кэширование KV-кэша. Если префикс уже есть на другом узле, LMCache передаёт его через NIXL вместо повторного предзаполнения.
Активно управляйте KV-кэшем. Квантование и eviction — ключевые инструменты для длинных контекстов.
При разделении предзаполнения и декодирования отказ узла декодирования приводит к потере KV-кэша и активного запроса.
Асинхронная репликация KV-кэша на резервные узлы через NIXL. LMCache поддерживает многоуровневое хранение: GPU-память → CPU-память → NVMe.
Для интерактивных сессий система периодически сохраняет контрольные точки: KV-кэш, сгенерированные токены, метаданные запроса.
Оставшиеся узлы берут на себя нагрузку отказавшего. Kubernetes запускает узел-заместитель, инициализируемый из контрольной точки.
Репликация KV-кэша, контрольные точки сессий и плавная деградация — необходимые стратегии для продакшн-развёртываний. Настройте многоуровневый мониторинг здоровья с разумными тайм-аутами.
Используйте health-checks на уровнях GPU (ECC, температура), узла (NVLink, InfiniBand) и процесса (heartbeat).
В многоузловых кластерах с сотнями GPU вероятность отказа узла значительна. Планируйте отказоустойчивость заранее.
Непрерывное батчирование (continuous batching) — ключевой механизм повышения пропускной способности многоузлового инференса.
При статическом батчировании все запросы должны ожидать завершения самого длинного, что приводит к простоям GPU.
Система Orca впервые предложила планирование на уровне итераций: планировщик принимает решения на каждом шаге декодирования, добавляя новые запросы и удаляя завершённые.
vLLM использует PagedAttention для эффективного управления KV-кэшем при непрерывном батчировании. KV-кэш разбивается на блоки фиксированного размера, аналогично страницам виртуальной памяти.
Планирование на уровне итераций кардинально повышает утилизацию GPU. PagedAttention обеспечивает эффективное управление памятью KV-кэша.
vLLM, SGLang и TensorRT-LLM реализуют непрерывное батчирование. vLLM Router обеспечивает интеллектуальную балансировку с учётом KV-кэша.
Для продакшн-инференса используйте движки с поддержкой continuous batching и PagedAttention.
Глава 15 книги Fregly описывает ландшафт многоузлового инференса на 2025 год. С тех пор появились новые данные, позволяющие проверить прогнозы и уточнить цифры.
«Disaggregated prefill and decode is standard practice for LLM inference at scale».
Подтверждено. К 2026 году разделение фаз стало стандартом для крупномасштабного инференса. vLLM Router, NVIDIA Dynamo и llm-d обеспечивают оркестрацию. Kubernetes-native развёртывания через LeaderWorkerSet и Kthena поддерживают prefill/decode disaggregation[reference:0][reference:1].
«NIXL provides high throughput, low latency, and point-to-point data movement».
Подтверждено. NIXL интегрирован в vLLM (NixlConnector), TensorRT-LLM и NVIDIA Dynamo. NixlConnector обеспечивает полностью асинхронные операции send/receive для кросс-процессной передачи KV-кэша[reference:2]. UCX (Unified Communication X) используется как основной транспортный бэкенд[reference:3].
«Speculative decoding reduces the sequential decoding bottleneck by generating and verifying multiple tokens per pass».
Подтверждено. Бенчмарки 2025 года показывают: EAGLE-2 достигает ~1,5–2× на vLLM при batch 1–128[reference:4]. Medusa показывает 2,07–2,78× в зависимости от задачи[reference:5]. EAGLE-3 демонстрирует дальнейшее улучшение за счёт объединения многослойных признаков.
«Capacity factor and expert replication prevent hotspots».
Подтверждено. Исследования 2025 года подтверждают: экспертный параллелизм требует балансировки нагрузки. Expert Capacity (EC) определяется как B × CF / K, где CF — capacity factor[reference:6]. vLLM поддерживает настройку capacity_factor для контроля trade-off между производительностью и точностью[reference:7].
«MPS and MIG raise utilization for multi-tenant inference».
Частично подтверждено. MIG и MPS широко используются для мультитенантного инференса. Однако для многоузлового инференса с разделением фаз MIG менее актуален из-за отключения P2P между экземплярами. MPS чаще применяется на одном узле.
Глава описывает архитектуру и принципы, но оставляет за скобками несколько аспектов, которые проявились в реальной практике.
vLLM Router (релиз декабрь 2025) — высокопроизводительный балансировщик нагрузки на Rust, специально разработанный для vLLM. Он обеспечивает intelligent load balancing с учётом KV-кэша (consistent hashing, power-of-two) и нативную поддержку prefill/decode disaggregation. Роутер управляет маршрутизацией новых запросов к prefill-воркерам, передачей состояния к decode-воркерам и поддерживает как NIXL, так и NCCL-based backends[reference:8]. Встроенный Prometheus endpoint обеспечивает observability[reference:9].
LeaderWorkerSet (LWS) — Kubernetes API для развёртывания наборов Pod'ов, поддерживающих multi-node inference. LWS предоставляет minimal prefill/decode disaggregation с vLLM и SGLang, где каждая роль (prefill/decode) является отдельным child LeaderWorkerSet[reference:10]. Kthena (Volcano) обеспечивает оркестрацию PD disaggregation на Kubernetes для vLLM-Ascend[reference:11].
NixlConnector — высокопроизводительный коннектор для передачи KV-кэша в vLLM. Он использует NIXL для полностью асинхронных операций send/receive. Конфигурация транспорта: UCX как основной бэкенд. При использовании UCX NCCL-переменные (NCCL_IB_HCA, NCCL_SOCKET_IFNAME) не применяются — используются UCX-специфичные переменные[reference:12]. Поддерживаются как CUDA, так и ROCm платформы (через RIXL)[reference:13].
Бенчмарк спекулятивного декодирования для test-time scaling (2025) показывает: training-based методы (Medusa, EAGLE) требуют значительных upfront-инвестиций в обучение. N-gram-based методы (training-free) используют dynamic cache и suffix automaton — они особенно эффективны для repetitive patterns в reasoning chains[reference:14]. Комбинация speculative decoding с MoE может активировать больше экспертов, чем baseline, что снижает выигрыш[reference:15].
Глава 15 книги Fregly — систематический обзор методов многоузлового инференса LLM. Ключевая идея: производительность определяется не только вычислительной мощностью GPU, но и качеством коммуникаций, балансировкой нагрузки и эффективным использованием памяти. Разделение предзаполнения и декодирования, гибридный параллелизм, спекулятивное декодирование, управление KV-кэшем и отказоустойчивость — все эти техники работают в комплексе.
Проверка прогнозов показывает: книга оказалась точной в части распространения технологий. NIXL стал стандартом для передачи KV-кэша. vLLM Router обеспечил intelligent load balancing. Спекулятивное декодирование даёт ускорение 2–3,6×. Kubernetes-native развёртывание через LeaderWorkerSet и Kthena поддерживает prefill/decode disaggregation. Главный вывод остаётся неизменным: многоузловой инференс — это системная задача, требующая координации всех уровней стека.
Источники: Chris Fregly, «AI Systems Performance Engineering» (O'Reilly, 2026), Глава 15 — цитаты приводятся в ограниченном объёме в целях обзора и критического анализа. vLLM Router documentation; NIXL Connector Usage Guide (vLLM); LeaderWorkerSet documentation; Kthena (Volcano); «Scaling Up, Speeding Up: A Benchmark of Speculative Decoding» (arXiv 2509.04474); «A Survey on Accelerated Technologies for Mixture-of-Experts Model Training Systems» (2025); MLPerf Inference v5.0.
This material is a review of Chapter 15 of Chris Fregly, «AI Systems Performance Engineering: Optimizing Model Training and Inference Workloads with GPUs, CUDA, and PyTorch», O'Reilly Media, 2026 (Copyright © 2026 Flux Capacitor, LLC).
Direct quotes from the book are marked with separate blocks labeled «Quote from the book». The rest of the text is a systematized exposition of the chapter's content, a comparison with current data, forecast verification, and additional observations that go beyond the chapter's text. Quotes are provided in limited volume for review and critical analysis purposes.
Chapter 15 of Fregly's book is dedicated to advanced optimization techniques for high-performance multi-node inference of large language models (LLMs) on modern NVIDIA GPUs. Models continue to scale to hundreds of billions and trillions of parameters, and architectures like mixture-of-experts (MoE) make distributed inference a necessity rather than an option.
«LLMs continue to scale up to a massive number of parameters. In particular, the emergence of mixture-of-experts (MoE) LLMs, models that combine many specialist subnetworks ("experts") with a built-in expert-gating mechanism, has pushed model parameter sizes into the hundreds of billions or multiple trillions. And while only a fraction of those parameters are active for a given input, running inference on these enormous model sizes requires distributing the workload across multiple GPUs».
The chapter examines the full spectrum of techniques for multi-node inference: from architectural separation of prefill and decode phases to parallelism strategies, speculative decoding, constrained output, dynamic expert routing, KV cache management, and fault tolerance. The key idea: multi-node inference performance is determined not only by GPU compute power but also by communication quality, load balancing, and efficient memory usage.
Modern LLM inference consists of two fundamentally different phases: prefill and decode. Separating these stages into separate compute pools lets you scale each independently.
During prefill, the model processes the entire input prompt in a single forward pass, forming the KV cache for all prompt tokens. This stage is characterized by high arithmetic intensity and is compute-bound.
During decode, the model performs autoregressive generation, predicting each next token using cached KV representations. This stage is memory-bandwidth-bound.
Prefill and Decode run in parallel, exchanging KV cache over a dedicated channel
Traditionally, inference systems place both stages on the same nodes, causing interference: a long prefill blocks the GPU and delays token generation for other requests. The DistServe system, using separation, reported up to 7.4× goodput growth for requests served within TTFT and TPOT constraints, tightening the latency SLA by up to 12.6×.
NVIDIA's NIXL library minimizes KV cache transfer overhead by automatically choosing NVLink/NVSwitch, RDMA, or host paths based on topology. NIXL integrates with Dynamo, vLLM, and TensorRT-LLM.
NIXL provides direct GPU-to-GPU KV cache transfer between prefill and decode engines
Separating prefill and decode into dedicated GPU pools eliminates interference and allows independent scaling of each phase. NIXL provides efficient KV cache transfer over NVLink, NVSwitch, or RDMA.
For disaggregated inference deployment, Kubernetes with separate deployments for prefill and decode is used. vLLM Router and llm-d provide orchestration.
Monitor NVLink and NIC utilization during KV transfer. The goal is to overlap transfer and compute using separate streams and events.
Efficiently serving massive MoE models requires multiple forms of parallelism due to limited GPU memory.
| Strategy | Split basis | Pros | Cons |
|---|---|---|---|
| Tensor (TP) | Within a layer (weight matrices) | Near-linear speedup of compute-bound layers; overlap all-reduce | Frequent communication; needs NVLink/NVSwitch |
| Pipeline (PP) | Different layers on different GPUs | Memory scaling across layers; microbatching | Pipeline bubbles; harder to implement |
| Expert (EP) | Different MoE experts on different GPUs | Virtually unlimited model size | High all-to-all overhead; imbalance |
| Data (DP) | Full model replication | Near-linear scaling; simplicity | Doesn't reduce latency; multiplies memory |
| Context (CP) | Sequence tokens across GPUs | Speedup for long context | Special attention algorithms; communication |
Expert parallelism (EP) is specific to MoE architectures. Each expert is placed on a separate GPU, and the gating network routes tokens to activated experts. This requires an all-to-all communication pattern at each MoE layer.
To prevent expert overload, a capacity factor is used, typically 1.2–1.5× the average load. Tokens beyond this are routed to a fallback expert.
Each GPU receives only tokens for experts hosted on it
The combination of TP, PP, EP, and DP allows serving models of any size. Expert parallelism is the key to scaling MoE models. Capacity factor and hot expert replication prevent imbalance.
Keep TP groups within an NVLink domain. PP — minimally for model fit. EP — maximize for expert distribution. DP — for throughput.
Profile with Nsight Systems to find imbalance. Use hierarchical all-to-all and double buffering to reduce communication overhead.
One of the fundamental performance problems of LLM inference is the sequential nature of decoding. Speculative decoding solves this by generating multiple tokens per step.
Speculative decoding combines a small, fast "draft" model with a larger "target" model. The draft proposes k tokens, and the target verifies them in one batch.
Draft model proposes k tokens; target model verifies them in one batch
EAGLE operates at the feature level rather than the token level, using one-step extrapolation of the target model's intermediate representation. EAGLE-2 adds a context-dependent draft tree. EAGLE-3 favors direct token prediction with multi-layer feature fusion.
Medusa modifies the model architecture by adding several lightweight heads that predict multiple tokens in parallel. Medusa-2 achieved 2.8–3.6× speedup.
In self-speculative decoding, the target model generates a draft by skipping some layers, then verifies it with a full pass. This eliminates the need for a separate draft model.
Speculative decoding reduces the sequential bottleneck by generating multiple tokens per pass. EAGLE, Medusa, and self-speculative methods provide 2–3.6× speedup.
vLLM, SGLang, and TensorRT-LLM support speculative decoding out of the box. The draft model must use the same tokenizer.
Choose a method that balances deployment complexity and gain. For interactive applications, reducing latency by a few milliseconds justifies the complexity.
Constrained decoding modifies the token selection process so that only valid tokens are allowed at each step. This is necessary for structured output (JSON, grammars).
The downside is extra latency for constraint enforcement. Modern engines compile grammars and precompute valid tokens, reducing overhead to low single-digit percentages.
When using TensorRT-LLM guided decoding, the XGrammar backend provides JSON schema and CFG support on GPU. Some configurations may fall back to slower backends and cause excessive first-request latency. Keep grammars compact.
Constrained decoding adds latency, but grammar compilation and GPU kernel mask integration minimize overhead.
For simple JSON schemas, modern engines achieve low single-digit overhead. Profile your specific schema.
Avoid overly strict constraints. An alternative is output post-processing, but it's not always performant.
Efficient MoE serving requires intelligent token routing to experts with load balancing.
Hierarchical routing strategy: first intra-node all-to-all over NVSwitch/NVLink, then inter-node for remaining tokens. Double buffering overlaps communication with computation.
The capacity factor limits the number of tokens per expert. Hot expert replication distributes load.
Capacity factor 1.5 lets experts process +50% tokens before spillover
Adaptive routing adjusts gating decisions in real time based on current load. Monitoring expert utilization via Prometheus/Grafana allows dynamic token redirection.
Capacity factor, hot expert replication, and adaptive routing are critical for MoE inference throughput. Hierarchical all-to-all and double buffering reduce communication overhead.
For MoE, tune the cluster for all-to-all optimization. Confirm GPUDirect RDMA for inter-node paths.
Profile link utilization. Keep the first all-to-all inside the rack (NVLink); send only residual tokens between racks.
The KV cache is one of the main consumers of GPU memory. For a model with hidden size h, L layers, and sequence length n, the KV cache size in FP16 is:
KV size = 2 × n × h × L × 2 bytes
For a model with h=8192, L=80, n=128000 (128K context), the KV cache size reaches ~320 GB — many times the memory of a single GPU.
Converting the KV cache from FP16 to FP8 halves memory with minimal quality loss. INT4 reduces it by 4× but requires calibration.
H2O (Heavy-Hitter Oracle) keeps KV cache only for "heavy" tokens. Sliding window attention limits attention to a fixed window w of previous tokens.
vLLM implements PagedAttention, breaking the KV cache into fixed-size blocks. SGLang uses RadixAttention with a radix tree for efficient common prefix lookup.
KV cache quantization (FP8), eviction methods (H2O, sliding window), and prefix caching (PagedAttention, RadixAttention) substantially reduce memory usage and accelerate decoding.
LMCache and NIXL provide cross-node KV cache caching. If a prefix already exists on another node, LMCache transfers it via NIXL instead of re-prefilling.
Actively manage the KV cache. Quantization and eviction are key tools for long contexts.
When prefill and decode are separated, a decode node failure loses the KV cache and the active request.
Asynchronous KV cache replication to standby nodes via NIXL. LMCache supports tiered storage: GPU memory → CPU memory → NVMe.
For interactive sessions, the system periodically saves checkpoints: KV cache, generated tokens, request metadata.
Remaining nodes take on the load of the failed node. Kubernetes starts a replacement node, initialized from a checkpoint.
KV cache replication, session checkpoints, and graceful degradation are necessary strategies for production deployments. Configure multi-level health monitoring with sensible timeouts.
Use health checks at the GPU (ECC, temperature), node (NVLink, InfiniBand), and process (heartbeat) levels.
In multi-node clusters with hundreds of GPUs, the probability of a node failure is significant. Plan for fault tolerance in advance.
Continuous batching is a key mechanism for increasing multi-node inference throughput.
With static batching, all requests must wait for the longest to finish, causing GPU idle time.
The Orca system first proposed iteration-level scheduling: the scheduler makes decisions at each decoding step, adding new requests and removing completed ones.
vLLM uses PagedAttention for efficient KV cache management under continuous batching. The KV cache is split into fixed-size blocks, similar to OS virtual memory pages.
Iteration-level scheduling dramatically improves GPU utilization. PagedAttention provides efficient KV cache memory management.
vLLM, SGLang, and TensorRT-LLM implement continuous batching. vLLM Router provides intelligent load balancing with KV cache awareness.
For production inference, use engines with continuous batching and PagedAttention support.
Chapter 15 of Fregly's book describes the multi-node inference landscape as of 2025. Since then, new data has emerged to verify forecasts and clarify figures.
«Disaggregated prefill and decode is standard practice for LLM inference at scale».
Confirmed. By 2026, phase separation became standard for large-scale inference. vLLM Router, NVIDIA Dynamo, and llm-d provide orchestration. Kubernetes-native deployments via LeaderWorkerSet and Kthena support prefill/decode disaggregation[reference:16][reference:17].
«NIXL provides high throughput, low latency, and point-to-point data movement».
Confirmed. NIXL is integrated into vLLM (NixlConnector), TensorRT-LLM, and NVIDIA Dynamo. NixlConnector provides fully asynchronous send/receive operations for cross-process KV cache transfer[reference:18]. UCX (Unified Communication X) is used as the primary transport backend[reference:19].
«Speculative decoding reduces the sequential decoding bottleneck by generating and verifying multiple tokens per pass».
Confirmed. 2025 benchmarks show: EAGLE-2 achieves ~1.5–2× on vLLM at batch 1–128[reference:20]. Medusa shows 2.07–2.78× depending on the task[reference:21]. EAGLE-3 demonstrates further improvement through multi-layer feature fusion.
«Capacity factor and expert replication prevent hotspots».
Confirmed. 2025 research confirms: expert parallelism requires load balancing. Expert Capacity (EC) is defined as B × CF / K, where CF is the capacity factor[reference:22]. vLLM supports capacity_factor tuning to control the performance-accuracy trade-off[reference:23].
«MPS and MIG raise utilization for multi-tenant inference».
Partially confirmed. MIG and MPS are widely used for multi-tenant inference. However, for multi-node inference with phase separation, MIG is less relevant due to P2P being disabled between instances. MPS is more commonly used on a single node.
The chapter describes the architecture and principles but leaves out several aspects that emerged in real-world practice.
vLLM Router (December 2025 release) is a high-performance Rust-based load balancer specifically designed for vLLM. It provides intelligent load balancing with KV cache awareness (consistent hashing, power-of-two) and native support for prefill/decode disaggregation. The router manages routing of new requests to prefill workers, transfers state to decode workers, and supports both NIXL and NCCL-based backends[reference:24]. A built-in Prometheus endpoint provides observability[reference:25].
LeaderWorkerSet (LWS) is a Kubernetes API for deploying sets of Pods supporting multi-node inference. LWS provides minimal prefill/decode disaggregation with vLLM and SGLang, where each role (prefill/decode) is a separate child LeaderWorkerSet[reference:26]. Kthena (Volcano) provides PD disaggregation orchestration on Kubernetes for vLLM-Ascend[reference:27].
NixlConnector is a high-performance connector for KV cache transfer in vLLM. It uses NIXL for fully asynchronous send/receive operations. Transport configuration: UCX as the primary backend. When using UCX, NCCL variables (NCCL_IB_HCA, NCCL_SOCKET_IFNAME) do not apply — UCX-specific variables are used[reference:28]. Both CUDA and ROCm platforms are supported (via RIXL)[reference:29].
A 2025 benchmark of speculative decoding for test-time scaling shows: training-based methods (Medusa, EAGLE) require significant upfront training investment. N-gram-based methods (training-free) use a dynamic cache and suffix automaton — they are particularly effective for repetitive patterns in reasoning chains[reference:30]. Combining speculative decoding with MoE can activate more experts than baseline, diminishing the gain[reference:31].
Chapter 15 of Fregly's book is a systematic overview of multi-node LLM inference techniques. The key idea: performance is determined not only by GPU compute power but also by communication quality, load balancing, and efficient memory usage. Prefill/decode disaggregation, hybrid parallelism, speculative decoding, KV cache management, and fault tolerance all work together.
Forecast verification shows: the book proved accurate in terms of technology adoption. NIXL became the standard for KV cache transfer. vLLM Router provided intelligent load balancing. Speculative decoding provides 2–3.6× speedup. Kubernetes-native deployment via LeaderWorkerSet and Kthena supports prefill/decode disaggregation. The main takeaway remains unchanged: multi-node inference is a systems problem requiring coordination across all stack levels.
Sources: Chris Fregly, «AI Systems Performance Engineering» (O'Reilly, 2026), Chapter 15 — quotes provided in limited volume for review and critical analysis purposes. vLLM Router documentation; NIXL Connector Usage Guide (vLLM); LeaderWorkerSet documentation; Kthena (Volcano); «Scaling Up, Speeding Up: A Benchmark of Speculative Decoding» (arXiv 2509.04474); «A Survey on Accelerated Technologies for Mixture-of-Experts Model Training Systems» (2025); MLPerf Inference v5.0.