Настоящий материал представляет собой обзор четвёртой главы книги 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).
Прямые цитаты из книги выделены отдельными блоками с пометкой «Цитата из книги». Остальной текст — систематизированное изложение содержания главы, сопоставление с актуальными данными о платформе, проверка прогнозов по открытым источникам, а также дополнительные замечания, выходящие за пределы текста главы. Цитаты приводятся в ограниченном объёме в целях обзора и критического анализа.
Четвёртая глава книги Fregly посвящена настройке распределённых сетевых коммуникаций — той части производительности AI-систем, которая становится определяющей при выходе за пределы одного узла. В главе рассматриваются технологии Magnum IO (NCCL, GPUDirect RDMA, GDS), стратегии перекрытия вычислений и связи, многоузловые ловушки, алгоритмы коллективных операций и эволюция от NCCL к NIXL для дизагрегированного инференса.
«В современных AI-системах потребность в бесшовном и низколатентном перемещении данных между GPU, хранилищами и сетевыми интерфейсами является обязательным условием… В крупномасштабных системах даже самые быстрые GPU могут быть ограничены неэффективной коммуникацией и передачей данных из памяти и с диска».
Глава начинается с фундаментального наблюдения: при масштабировании за пределы одного узла сетевая коммуникация превращается из вспомогательного механизма в критический путь производительности. Если на одном GPU узкое место обычно связано с вычислениями или памятью, то на кластере из тысяч ускорителей доминирующим фактором становится то, как быстро данные могут быть переданы между ними.
Ключевая идея главы — рассматривать коммуникации не как «инфраструктурную деталь», а как полноценный объект оптимизации наравне с ядрами CUDA. Оптимизация сети может дать больший эффект, чем оптимизация вычислений, — особенно на масштабе. Именно поэтому в главе подробно разбираются NCCL, NIXL, SHARP, RDMA и стратегии перекрытия.
«Основная идея — обеспечить, чтобы передача данных происходила одновременно с текущими вычислениями… Современные фреймворки, такие как PyTorch, поддерживают асинхронные операции, так что коллективная коммуникация (например, all-reduce градиентов) может выполняться параллельно с вычислительными задачами. Это уменьшает время простоя GPU».
В главе принцип перекрытия описывается как фундамент всей оптимизации распределённого обучения. Если GPU вынужден ждать завершения all-reduce градиентов, прежде чем начать следующий шаг, то каждый шаг занимает сумму времён вычислений и коммуникаций. Если же коммуникация запускается асинхронно и перекрывается с вычислениями, время шага приближается к максимуму из этих двух величин, а не к их сумме.
PyTorch DistributedDataParallel реализует это через механизм wait-free backpropagation: градиенты разбиваются на bucket’ы, и по мере готовности каждого bucket’а запускается асинхронный all-reduce в отдельном CUDA-потоке. Основной поток продолжает вычислять градиенты для следующих слоёв. Размер bucket’а по умолчанию — 25 МиБ — компромисс между утилизацией сети и задержкой старта коммуникации.
Практический эффект, отмечаемый в главе: при правильной настройке большая часть коммуникации оказывается скрыта за вычислениями. Видимый прирост производительности для типичной модели — 20–30% времени итерации, а на больших моделях — существенно больше.
Пока считаются градиенты следующего слоя, сеть передаёт предыдущие
В главе выделяются три техники усиления перекрытия:
Неявная синхронизация убивает перекрытие. Вызов .item() на тензоре, torch.cuda.synchronize() без необходимости, print() с GPU-тензором — всё это заставляет GPU дождаться завершения всех асинхронных операций, включая идущий в фоне all-reduce. Один такой вызов в середине итерации может свести на нет всю оптимизацию DDP.
Перекрытие коммуникаций с вычислениями — основной принцип оптимизации распределённого обучения. DDP реализует это через bucket’ы и асинхронные all-reduce в отдельном CUDA-потоке.
Накопление градиентов, сжатие данных, увеличение размера батча. Каждая из них сокращает частоту или объём коммуникаций, увеличивая окно перекрытия.
Любая неявная синхронизация в середине итерации (например, .item() или print() с GPU-тензором) разрушает перекрытие и добавляет всё время коммуникации к времени шага. Профилирование через Nsight Systems показывает, есть ли перекрытие — по чередованию compute и NCCL-ядер в таймлайне.
«Достижение перекрытия принципиально опирается на асинхронное исполнение. GPU поддерживают множество потоков (streams), или очередей операций, которые могут выполняться параллельно или перекрываться, если нацелены на разные ресурсы… PyTorch DistributedDataParallel автоматически устанавливает хуки на backward pass, так что каждый bucket градиентов инициирует асинхронный all-reduce NCCL в выделенном коммуникационном CUDA-потоке, пока поток по умолчанию продолжает вычислять градиенты для последующих слоёв».
В главе подчёркивается, что перекрытие невозможно без асинхронного исполнения. CUDA-потоки предоставляют механизм, позволяющий разным операциям выполняться параллельно. Ключевое требование — чтобы коммуникационные операции (NCCL) использовали nonblocking-вызовы, возвращающие управление немедленно. Это позволяет основному потоку продолжать вычисления, пока NCCL работает в фоне.
В PyTorch DDP этот механизм скрыт от пользователя, но важно понимать принцип: каждый bucket градиентов отправляется в отдельный коммуникационный поток, а основной поток продолжает backward. Если пользователь случайно вызовет синхронизацию (например, чтобы получить значение тензора), всё перекрытие разрушается.
Практическое следствие: для сохранения перекрытия следует избегать любых неявных синхронизаций в горячем цикле. Единственная синхронизация — в самом конце итерации, когда нужно дождаться завершения всей асинхронной работы перед переходом к следующему шагу.
CUDA-потоки — механизм перекрытия. NCCL использует nonblocking-вызовы, позволяющие основному потоку продолжать вычисления.
Любая явная или неявная синхронизация в середине итерации (.item(), print(), synchronize()) разрушает перекрытие. Синхронизация допускается только в конце итерации.
«Как отмечалось, выполнение большего объёма работы за шаг коммуникации может увеличить перекрытие и эффективность. Накопление градиентов во время обучения — одна из таких техник. Вместо all-reduce градиентов для каждого мини-батча вы накапливаете градиенты за несколько мини-батчей, суммируете их локально и выполняете один all-reduce».
«Другой подход к сокращению объёма коммуникаций — сжатие или квантование обмениваемых данных… Чрезвычайным случаем является разреживание. При использовании разреженности вы отправляете только часть градиентов».
В главе сокращение частоты и объёма коммуникаций рассматривается как второй по важности принцип после перекрытия. Накопление градиентов сокращает количество all-reduce-операций линейно с числом шагов накопления. Сжатие и разреживание сокращают объём данных, передаваемых за одну операцию.
Отдельно оговаривается компромисс bucket’ов: очень большие bucket’ы максимизируют утилизацию полосы пропускания, но задерживают старт коммуникации. Очень маленькие bucket’ы стартуют раньше, но порождают больше накладных расходов на вызов NCCL. Размер по умолчанию в PyTorch — 25 МиБ — эмпирический баланс, но для конкретной модели он может потребовать тюнинга.
Практическое следствие: если модель имеет очень большие слои, увеличение bucket’а снижает накладные расходы. Если модель имеет много мелких слоёв, уменьшение bucket’а позволяет раньше начать коммуникацию.
Очень большие bucket’ы максимизируют утилизацию пропускной способности, но задерживают старт коммуникации, так как нужно дождаться накопления градиентов. Очень маленькие bucket’ы стартуют раньше, но создают больше вызовов NCCL с накладными расходами. Оптимальный размер зависит от модели и топологии.
Сокращение частоты (накопление градиентов) и объёма (сжатие, разреживание) коммуникаций — второй принцип оптимизации после перекрытия.
Размер bucket’а — баланс между утилизацией сети и задержкой старта коммуникации. Для больших слоёв выгоднее большие bucket’ы, для многих мелких слоёв — маленькие.
«Magnum IO, сквозная платформа ускорения ввода-вывода NVIDIA, объединяет ряд технологий для ускорения перемещения, доступа и управления данными между GPU, CPU, хранилищами и сетевыми интерфейсами. Ключевые компоненты Magnum IO включают GPUDirect Storage, GPUDirect RDMA, NCCL, NVSHMEM, SHARP и средства управления вводом-выводом, такие как NVIDIA NetQ и Unified Fabric Manager».
«RDMA позволяет сетевому адаптеру напрямую читать и писать память другого узла, минуя ядро операционной системы и CPU… GPUDirect RDMA позволяет RDMA-способному NIC выполнять DMA напрямую в память GPU и из неё, минуя хост-CPU и системную RAM».
В главе RDMA описывается как фундаментальная технология для многоузловых коммуникаций. Ключевое отличие от TCP/IP: RDMA позволяет сетевому адаптеру напрямую обращаться к памяти удалённого узла без участия CPU и без копирования через системную RAM. GPUDirect RDMA расширяет это на память GPU — NIC может писать напрямую в HBM удалённого GPU.
Практический эффект — снижение задержки с 20–50 микросекунд (TCP/IP) до 1–5 микросекунд (RDMA) и рост пропускной способности с ~100 Гбит/с до 400–800 Гбит/с на порт. На масштабе тысяч GPU это даёт кратный выигрыш в синхронизации градиентов.
Отдельно в главе отмечается, что в контейнерных средах (Docker, Kubernetes) NCCL может не получить доступ к устройствам InfiniBand и тихо переключиться на TCP-сокеты. Ошибок нет, обучение идёт — но пропускная способность падает в десятки раз. Это одна из самых коварных проблем, поскольку не вызывает сбоев.
TCP/IP прогоняет каждый байт через CPU и system RAM, RDMA — напрямую
Молчаливый откат RDMA на TCP. В контейнерных средах (Docker, Kubernetes) NCCL может не получить доступ к устройствам InfiniBand и тихо переключиться на TCP-сокеты. Ошибок нет, обучение идёт — но пропускная способность на одно GPU-соединение падает с ~100 ГБ/с (RDMA/InfiniBand) до ~2 ГБ/с (TCP через Ethernet). Для диагностики используется NCCL_DEBUG=INFO и проверка модуля nvidia_peermem.
# Проверить, загружен ли модуль peermem
lsmod | grep nvidia_peermem
# Запустить NCCL с отладкой и убедиться, что используется IB, а не Socket
NCCL_DEBUG=INFO python train.py 2>&1 | grep -E "NET|IB|Socket"
# Проверить инициализацию в dmesg
dmesg | grep -i peer
RDMA и GPUDirect RDMA — фундаментальные технологии для многоузловых коммуникаций. Снижение задержки в 10× и рост пропускной способности в 8× относительно TCP/IP (на одно соединение).
В Docker и Kubernetes NCCL может тихо переключиться на TCP, если нет доступа к InfiniBand-устройствам. Ошибок нет — только падение производительности в десятки раз на соединение. Требуется явная проверка через NCCL_DEBUG=INFO.
«Масштабирование обучения на несколько узлов в кластере вводит новый класс ловушек… Использование CPU-привязанного бэкенда Gloo вместо NCCL. PyTorch поддерживает несколько бэкендов для коммуникации. Для multi-GPU обучения NCCL — предпочтительный бэкенд для NVIDIA GPU, но есть также fallback-бэкенд Gloo, использующий CPU и TCP-сокеты».
«Несоответствие версий NCCL. Если вы запускаете встроенный в PyTorch NCCL против другой версии системного libnccl, вы можете зависнуть. Или, что хуже, тихо откатиться на более медленную реализацию».
В главе перечисляются шесть типовых ловушек многоузлового обучения: неправильный бэкенд (Gloo вместо NCCL), несоответствие версий NCCL, исчерпание TCP-портов, недостаточная пропускная способность сети, отстающие узлы и фрагментация памяти GPU под UCX/RDMA.
Каждая ловушка имеет характерный признак. Gloo вместо NCCL даёт падение производительности в 10–50 раз без каких-либо ошибок. Несовпадение версий NCCL приводит к зависаниям или тихому откату на медленную реализацию. Исчерпание TCP-портов проявляется зависанием handshake без явной ошибки. Отстающий узел тормозит весь кластер, поскольку синхронное обучение определяется самым медленным участником.
Практическое следствие: для диагностики каждой ловушки в главе предлагается конкретный инструмент. Для бэкенда — torch.distributed.get_backend(). Для версий NCCL — torch.cuda.nccl.version(). Для отстающих узлов — dist.monitored_barrier с таймаутом. Для сети — мониторинг через nvidia-smi dmon или ibstat.
Многоузловое обучение имеет шесть типовых ловушек, большинство из которых не вызывают сбоев, а тихо замедляют работу. Диагностика требует явных проверок.
Для бэкенда — get_backend(). Для версий — nccl.version(). Для отстающих — monitored_barrier. Для сети — nvidia-smi dmon или ibstat.
«NVIDIA NCCL — это библиотека коммуникации «многие-ко-многим» для операций, называемых коллективами, используемых группами GPU для обмена данными. NCCL лежит в основе большинства multi-GPU обучающих нагрузок в экосистеме NVIDIA… NCCL обеспечивает оптимизированные реализации коллективных операций, таких как all-reduce, all-gather, broadcast и reduce-scatter, которые масштабируются от нескольких GPU до тысяч и, в будущем, миллионов».
В главе NCCL описывается как фундамент распределённого обучения в экосистеме NVIDIA. Ключевая особенность NCCL — автоматический выбор оптимального пути передачи данных на основе физической топологии. Библиотека сама определяет, использовать ли NVLink, PCIe, InfiniBand или TCP, и строит соответствующую коммуникационную схему.
Дополнением к NCCL в главе представлен NIXL (NVIDIA Inference Xfer Library) — библиотека для точечных передач, оптимизированная для инференса. Если NCCL решает задачу «многие-ко-многим» (all-reduce градиентов в обучении), то NIXL решает задачу «один-к-одному» (передача KV-кэша между prefill и decode в дизагрегированном инференсе).
Практическое следствие: для обучения используется NCCL, для инференса с передачей KV-кэша — NIXL. Обе библиотеки дополняют друг друга, а не заменяют.
NCCL — основа коллективных операций в распределённом обучении. NIXL дополняет его для точечных передач в инференсе.
Для обучения — NCCL. Для передачи KV-кэша в дизагрегированном инференсе — NIXL. Библиотеки дополняют друг друга.
«Внутри NCCL может применять различные алгоритмы коммуникации в зависимости от размера данных, количества GPU и топологии. Основные алгоритмы, которые NCCL использует для коллективов: Ring, Tree, CollNet и Parallel Aggregated Tree (PAT), среди прочих».
В главе разбираются четыре основных алгоритма NCCL. Ring обеспечивает идеальную балансировку нагрузки (каждая ссылка передаёт одинаковый объём), но задержка растёт линейно с числом GPU. Tree сокращает за O(log N) шагов, что лучше для маленьких сообщений, но не все ссылки загружены равномерно. CollNet строит двухуровневое дерево: локальное внутри узла (NVLink) и глобальное между узлами (RDMA). PAT — гибрид кольца и дерева, разбивающий сообщение на фрагменты с перекрытием.
Практическое следствие: NCCL выбирает алгоритм автоматически на основе размера сообщения и топологии. Для отладки можно переопределить через NCCL_ALGO, но в продакшене автоматический выбор обычно оптимален.
Выбор алгоритма зависит от размера сообщения и топологии
NCCL_ALGO=Ring,Tree,PAT. Это полезно для отладки, но в продакшене автоматический выбор обычно оптимальнее.
NCCL использует четыре основных алгоритма: Ring (балансировка, высокая задержка), Tree (O(log N), малые сообщения), CollNet (двухуровневое дерево), PAT (гибрид).
NCCL выбирает алгоритм автоматически. Для отладки можно переопределить через NCCL_ALGO, но в продакшене автоматический выбор обычно оптимален.
«Топологическая осведомлённость играет главную роль в производительности NCCL. NCCL определяет, как GPU физически соединены, и соответственно оптимизирует свою коммуникационную схему. Например, в системе с полностью соединёнными NVLink и NVSwitch каждый GPU будет взаимодействовать с каждым другим, используя эти высокоскоростные интерконнекты».
В главе топологическая осведомлённость описывается как одна из главных причин, по которой NCCL эффективен. Библиотека анализирует физическую схему соединений GPU и строит иерархический паттерн коммуникации. Если GPU 0–1 соединены через NVLink, а GPU 2–3 — через другой NVLink, но между парами только PCIe, NCCL сначала выполнит сокращение внутри пар (быстрый NVLink), затем обмен между парами через PCIe (медленный, но только часть данных).
Практическое следствие: для диагностики проблем масштабирования используется nvidia-smi topo -n. Если масштабирование хуже ожидаемого, первая гипотеза — трафик идёт по медленным путям, например, через PCIe вместо NVLink или через Ethernet вместо InfiniBand.
От быстрого локального NVLink до медленного TCP — выбор по топологии
nvidia-smi topo -n. Если масштабирование хуже ожидаемого — первая гипотеза: трафик идёт по медленным путям.NCCL автоматически определяет топологию и строит иерархический паттерн коммуникации. Это одна из главных причин его эффективности.
Для диагностики — nvidia-smi topo -n. Если масштабирование хуже ожидаемого, проверяется, не идёт ли трафик по медленным путям (PCIe вместо NVLink, Ethernet вместо InfiniBand).
«Хотя NCCL абстрагирует большинство низкоуровневых деталей, то, как мы используем NCCL в коде, всё ещё может влиять на производительность. Кроме того, NCCL имеет множество переменных окружения для управления своим поведением. Неправильная настройка этих переменных может ухудшить производительность или даже вызвать зависания».
В главе разбираются четыре ключевые ловушки, связанные с NCCL: слишком частое создание коммуникаторов, создание и уничтожение коммуникаторов на каждой итерации, отключение функций через переменные окружения без последующего включения и игнорирование предупреждений NCCL.
Создание NCCL-коммуникатора — дорогостоящая операция. Если код инициализирует и уничтожает коммуникатор на каждой итерации, накладные расходы могут превышать время самого обучения. Правильный подход — инициализировать один раз вне цикла.
Отдельно в главе отмечается, что переменные окружения NCCL следует оставлять на значениях по умолчанию, если нет конкретной причины их менять. Некоторые переменные, такие как NCCL_P2P_DISABLE или NCCL_SHM_DISABLE, могут использоваться для отладки, но забытые включёнными в продакшене они заметно снижают производительность.
Создание NCCL-коммуникатора — дорогая операция. Инициализация должна происходить один раз вне цикла обучения.
Переменные окружения NCCL оставляются на значениях по умолчанию, если нет конкретной причины. Отладочные переменные (NCCL_P2P_DISABLE, NCCL_SHM_DISABLE) должны быть возвращены в исходное состояние после отладки.
«SHARP — это InfiniBand-технология внутрисетевой редукции, используемая с коммутаторами Quantum-класса через плагин NCCL-SHARP… В практических терминах SHARP позволяет таким коллективам, как all-reduce, частично вычисляться сетевой фабрикой. Когда данные от нескольких GPU поступают в коммутатор, он выполняет редукцию/агрегацию и распространяет частично редуцированный результат».
В главе SHARP описывается как технология, выносящая часть коллективной операции в сеть. Вместо того чтобы каждый GPU получал данные от всех остальных и сам выполнял редукцию, коммутатор сам агрегирует частичные результаты. Это снижает и нагрузку на SM, и объём трафика.
Практический эффект, отмечаемый в главе: NVIDIA сообщает о 2–5-кратном ускорении all-reduce на больших масштабах. Выигрыш зависит от размера кластера: на 2–4 GPU он незаметен, на 72+ GPU внутри стойки — существенен. SHARP — одна из ключевых инноваций, полученных NVIDIA в результате приобретения Mellanox.
Также в главе отмечаются персистентные пользовательские буферы NCCL (user buffer registration), позволяющие коллективам работать напрямую с тензорами без промежуточного копирования. Это особенно важно для достижения наилучших путей через SHARP как на NVLink (NVLS), так и на InfiniBand.
SHARP выносит редукцию в сеть, освобождая SM и снижая трафик. NVIDIA сообщает о 2–5-кратном ускорении all-reduce на больших масштабах.
NCCL поддерживает регистрацию пользовательских буферов, позволяющую коллективам работать напрямую с тензорами. Это критично для достижения наилучших путей через SHARP.
SHARP включается через NCCL-SHARP плагин. Выигрыш зависит от масштаба: на 2–4 GPU незаметен, на 72+ GPU существенен.
«NVIDIA NIXL — это открытая библиотека коммуникации «точка-точка» с высокой пропускной способностью и низкой задержкой, выпущенная в начале 2025 года. NIXL была разработана специально для ускорения крупномасштабного распределённого и дизагрегированного инференса LLM».
«NIXL — ключевой компонент открытого движка инференса NVIDIA Dynamo. NIXL оптимизирует передачи «один-к-одному» и «один-к-немногим», такие как перемещение KV-кэша между дизагрегированными стадиями, с минимальной задержкой и накладными расходами. Он дополняет NCCL, который в основном используется для коллективов «многие-ко-многим».
В главе NIXL описывается как эволюционный шаг для инференса. Традиционный NCCL оптимизирован для коллективных операций (all-reduce градиентов), но инференс требует другого паттерна: передачи KV-кэша между конкретными GPU в дизагрегированной архитектуре prefill-decode.
NIXL обеспечивает точечные передачи с минимальной задержкой и автоматически выбирает транспорт — NVLink для intra-node, InfiniBand/RDMA для inter-node, GPUDirect Storage для дисковых операций. Асинхронный API с callback’ами позволяет перекрывать передачу с вычислениями.
Практическое следствие: в дизагрегированном инференсе prefill выполняется на одних GPU, decode — на других, а KV-кэш передаётся через NIXL. Это позволяет независимо масштабировать prefill и decode, а также оптимизировать каждый этап под свои характеристики.
Коллективная синхронизация против точечной передачи KV-кэша
send/recv тоже доступен для инференса, но накладные расходы выше. Для крупномасштабных развёртываний NIXL обеспечивает более низкую хвостовую задержку, что критично для реального времени.
NIXL — библиотека для точечных передач в дизагрегированном инференсе. Дополняет NCCL, а не заменяет его.
В дизагрегированном prefill-decode KV-кэш передаётся через NIXL. Это позволяет независимо масштабировать prefill и decode.
«NCCL разработан для максимизации коллективной пропускной способности через множество GPU как внутри одного хоста, так и между узлами… NIXL строится на принципах высокой производительности NCCL и оркестрирует асинхронные, аппаратно-агностические точечные передачи между GPU, CPU и устройствами хранения. NIXL был разработан для крупномасштабных нагрузок распределённого инференса, включая сверхбыстрые передачи KV-кэша».
В главе проводится систематическое сравнение NCCL и NIXL. NCCL ориентирован на коллективы «многие-ко-многим» с синхронной семантикой (все участники должны достичь вызова). NIXL ориентирован на точечные передачи с асинхронной семантикой (один инициатор, один или несколько получателей).
NCCL используется в обучении для all-reduce градиентов. NIXL используется в инференсе для передачи KV-кэша и model shards. NCCL оптимизирован для малых и средних тензоров, NIXL — для больших блоков данных (сотни мегабайт). NCCL интегрирован в PyTorch DDP, Horovod и другие фреймворки обучения. NIXL интегрирован в NVIDIA Dynamo, vLLM через LMCache и другие inference-движки.
Практическое следствие: для обучения — NCCL, для инференса — NIXL. Обе библиотеки могут использоваться в одном приложении, если оно включает и обучение, и инференс.
NCCL — коллективы «многие-ко-многим» для обучения. NIXL — точечные передачи для инференса. Библиотеки дополняют друг друга.
Для обучения — NCCL. Для инференса с передачей KV-кэша — NIXL. Обе библиотеки могут использоваться в одном приложении.
Книга Fregly писалась в 2025 году, когда NCCL и NIXL были актуальными инструментами. С тех пор многое изменилось. Ниже представлено сопоставление прогнозов главы с открытыми данными.
«RDMA позволяет сетевому адаптеру напрямую читать и писать память другого узла, минуя ядро операционной системы и CPU».
Подтверждено. RDMA и GPUDirect RDMA остаются основой многоузловых коммуникаций в 2025–2026 годах. NVIDIA продолжает развивать эту технологию: ConnectX-8 обеспечивает 800 Гбит/с на порт, а BlueField-4 DPU разгружает сетевые задачи ещё эффективнее. Для NVL72 и последующих платформ GPUDirect RDMA критичен для передачи KV-кэша между стойками.
«NVIDIA сообщает о 2–5-кратном ускорении all-reduce на больших масштабах с использованием SHARP».
Подтверждено. NVIDIA подтверждает 2–5-кратное ускорение на больших масштабах. Внутри одного NVL72 (72 GPU в едином NVLink-домене) SHARP-ускорение особенно заметно, поскольку домен достаточно велик, чтобы агрегация в сети давала эффект.
Отдельно уточняется контекст по «выходу за пределы стойки»: при пересечении границ NVLink-домена агрегированная пропускная способность на стойку (суммарная по 18 узлам, а не на один GPU) падает с оценки в ~800–900 ГБ/с (внутридоменная NVLink/NVSwitch-фабрика) до 100–200 ГБ/с (InfiniBand между стойками), если job scheduling не учитывает топологию. Это оценочные числа на уровне стойки, а не на уровне отдельного GPU; на одно GPU-соединение соответствующие значения — примерно 50–100 ГБ/с и 12–25 ГБ/с. Точные цифры зависят от числа NIC на узел и типа фабрики.
«NIXL была разработана специально для ускорения крупномасштабного распределённого и дизагрегированного инференса LLM».
Подтверждено. NIXL интегрирован в NVIDIA Dynamo, vLLM через LMCache и другие inference-движки. Дизагрегация prefill и decode стала стандартом для высокопроизводительного LLM-инференса. NVIDIA Dynamo обеспечивает до 30-кратного увеличения пропускной способности для моделей с ~680 млрд параметров на NVL72.
«В контейнерных средах (Docker, Kubernetes) NCCL может не получить доступ к устройствам InfiniBand и тихо переключиться на TCP-сокеты».
Подтверждено с корректировкой. Проблема остаётся актуальной, но современные версии NVIDIA Container Toolkit и Kubernetes GPU Operator научились автоматически пробрасывать InfiniBand-устройства в контейнеры. Тем не менее, для надёжности рекомендуется явная проверка NCCL_DEBUG=INFO и модуля nvidia_peermem. Численный эффект (на одно GPU-соединение) — падение с ~100 ГБ/с RDMA до ~2 ГБ/с TCP, как указано в разделе IV; это отличается от агрегированных чисел на уровне стойки.
«Отдельные стадии prefill и decode выполняются на разных GPU, что позволяет независимо масштабировать и оптимизировать каждый этап».
Подтверждено и опережает график. Дизагрегация prefill и decode стала стандартом в 2025 году. OpenAI, Meta, xAI, NVIDIA, Amazon — все крупные игроки используют эту архитектуру. DistServe показал 7,4-кратное увеличение goodput при строгих latency SLO. vLLM, SGLang, NVIDIA Dynamo поддерживают дизагрегацию из коробки.
Глава описывает технологии и принципы, но оставляет за скобками несколько аспектов, которые проявились в реальной эксплуатации.
В главе упоминаются ConnectX-8 и BlueField-4 как перспективные разработки. К 2026 году ConnectX-8 (800 Гбит/с) и BlueField-4 DPU стали стандартом для новых развёртываний. ConnectX-8 обеспечивает удвоенную пропускную способность по сравнению с предыдущим поколением, что критично для дизагрегированного инференса с большими KV-кэшами.
В главе упоминается, что NVLink Switch System может объединять до 576 GPU в один домен. С выходом Vera Rubin NVLink 6 удваивает пропускную способность до 3,6 ТБ/с на GPU, а домен расширяется до ещё большего числа GPU. Это позволяет использовать TP и EP через ещё большее число GPU без выхода за пределы NVLink-фабрики.
В главе упоминается NVIDIA Dynamo как пример использования NIXL. К 2026 году Dynamo стал стандартом для развёртывания дизагрегированного инференса в Kubernetes. vLLM, SGLang, TensorRT-LLM — все поддерживают интеграцию с NIXL через LMCache или собственные коннекторы.
В главе PDL не упоминается. Это технология, появившаяся в Hopper и развитая в Blackwell, позволяющая одному ядру сигнализировать о завершении своего пролога и запускать зависимое ядро до полного завершения первого. PDL дополняет перекрытие коммуникаций с вычислениями, сокращая время между последовательными вызовами ядер.
В главе не упоминается интеграция Groq LPU в платформу Vera Rubin. Это признание того, что одного типа ускорителя недостаточно для reasoning-нагрузок, где test-time scaling многократно увеличивает inference-нагрузку. Гетерогенные вычисления становятся новым трендом, и это влияет на стратегии коммуникаций.
.item(), print() с GPU-тензором, synchronize() — всё это заставляет GPU ждать завершения всех асинхронных операций.NCCL_DEBUG=INFO и nvidia_peermem. Падение — на одно соединение: с ~100 ГБ/с до ~2 ГБ/с.nvidia-smi topo -n.Четвёртая глава книги Fregly — систематический разбор технологий и принципов распределённых сетевых коммуникаций. Ключевая идея: коммуникации — не «инфраструктурная деталь», а объект оптимизации первого класса. По мере роста кластеров до десятков тысяч GPU сетевая коммуникация становится доминирующим фактором производительности. Инженер, понимающий принципы перекрытия, топологии и алгоритмов коллективов, может достичь кратного выигрыша даже без замены железа.
Проверка прогнозов показывает: книга оказалась точной в своих предсказаниях. RDMA, SHARP, NIXL и дизагрегация prefill/decode — все эти технологии стали стандартом. Главный вывод остаётся неизменным: инвестиции в фундаментальные принципы обеспечивают адаптацию к любому поколению оборудования.
Источники: Chris Fregly, «AI Systems Performance Engineering» (O'Reilly, 2026), Глава 4 — цитаты приводятся в ограниченном объёме в целях обзора и критического анализа. Документация NVIDIA NCCL, NIXL, SHARP, GPUDirect RDMA; NVIDIA Dynamo; vLLM; SGLang; MLPerf Training/Inference v5.0; DistServe.
This material is a review of Chapter 4 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 about the platform, verification of forecasts against open sources, and additional observations that go beyond the chapter's text. Quotes are provided in limited volume for review and critical analysis purposes.
Chapter 4 of Fregly's book is dedicated to tuning distributed networking communication — the part of AI system performance that becomes decisive beyond a single node. The chapter examines Magnum IO technologies (NCCL, GPUDirect RDMA, GDS), strategies for overlapping computation and communication, multi-node pitfalls, collective operation algorithms, and the evolution from NCCL to NIXL for disaggregated inference.
«In today's AI landscape, the need for seamless and low-latency data movement between GPUs, storage, and network interfaces is a must… In large-scale systems, even the fastest GPUs can be hindered by inefficient communication and data transfer from memory and disk».
The chapter begins with a fundamental observation: when scaling beyond a single node, network communication transforms from an auxiliary mechanism into the critical path of performance. While on a single GPU the bottleneck is usually related to computation or memory, on a cluster of thousands of accelerators the dominant factor becomes how quickly data can be transferred between them.
The key idea of the chapter is to treat communication not as an «infrastructure detail» but as a full-fledged object of optimization on par with CUDA kernels. Network optimization can deliver a greater effect than compute optimization — especially at scale. This is why the chapter examines NCCL, NIXL, SHARP, RDMA and overlap strategies in detail.
«The main idea is to ensure that data transfers occur concurrently with ongoing computations… Modern frameworks such as PyTorch support asynchronous operations so that collective communication (e.g., all-reduce of gradients) can run alongside compute tasks. This reduces idle GPU time».
In the chapter, the overlap principle is described as the foundation of all distributed training optimization. If a GPU must wait for all-reduce of gradients to complete before starting the next step, each step takes the sum of compute and communication times. If communication is launched asynchronously and overlapped with computation, the step time approaches the maximum of these two values rather than their sum.
PyTorch DistributedDataParallel implements this through wait-free backpropagation: gradients are split into buckets, and as each bucket becomes ready, an asynchronous all-reduce is launched on a separate CUDA stream. The main stream continues computing gradients for subsequent layers. The default bucket size is 25 MiB — a trade-off between network utilization and communication start latency.
The practical effect noted in the chapter: with proper tuning, most communication is hidden behind computation. The visible performance gain for a typical model is 20–30% of iteration time, and for larger models — significantly more.
While gradients of the next layer are being computed, the network transmits the previous ones
The chapter highlights three techniques for strengthening overlap:
Implicit synchronization kills overlap. Calling .item() on a tensor, torch.cuda.synchronize() unnecessarily, print() with a GPU tensor — all of these force the GPU to wait for all asynchronous operations to complete, including the background all-reduce. One such call mid-iteration can negate all DDP optimization.
Overlapping communication with computation is the primary principle of distributed training optimization. DDP implements this through buckets and asynchronous all-reduce on a separate CUDA stream.
Gradient accumulation, data compression, increasing batch size. Each of these reduces the frequency or volume of communication, increasing the overlap window.
Any implicit synchronization mid-iteration (e.g., .item() or print() with a GPU tensor) destroys overlap and adds all communication time to the step time. Profiling through Nsight Systems shows whether overlap exists — by the interleaving of compute and NCCL kernels in the timeline.
«Achieving overlap fundamentally relies on asynchronous execution. GPUs support multiple streams, or queues of operations, that can execute concurrently or overlap if they target different resources… PyTorch DistributedDataParallel automatically installs hooks on the backward pass so that each gradient bucket triggers an asynchronous NCCL all-reduce on a dedicated communication CUDA stream, while the default CUDA stream continues computing gradients for subsequent layers».
The chapter emphasizes that overlap is impossible without asynchronous execution. CUDA streams provide the mechanism allowing different operations to execute in parallel. The key requirement is that communication operations (NCCL) use nonblocking calls that return control immediately. This allows the main stream to continue computing while NCCL works in the background.
In PyTorch DDP this mechanism is hidden from the user, but it is important to understand the principle: each gradient bucket is sent to a separate communication stream, while the main stream continues backward. If the user accidentally calls a synchronization (e.g., to get a tensor value), all overlap is destroyed.
Practical consequence: to preserve overlap, any implicit synchronizations in the hot loop should be avoided. The only synchronization should be at the very end of the iteration, when it is necessary to wait for all asynchronous work to complete before moving to the next step.
CUDA streams are the mechanism of overlap. NCCL uses nonblocking calls that allow the main stream to continue computing.
Any explicit or implicit synchronization mid-iteration (.item(), print(), synchronize()) destroys overlap. Synchronization is allowed only at the end of the iteration.
«As noted, performing more work per communication step can increase overlap and efficiency. Gradient accumulation during model training is one such technique. Instead of all-reducing gradients for every single minibatch, you accumulate gradients over a few minibatches, sum them locally, and then do one all-reduce».
«Another approach to reduce communication volume is compressing or quantizing the data exchanged… The extreme of this is sparsification. When using sparsity, you send only a fraction of the gradients».
In the chapter, reducing the frequency and volume of communication is considered the second most important principle after overlap. Gradient accumulation reduces the number of all-reduce operations linearly with the number of accumulation steps. Compression and sparsification reduce the volume of data transferred per operation.
The trade-off of buckets is separately stipulated: very large buckets maximize bandwidth utilization but delay the start of communication. Very small buckets start earlier but generate more per-call overhead. The default size in PyTorch — 25 MiB — is an empirical balance, but for a specific model it may require tuning.
Practical consequence: if a model has very large layers, increasing the bucket reduces overhead. If a model has many small layers, decreasing the bucket allows communication to start earlier.
Very large buckets maximize bandwidth utilization but delay the start of communication, as one must wait for gradients to accumulate. Very small buckets start earlier but create more NCCL calls with overhead. The optimal size depends on the model and topology.
Reducing frequency (gradient accumulation) and volume (compression, sparsification) of communication is the second principle of optimization after overlap.
Bucket size is a balance between network utilization and communication start latency. For large layers, larger buckets are better; for many small layers, smaller buckets.
«Magnum IO, NVIDIA's overarching I/O acceleration platform, brings together a range of technologies to speed up data movement, access, and management across GPUs, CPUs, storage, and network interfaces. Key Magnum IO components include GPUDirect Storage, GPUDirect RDMA, NCCL, NVSHMEM, SHARP, and I/O management tools such as NVIDIA NetQ and Unified Fabric Manager».
«RDMA lets the network adapter read and write the memory of another node directly, bypassing the OS kernel and CPU… GPUDirect RDMA allows an RDMA-capable NIC to perform DMA directly to and from GPU memory, bypassing the host CPU and system RAM».
In the chapter, RDMA is described as a fundamental technology for multi-node communication. The key difference from TCP/IP: RDMA allows the network adapter to directly access the memory of a remote node without CPU involvement and without copying through system RAM. GPUDirect RDMA extends this to GPU memory — the NIC can write directly to the HBM of a remote GPU.
The practical effect — reducing latency from 20–50 microseconds (TCP/IP) to 1–5 microseconds (RDMA) and increasing throughput from ~100 Gb/s to 400–800 Gb/s per port. At the scale of thousands of GPUs, this delivers a multiplicative gain in gradient synchronization.
The chapter separately notes that in container environments (Docker, Kubernetes), NCCL may fail to access InfiniBand devices and quietly switch to TCP sockets. There are no errors, training proceeds — but throughput drops by an order of magnitude. This is one of the most insidious problems because it does not cause failures.
TCP/IP pushes every byte through the CPU and system RAM; RDMA goes direct
Silent fallback from RDMA to TCP. In container environments (Docker, Kubernetes), NCCL may fail to access InfiniBand devices and quietly switch to TCP sockets. No errors, training runs — but throughput per GPU connection drops from ~100 GB/s (RDMA/InfiniBand) to ~2 GB/s (TCP over Ethernet). For diagnostics, NCCL_DEBUG=INFO and checking the nvidia_peermem module are used.
# Check if the peermem module is loaded
lsmod | grep nvidia_peermem
# Run NCCL with debugging to verify IB is used, not Socket
NCCL_DEBUG=INFO python train.py 2>&1 | grep -E "NET|IB|Socket"
# Check initialization in dmesg
dmesg | grep -i peer
RDMA and GPUDirect RDMA are fundamental technologies for multi-node communication. Latency reduced by 10×, throughput increased by 8× versus TCP/IP (per connection).
In Docker and Kubernetes, NCCL may quietly switch to TCP if there is no access to InfiniBand devices. No errors — only a performance drop by an order of magnitude per connection. Explicit verification via NCCL_DEBUG=INFO is required.
«Scaling training across multiple nodes in a cluster introduces a new class of pitfalls… Using a CPU-bound Gloo backend instead of NCCL. PyTorch's distributed framework supports multiple backends for communication. For multi-GPU training, NCCL is the preferred backend for NVIDIA GPUs, but there is also a fallback backend called Gloo, which uses CPUs and TCP sockets».
«Mismatched NCCL versions. If you run PyTorch's bundled NCCL against a different version of the system-installed libnccl, you will hang the system. Or worse, you will silently fall back to a slower implementation».
The chapter enumerates six typical pitfalls of multi-node training: wrong backend (Gloo instead of NCCL), NCCL version mismatch, TCP port exhaustion, insufficient network bandwidth, straggler nodes, and GPU memory fragmentation under UCX/RDMA.
Each pitfall has a characteristic symptom. Gloo instead of NCCL causes a 10–50× performance drop without any errors. NCCL version mismatch leads to hangs or silent fallback to a slow implementation. TCP port exhaustion manifests as handshake hangs without an explicit error. A straggler node slows down the entire cluster, since synchronous training is determined by the slowest participant.
Practical consequence: for diagnosing each pitfall, the chapter suggests a specific tool. For the backend — torch.distributed.get_backend(). For NCCL versions — torch.cuda.nccl.version(). For straggler nodes — dist.monitored_barrier with a timeout. For the network — monitoring via nvidia-smi dmon or ibstat.
Multi-node training has six typical pitfalls, most of which do not cause failures but quietly slow things down. Diagnostics require explicit checks.
For the backend — get_backend(). For versions — nccl.version(). For stragglers — monitored_barrier. For the network — nvidia-smi dmon or ibstat.
«NVIDIA NCCL is a many-to-many communication library for operations, called collectives, used by groups of GPUs to share data. NCCL underpins most multi-GPU training workloads in NVIDIA's ecosystem… NCCL provides optimized implementations of collective communication operations like all-reduce, all-gather, broadcast, and reduce-scatter that scale from a few GPUs to many thousands and, someday, millions».
In the chapter, NCCL is described as the foundation of distributed training in the NVIDIA ecosystem. The key feature of NCCL is automatic selection of the optimal data transmission path based on physical topology. The library itself determines whether to use NVLink, PCIe, InfiniBand or TCP, and builds the corresponding communication scheme.
Complementing NCCL, the chapter introduces NIXL (NVIDIA Inference Xfer Library) — a library for point-to-point transfers optimized for inference. If NCCL solves the «many-to-many» problem (all-reduce of gradients in training), then NIXL solves the «one-to-one» problem (KV cache transfer between prefill and decode in disaggregated inference).
Practical consequence: for training, NCCL is used; for inference with KV cache transfer — NIXL. Both libraries complement each other rather than replace one another.
NCCL is the foundation of collective operations in distributed training. NIXL complements it for point-to-point transfers in inference.
For training — NCCL. For KV cache transfer in disaggregated inference — NIXL. The libraries complement each other.
«Internally, NCCL can employ different communication algorithms depending on the size of data, number of GPUs, and topology. The primary algorithms NCCL uses for collectives are Ring, Tree, CollNet, and Parallel Aggregated Tree (PAT), among others».
The chapter examines four main NCCL algorithms. Ring provides perfect load balancing (each link transfers an equal volume), but latency grows linearly with the number of GPUs. Tree reduces in O(log N) steps, which is better for small messages, but not all links are evenly loaded. CollNet builds a two-level tree: local within a node (NVLink) and global between nodes (RDMA). PAT is a hybrid of ring and tree, splitting a message into fragments with overlap.
Practical consequence: NCCL selects the algorithm automatically based on message size and topology. For debugging, it can be overridden via NCCL_ALGO, but in production the automatic choice is usually optimal.
Algorithm choice depends on message size and topology
NCCL_ALGO=Ring,Tree,PAT. Useful for debugging, but in production the automatic choice is usually better.
NCCL uses four main algorithms: Ring (balance, high latency), Tree (O(log N), small messages), CollNet (two-level tree), PAT (hybrid).
NCCL selects the algorithm automatically. For debugging, it can be overridden via NCCL_ALGO, but in production the automatic choice is usually optimal.
«Topology awareness plays a major role in NCCL's performance. NCCL detects how GPUs are physically connected and optimizes its communication pattern accordingly. For example, in a system of fully connected NVLink and NVSwitches, every GPU will communicate with every other GPU using these high-speed interconnects».
In the chapter, topology awareness is described as one of the main reasons NCCL is effective. The library analyzes the physical connection scheme of GPUs and builds a hierarchical communication pattern. If GPU 0–1 are connected via NVLink and GPU 2–3 via another NVLink, but only PCIe connects the pairs, NCCL first reduces within pairs (fast NVLink), then exchanges between pairs via PCIe (slow, but only part of the data).
Practical consequence: for diagnosing scaling problems, nvidia-smi topo -n is used. If scaling is worse than expected, the first hypothesis is that traffic is going over slow paths, for example, through PCIe instead of NVLink or through Ethernet instead of InfiniBand.
From fast local NVLink to slow TCP — chosen by topology
nvidia-smi topo -n. If scaling is worse than expected — first hypothesis: traffic is being forced onto slow paths.NCCL automatically detects topology and builds a hierarchical communication pattern. This is one of the main reasons for its effectiveness.
For diagnostics — nvidia-smi topo -n. If scaling is worse than expected, check whether traffic is going over slow paths (PCIe instead of NVLink, Ethernet instead of InfiniBand).
«While NCCL abstracts most low-level details, how we use NCCL in our code can still affect performance. Additionally, NCCL has many environment variables to control its behavior. Misconfiguring these variables can degrade performance or even cause hangs».
The chapter examines four key pitfalls related to NCCL: creating communicators too often, creating and destroying communicators on every iteration, disabling features via environment variables without re-enabling them, and ignoring NCCL warnings.
Creating an NCCL communicator is an expensive operation. If code initializes and destroys a communicator on every iteration, the overhead can exceed the training time itself. The correct approach is to initialize once outside the loop.
The chapter separately notes that NCCL environment variables should be left at their default values unless there is a specific reason to change them. Some variables, such as NCCL_P2P_DISABLE or NCCL_SHM_DISABLE, can be used for debugging, but left enabled in production they noticeably reduce performance.
Creating an NCCL communicator is an expensive operation. Initialization should happen once outside the training loop.
NCCL environment variables are left at defaults unless there is a specific reason. Debug variables (NCCL_P2P_DISABLE, NCCL_SHM_DISABLE) must be returned to their original state after debugging.
«SHARP is an InfiniBand in-network reduction technology used with Quantum-class switches through the NCCL-SHARP plugin… In practical terms, SHARP enables collectives such as all-reduce to be partially computed by the network fabric. As data from multiple GPUs flows into the switch, it will reduce/aggregate the data and share the partially reduced result».
In the chapter, SHARP is described as a technology that moves part of the collective operation into the network. Instead of each GPU receiving data from all others and performing the reduction itself, the switch aggregates partial results. This reduces both SM load and traffic volume.
The practical effect noted in the chapter: NVIDIA reports 2–5× acceleration of all-reduce at large scales. The gain depends on cluster size: at 2–4 GPUs it is negligible, at 72+ GPUs within a rack it is substantial. SHARP is one of the key innovations NVIDIA gained through its Mellanox acquisition.
The chapter also notes NCCL persistent user buffers (user buffer registration), allowing collectives to work directly with tensors without intermediate copying. This is especially important for achieving the best paths through SHARP on both NVLink (NVLS) and InfiniBand.
SHARP moves reduction into the network, freeing SMs and reducing traffic. NVIDIA reports 2–5× acceleration of all-reduce at large scales.
NCCL supports user buffer registration, allowing collectives to work directly with tensors. This is critical for achieving the best paths through SHARP.
SHARP is enabled through the NCCL-SHARP plugin. The gain depends on scale: negligible at 2–4 GPUs, substantial at 72+ GPUs.
«NVIDIA NIXL is an open-source, high-throughput, low-latency, point-to-point communication library released in early 2025. NIXL was designed specifically to accelerate large-scale LLM distributed and disaggregated inference».
«NIXL is a core component of NVIDIA's open source Dynamo inference engine. NIXL streamlines one-to-one and one-to-few data transfers such as moving a key-value (KV) cache between the disaggregated stages with minimal latency and overhead. It complements NCCL, which is mainly used for many-to-many collectives».
In the chapter, NIXL is described as an evolutionary step for inference. Traditional NCCL is optimized for collective operations (all-reduce of gradients), but inference requires a different pattern: transferring KV cache between specific GPUs in disaggregated prefill-decode architecture.
NIXL provides point-to-point transfers with minimal latency and automatically selects the transport — NVLink for intra-node, InfiniBand/RDMA for inter-node, GPUDirect Storage for disk operations. The asynchronous API with callbacks allows overlapping transfer with computation.
Practical consequence: in disaggregated inference, prefill is performed on some GPUs, decode on others, and KV cache is transferred via NIXL. This allows independent scaling of prefill and decode, as well as optimizing each stage for its own characteristics.
Collective synchronization vs point-to-point KV-cache transfer
send/recv is also available for inference, but overhead is higher. For large-scale deployments, NIXL provides lower tail latency, which is critical for real-time.
NIXL is a library for point-to-point transfers in disaggregated inference. Complements NCCL rather than replaces it.
In disaggregated prefill-decode, KV cache is transferred via NIXL. This allows independent scaling of prefill and decode.
«NCCL is designed to maximize collective throughput across multiple GPUs both within a single host and across nodes… NIXL builds on NCCL's high-performance principles and orchestrates asynchronous, hardware-agnostic point-to-point transfers across GPUs, CPUs, and storage devices. NIXL was designed for large-scale distributed inference workloads, including super fast KV cache data transfers».
The chapter provides a systematic comparison of NCCL and NIXL. NCCL is oriented toward «many-to-many» collectives with synchronous semantics (all participants must reach the call). NIXL is oriented toward point-to-point transfers with asynchronous semantics (one initiator, one or more receivers).
NCCL is used in training for all-reduce of gradients. NIXL is used in inference for KV cache transfer and model shards. NCCL is optimized for small and medium tensors, NIXL — for large data blocks (hundreds of megabytes). NCCL is integrated into PyTorch DDP, Horovod and other training frameworks. NIXL is integrated into NVIDIA Dynamo, vLLM via LMCache, and other inference engines.
Practical consequence: for training — NCCL, for inference — NIXL. Both libraries can be used in one application if it includes both training and inference.
NCCL — many-to-many collectives for training. NIXL — point-to-point transfers for inference. The libraries complement each other.
For training — NCCL. For inference with KV cache transfer — NIXL. Both libraries can be used in one application.
Fregly's book was written in 2025, when NCCL and NIXL were current tools. Much has changed since. Below is a comparison of the chapter's forecasts with open data.
«RDMA lets the network adapter read and write the memory of another node directly, bypassing the OS kernel and CPU».
Confirmed. RDMA and GPUDirect RDMA remain the foundation of multi-node communication in 2025–2026. NVIDIA continues to develop this technology: ConnectX-8 provides 800 Gb/s per port, and BlueField-4 DPU offloads network tasks even more efficiently. For NVL72 and subsequent platforms, GPUDirect RDMA is critical for KV cache transfer between racks.
«NVIDIA reports 2–5× acceleration of all-reduce at large scales using SHARP».
Confirmed. NVIDIA confirms 2–5× acceleration at large scales. Within a single NVL72 (72 GPUs in a single NVLink domain), SHARP acceleration is especially noticeable, since the domain is large enough for in-network aggregation to have an effect.
A separate clarification on the «beyond the rack» context: when crossing the boundaries of the NVLink domain, aggregate bandwidth per rack (summed across 18 nodes, not per single GPU) drops from an estimated ~800–900 GB/s (intra-domain NVLink/NVSwitch fabric) to 100–200 GB/s (InfiniBand between racks), if job scheduling does not account for topology. These are rack-level estimates, not per-GPU figures; per GPU connection the corresponding values are roughly 50–100 GB/s and 12–25 GB/s respectively. Exact numbers depend on the number of NICs per node and fabric type.
«NIXL was designed specifically to accelerate large-scale LLM distributed and disaggregated inference».
Confirmed. NIXL is integrated into NVIDIA Dynamo, vLLM via LMCache, and other inference engines. Disaggregation of prefill and decode has become the standard for high-performance LLM inference. NVIDIA Dynamo provides up to 30× throughput improvement for models with ~680B parameters on NVL72.
«In container environments (Docker, Kubernetes), NCCL may fail to access InfiniBand devices and quietly switch to TCP sockets».
Confirmed with correction. The problem remains relevant, but modern versions of NVIDIA Container Toolkit and Kubernetes GPU Operator have learned to automatically pass InfiniBand devices into containers. Nevertheless, for reliability, explicit verification of NCCL_DEBUG=INFO and the nvidia_peermem module is recommended. The numerical effect (per GPU connection) — drop from ~100 GB/s RDMA to ~2 GB/s TCP, as noted in Section IV; this differs from the aggregate rack-level figures above.
«Separate prefill and decode stages run on different GPUs, allowing independent scaling and optimization of each stage».
Confirmed and ahead of schedule. Disaggregation of prefill and decode became standard in 2025. OpenAI, Meta, xAI, NVIDIA, Amazon — all major players use this architecture. DistServe showed 7.4× increase in goodput under strict latency SLOs. vLLM, SGLang, NVIDIA Dynamo support disaggregation out of the box.
The chapter describes technologies and principles but leaves out several aspects that emerged in real-world operation.
The chapter mentions ConnectX-8 and BlueField-4 as promising developments. By 2026, ConnectX-8 (800 Gb/s) and BlueField-4 DPU have become standard for new deployments. ConnectX-8 provides double the throughput of the previous generation, which is critical for disaggregated inference with large KV caches.
The chapter mentions that the NVLink Switch System can combine up to 576 GPUs into a single domain. With the release of Vera Rubin, NVLink 6 doubles throughput to 3.6 TB/s per GPU, and the domain expands to an even larger number of GPUs. This allows TP and EP across even more GPUs without leaving the NVLink fabric.
The chapter mentions NVIDIA Dynamo as an example of NIXL usage. By 2026, Dynamo has become the standard for deploying disaggregated inference in Kubernetes. vLLM, SGLang, TensorRT-LLM — all support integration with NIXL via LMCache or their own connectors.
The chapter does not mention PDL. This is a technology that appeared in Hopper and was developed in Blackwell, allowing one kernel to signal the completion of its prologue and launch a dependent kernel before the first fully completes. PDL complements overlapping communication with computation, reducing time between successive kernel launches.
The chapter does not mention the integration of Groq LPU into the Vera Rubin platform. This is recognition that a single accelerator type is insufficient for reasoning workloads, where test-time scaling multiplies inference load. Heterogeneous computing is becoming a new trend, and this affects communication strategies.
.item(), print() with a GPU tensor, synchronize() — all of these force the GPU to wait for all asynchronous operations to complete.NCCL_DEBUG=INFO and nvidia_peermem is required. The drop is per connection: from ~100 GB/s to ~2 GB/s.nvidia-smi topo -n.Chapter 4 of Fregly's book is a systematic examination of distributed networking communication technologies and principles. The key idea: communication is not an «infrastructure detail» but a first-class optimization object. As clusters grow to tens of thousands of GPUs, network communication becomes the dominant performance factor. An engineer who understands the principles of overlap, topology and collective algorithms can achieve a multiplicative gain even without replacing hardware.
Forecast verification shows: the book proved accurate in its predictions. RDMA, SHARP, NIXL and prefill/decode disaggregation — all these technologies have become standard. The main takeaway remains unchanged: investments in fundamental principles ensure adaptation to any generation of hardware.
Sources: Chris Fregly, «AI Systems Performance Engineering» (O'Reilly, 2026), Chapter 4 — quotes provided in limited volume for review and critical analysis purposes. NVIDIA NCCL, NIXL, SHARP, GPUDirect RDMA documentation; NVIDIA Dynamo; vLLM; SGLang; MLPerf Training/Inference v5.0; DistServe.