Настоящий обзор систематизирует инженерные и алгоритмические подходы к параллелизму по слоям — третьему измерению масштабирования нейросетей, наряду с data- и tensor-parallelism. Материал опирается на открытые публикации: Megatron-LM, GPipe, PipeDream, Zero Bubble Pipeline Parallelism, DualPipe/DualPipeV (DeepSeek), V-Shape Schedule, MGRIT и layer-parallel обучение ResNet/трансформеров (Sandia, XBraid/TorchBraid), SNLP и его применение в гомоморфном шифровании.
Числовые примеры, формулы памяти и коммуникаций, сравнительные таблицы расписаний и результаты экспериментов приведены по указанным источникам. Цитаты и ссылки даны в ограниченном объёме в целях обзора и критического анализа.
Когда модель перестаёт влезать в один GPU, у инженера обычно два рефлекторных ответа: размножить модель на устройствах и разнести данные (data parallelism) или разрезать матрицы внутри слоёв (tensor parallelism). Оба встроены в Megatron-LM, DeepSpeed и torchtitan и хорошо описаны. Но за кадром остаётся третье измерение — сама глубина модели. Пока слой k не завершил вычисления, слой k+1 не может начать, и никакое увеличение батча это не лечит.
Здесь важно сразу развести два явления, которые постоянно путают. Первое — pipeline parallelism: индустриальная практика, при которой модель разрезается на стадии, раскладывается по устройствам и обрабатывает микробатчи конвейером. Она зрелая и массово применяется в тренировках больших языковых моделей. Второе — алгоритмический layer-parallelism: семейство численных методов, которые заменяют саму последовательную цепочку слоёв итеративным решателем и позволяют всем слоям вычислять одновременно.
Отдельного упоминания заслуживает четвёртая ось — context parallelism: она режет длинную последовательность между устройствами и решает проблему квадратичного по контексту роста attention-активаций. К теме этой статьи она относится краем — но при чтении обзоров полезно держать полную карту: data, tensor, context и pipeline/layer — четыре разных ответа на четыре разных ограничения, и зрелость у них разная.
Data: модель целиком на каждом устройстве, разные батчи. Tensor: матрицы разрезаны внутри слоя. Layer: глубина разрезана между устройствами.
Прямой проход нейронной сети — это цепочка с полной зависимостью по данным: hk+1 = fk(hk). В терминах теории графов вычислительный граф имеет высоту L, и критический путь по глубине нельзя сократить никакой оптимизацией внутри слоёв — можно лишь изменить семантику вычисления. Именно это и делают layer-parallel методы: они переформулируют задачу так, чтобы глубина перестала быть критическим путём.
У последовательности есть вторая, менее очевидная цена — память на активации. Автоград требует хранить всё, что понадобится обратному проходу. Для трансформерного слоя в смешанной точности стандартная оценка из Megatron-LM:
Mact ≈ s·b·h · (34 + 5·a·s/h) байт на слой
где s — длина последовательности, b — размер батча, h — скрытая размерность, a — число голов внимания. Полный расчёт памяти на стек:
s·b·h·L·(10 + 24/t + 5·a·s/h)s·b·h·L·(10 + 24/t)2·s·b·h·L байт, где t — степень tensor-parallelism.Член 5·a·s²·b — это квадратичный по контексту вес attention-матриц; FlashAttention убирает его вовсе, работая тайлами в SRAM и никогда не материализуя [b, a, s, s]-тензор.
После активационной оптимизации доминирующей стоимостью в глубокой сети становится именно последовательное вычисление — то есть время критического пути. Это и есть та ниша, которую заполняет параллелизм по слоям.
Простейший вариант — раскладывать слои по устройствам и передавать активации по цепочке. Схема прозрачна, но глубоко дефектна: при обработке одного образца активна одна стадия из d, утилизация кластера 1/d. Активации и градиенты при этом всё равно гоняются между машинами на каждом шаге. Независимые обзоры фреймворков фиксируют, что такой наивный подход стабильно проигрывает не только data-parallel решениям вроде DDP и ZeRO, но и конвейерным схемам по времени эпохи.
Инженеру полезно запомнить размерность передачи: через границу стадии за один микробатч проходит тензор [s, b, h], то есть 2 · s · b · h байт в fp16. При s = b = 4096 и h = 4096 это 128 МБ на каждую границу в одну сторону — и столько же обратно на обратном проходе.
Уже эта арифметика показывает, почему топология межсоединений (NVLink внутри узла против InfiniBand между узлами) должна диктовать, где резать модель. Резать по границе с наименьшим трафиком — не оптимизация, а гигиена.
Идея конвейера — разрезать мини-батч на m микробатчей и пропустить их через d стадий так, чтобы простой исчез. За два десятилетия сложилась лестница расписаний, и каждое следующее решает конкретный дефект предыдущего.
GPipe → 1F1B → Interleaved 1F1B → Zero Bubble → DualPipe. Жёлтое = форвард, синее = бэквард, штриховка = пузырь.
GPipe пускает все m форвардов, затем все m бэквардов, суммируя градиенты синхронно в конце батча. Доля простоя:
bubble = (d − 1) / (m + d − 1)
При m > 4d накладные расходы становятся почти незаметными — но только при условии рекомпьютации активаций, потому что без неё GPipe хранит активации всех микробатчей сразу, и память растёт пропорционально m.
Расписание PipeDream-flush / 1F1B, ставшее стандартом Megatron-LM и DeepSpeed, меняет фазовый портрет: после прогрева каждая стадия чередует один форвард и один бэквард. Ключевое свойство — число «в полёте» микробатчей, для которых бэквард ещё не выполнен и активации держатся в памяти, ограничено глубиной конвейера d, а не размером батча m. Это фундаментально меняет кривую потребления памяти: она перестаёт расти с батчем.
Megatron-LM добавил трюк: каждое устройство владеет не одним непрерывным куском слоёв, а v «модельными чанками», разбросанными по конвейеру (например, вместо слоёв [4..7] — пары [4,5] и [12,13]). Пузырь сжимается примерно пропорционально числу чанков, ценой пропорционального роста point-to-point коммуникации. Авторы сообщают о росте пропускной способности более чем на 10% при сопоставимом следе памяти; в независимых замерах interleaved 1F1B с фактором 4 обычно сжимает пузырь в 3–4 раза относительно обычного 1F1B при росте коммуникации на 10–20%.
До 2024 года пузырь считался неустранимым при синхронной семантике. Zero Bubble Pipeline Parallelism заметил: бэквард распадается на две независимые части — градиент по входу B и градиент по весам W. Первое — цепочка по данным, второе — накопление, которое можно отложить. Разделив их в расписании и добавив обход синхронизаций на шаге оптимизатора, авторы получили конвейер без пузырей вообще; алгоритм автоматически подбирает оптимальное расписание под конфигурацию модели и лимит памяти. В публикационной версии статьи выигрыш против 1F1B — до 15% по пропускной способности при сопоставимой памяти и до 30% при ослабленном лимите.
Развитие той же идеи — расписания V-Shape: анализ показал, что пиковая активационная память определяется «временем жизни» (lifespan) блоков расписания, и это даёт управляемый рычаг. V-Min сжимает память до ~1/3 от 1F1B, V-Half — до ~1/2, а V-ZB держит память 1F1B, но убивает пузырь: на модели 9,6B с 16 микробатчами V-ZB достигал MFU 45,8% против 30,0% у 1F1B.
Самое заметное пополнение лестницы за последние годы — DualPipe, двунаправленное расписание, выпущенное DeepSeek и ставшее production-стандартом фронтирных тренировок: DeepSeek-V3 обучался с 16-way pipeline parallelism и 64-way expert parallelism, а DualPipe называют одним из рычагов знаменитой экономии на обучении. Идея — пустить форварды и бэкварды навстречу друг другу с двух краёв конвейера и перекрыть коммуникацию фаз all-to-all в MoE-моделях вычислениями. Фактор пузыря падает с (PP−1) у 1F1B до (PP/2−1) — примерно вдвое при том же числе рангов. Механически DualPipe опирается на то же разложение бэкварда на «backward for input» и «backward for weights», что и Zero Bubble, — именно это позволяет сдвигать коммуникацию в «свободные» половины шага. Развитие той же идеи — DualPipeV: V-образная упрощённая версия, совместимая с приёмом «cut-in-half» и не требующая двух копий параметров на устройство. Цена DualPipe — память: на каждом устройстве держатся две копии параметров активных направлений, поэтому профиль памяти 1F1B не сохраняется.
| Расписание | Пузырь | Память на активации | Коммуникация | Когда выбирать |
|---|---|---|---|---|
| GPipe | (d−1)/(m+d−1) | ∝ m — растёт с батчем | минимальная | маленькие модели, отладка |
| 1F1B | то же, но меньше из-за tf, tb | ограничена d in-flight | умеренная | рабочая лошадка, по умолчанию |
| Interleaved 1F1B (v чанков) | ниже в ~v раз | сопоставима с 1F1B | +10–20% P2P | большие конвейеры, warm-up дорог |
| Zero Bubble (ZB-V/ZB1P) | ≈ 0 | 1×–2× от 1F1B | выше | фронтирные тренировки, есть лимит памяти |
| V-Min / V-Half | зависит от блока | 1/3–1/2 от 1F1B | сопоставима | память — жёсткий ограничитель |
| DualPipe | (PP/2−1)·(F&B + B − 3W) — ≈ вдвое ниже 1F1B | 2× от 1F1B (параметры + активации) | перекрывается all-to-all | MoE-модели с тяжёлым all-to-all |
| DualPipeV | между 1F1B и DualPipe | ближе к 1F1B | перекрывается частично | когда память DualPipe недоступна |
Введите параметры модели и конфигурацию конвейера — получите оценку памяти, коммуникации, пузыря и КПД.
s·b·h·L·(10 + 24/t) для селективной рекомпьютации. Числа — порядковая оценка, а не замена профилированию.
В независимом бенчмарке фреймворков PipeDream и TorchGPipe показали время эпохи хуже и менее предсказуемое, чем DDP и ZeRO — отчасти из-за отсутствия поддержки смешанной точности в сравнивавшихся реализациях. Конвейер — зрелый, но не волшебный инструмент; выигрыш сильно зависит от качества реализации.
А теперь — то, ради чего статья. Идея: взглянуть на глубокую сеть глазами вычислительного математика. Остаточная сеть
hk+1 = hk + fk(hk)
— это явная дискретизация (forward Euler) непрерывной динамической системы, где каждый слой — шаг по «времени». А у сообщества scientific computing есть готовый арсенал для таких задач: parallel-in-time методы, которые решают временную задачу не последовательно, а итеративно — как conjugate gradient решает систему, не зануляя компоненты по одной.
MGRIT (Multigrid-Reduction-in-Time) переносит многосеточную иерархию на ось глубины. Точки слоёв разбиваются на C-точки (каждая cf-я) и F-точки; параметр cf — фактор огрубления. Одна итерация двухуровневого цикла:
Если в пункте 3 сделать один рекурсивный вызов — получится V-cycle; цикл повторяется до требуемой точности. Критически важная теорема: на сходимости state- и adjoint-итерации MGRIT восстанавливают ровно тот же редуцированный градиент, что и последовательный forward-backward. Это не аппроксимация на уровне методов — это другая схема вычисления того же результата. В типичных экспериментах фактор огрубления cf = 4 работал стабильно.
C-точки (каждая 4-я) образуют грубую сетку. F-точки внутри блоков считаются параллельно.
# N слоёв, coarsening cf, иерархия уровней 0..L
for i in 1..max_iters:
FCF-relaxation(level 0) # параллельно по N/cf блокам
for l in 0..L-1: # вниз по уровням
r[l+1] = restrict(residual(l))
sequential_solve(coarsest) # единственный последовательный кусок
for l in L-1..0: # вверх по уровням
correct(l, prolong(error(l+1)))
N₀/cf-путевой параллелизм по оси глубины. Типично cf = 4.
На сходимости state- и adjoint-итерации дают тот же редуцированный градиент, что и последовательный forward-backward.
Для 3D-классификации изображений — примерно 10× относительно последовательного выполнения.
Реализация — интерфейс на PyTorch, бэкенд на C-библиотеке XBraid, объединённые через MPI с GPU-ускорением. Статья о высокопроизводительном training с MPI и GPU опубликована в ACM Transactions on Mathematical Software. Практически важное: TorchBraid требует CUDA-aware MPI — прямого обмена между GPU без копирования через хост. Репозиторий поставляет тест, который проверяет доступность GPU Direct Communication при старте.
ompi_info --parsable -l 9 --all | grep mpi_built_with_cuda_support:value
# ожидаемый PASS: "PASSED: GPU aware MPI is available"
Сильная сторона подхода — новое измерение масштабирования: layer-parallel комбинируется с data и tensor parallelism, а не заменяет их. И есть честная оговорка: существует кросс-овер-поинт — при недостаточном числе процессоров последовательное вычисление остаётся быстрее.
Команда Sandia применила layer-parallel MGRIT к предобучению трансформеров и получила два важных инженерных урока.
Первый: точные градиенты не нужны на большей части траектории обучения. В ранних режимах, где грубая аппроксимация ещё терпима, параллельный решатель даёт ускорение — его разумно использовать для гиперпараметрического поиска и раннего обучения.
Второй: вблизи минимума потери начинают расходиться, если градиенты неточны. Решение — переключение с параллельного режима на последовательный, и — что особенно ценно — детектор переключения встроен в сам метод: невязка MGRIT показывает, насколько аппроксимация ещё далека от точного значения. Повышая число итераций решателя каждые несколько сотен итераций обучения и следя за невязкой, можно на лету увидеть, когда ускоритель пора выключить.
Это редкий пример алгоритма, который сам сообщает, когда перестаёт работать. Для production-инженерии это ценнее, чем красивая цифра пиковой скорости.
Последовательность слоёв мешает и инференсу — особенно авторегрессионным трансформерам, где на конвейер накладывается ещё и зависимость по токенам. SNLP (Structured Newton Layer Parallelism) атакует проблему иным способом: он трактует трассу скрытых состояний по глубине как решение системы нелинейных уравнений
Gl(h) = hl − fl(hl−1) = 0, l = 1, …, L
и решает её параллельными Ньютоновскими итерациями. На каждой итерации k все суффиксные слои вычисляются независимо и параллельно: h̃l(k) = fl(hl−1(k)), затем применяется структурная коррекция:
hl(k+1) = h̃l(k) + Al(k) · (hl−1(k+1) − hl−1(k))
где Al(k) — суррогат якобиана слоя. При Al = Jl получился бы точный DEER/Newton, но материализовать якобиан дорого. Вместо этого используются дешёвые суррогаты, индуцированные архитектурой: для остаточных трансформеров это Identity Newton (IDN) — коррекция вырождается в префикс-суммо-подобное обновление; для mHC-архитектур — HC Newton (HCN), использующий матрицу смешивания модели. Дорогие форварды блоков параллелятся, а на критическом пути остаётся лишь лёгкая структурная рекуррентность.
Дорогие блоки fl вычисляются параллельно; критический путь — только лёгкая рекуррентность Al.
В полностью гомоморфном шифровании (FHE) последовательная композиция L нелинейных блоков означает каскад криптографических перезагрузок шифротекста (bootstraps) — самой дорогой операции FHE. SNLP меняет картину: нелинейная последовательная глубина падает с L блоков до нескольких итераций решателя плюс линейные структурные коррекции.
Числа на модели 0,5B с IDN-обучением: bootstraps сокращаются с 53 до 20 (2,65×) при деградации перплексии всего в 1,2%, а накопление ошибки аппроксимации при SNLP оказалось даже ниже, чем при последовательном инференсе (усиление ошибки 1,36× против 1,42×) — и это правило выполняется на всех 8 протестированных моделях 4 архитектурных семейств. Абляции показали, что в бюджете ошибок доминирует аппроксимация softmax, а арифметический шум CKKS пренебрежимо мал — то есть SNLP комплементарен дизайну FHE-дружественных операторов, а не заменяет его.
Все приведённые FHE-результаты — симуляционные: Chebyshev-аппроксимации нелинейностей оценивались в моделировании, а не на реальном FHE-движке, а тестируемая модель 0,5 млрд параметров на порядки меньше production-деплоев. Корректная трактовка — «многообещающая архитектурная идея с доказательством на уровне симуляции», а не готовая к применению характеристика. Перед любым внедрением обязательна проверка на реальном криптографическом стеке.
Термин живёт и в других мирах, хотя в каждом по-своему. В аппаратных ускорителях различают intra-layer parallelism (параллелизм внутри одного слоя) и inter-layer pipelining (конвейер между слоями): исследовательская архитектура FLIP2M для AR/VR-нагрузок объединяет оба режима на тиловом ускорителе, распределяя слои по вычислительным блокам и конвейерно передавая данные между ними.
В классических многоуровневых системах — например, в протокольных стеках — уровни (транспортный, сетевой, канальный) могут исполняться на разных вычислительных элементах, а пакеты идут конвейером: пока один уровень обрабатывает пакет n, следующий уже работает с пакетом n−1.
Функции внутри одного слоя могут выполняться параллельно, но функции из разных слоёв не могут одновременно работать над одним и тем же элементом данных. Именно это отличает параллелизм по слоям от чисто горизонтального распараллеливания и объясняет, почему методы из предыдущих разделов не «сжимают» глубину бесплатно.
Вместо абстрактных сценариев — конкретная последовательность, от зрелого к экспериментальному. Пропускать ступени не стоит: верхние ступени дешевле и почти всегда достаточны.
Двигайтесь снизу вверх. Верхние ступени применяйте только после исчерпания нижних.
Параллелизм по слоям — не единый метод, а семейство с разной зрелостью и разной теорией. Pipeline parallelism маскирует последовательность слоёв микробатчами и умными расписаниями, но не устраняет её. Алгоритмический layer-parallelism в духе MGRIT и TorchBraid идёт дальше: он переопределяет саму семантику вычисления — с честной теоремой о том, что на сходимости градиент совпадает с последовательным. SNLP переносит ту же идею на инференс трансформеров и открывает неожиданное направление в гомоморфном шифровании.
Data, tensor и layer parallelism — три независимых оси масштабирования. Layer-parallel комбинируется с первыми двумя, а не заменяет их.
Pipeline parallelism маскирует последовательность микробатчами. Алгоритмический layer-parallelism (MGRIT, SNLP) переопределяет семантику вычисления.
GPipe → 1F1B → Interleaved → Zero Bubble → DualPipe → V-Shape. Каждое следующее сжимает пузырь и/или память; DualPipe добавляет бидирекциональность и перекрытие all-to-all. 1F1B ограничивает память глубиной конвейера d, а не размером батча m.
Остаточная сеть — forward Euler ODE. Многосетка по оси слоёв даёт новое измерение параллелизма при честной теореме о совпадении градиента на сходимости.
Sandia показала: точные градиенты не нужны на большей части траектории. Переключение параллель→последовательность по невязке MGRIT — встроенный детектор отказа.
Параллельные блоки + структурная коррекция через суррогат якобиана. 2,3× на инференсе; сокращение bootstraps 53→20 при деградации ppl 1,2%.
Сначала диагностика (память? коммуникация? последовательность?), потом инструмент. Экзотика на неправильной ступени — экспоненциально дорогая ошибка.
Простой вывод для инженера: если вы упёрлись в потолок производительности и классические измерения параллелизма уже выжаты, спросите себя, не является ли последовательность слоёв тем ресурсом, который вы ещё не трогали. Но начните с диагностики: узкое место — в памяти, в коммуникации или в самой последовательности вычислений? Ответ определит инструмент — и не позволит принять экспоненциально дорогую экзотику там, где хватает переключения расписания.
Ключевые источники: TorchBraid (GitHub, Multilevel-NN), layer-parallel обучение ResNet через MGRIT (arXiv:1812.04352), презентация Sandia по layer-parallel трансформерам (2025), SNLP (arXiv:2605.17842), SNLP для FHE (arXiv:2607.04819), Zero Bubble Pipeline Parallelism (ICLR 2024), формула активационной памяти Megatron (arXiv:2205.05198), V-Shape Schedule (NeurIPS 2024), FlashAttention (Dao et al.).
This review systematizes engineering and algorithmic approaches to layer parallelism — the third scaling axis for neural networks alongside data and tensor parallelism. It draws on open publications: Megatron-LM, GPipe, PipeDream, Zero Bubble Pipeline Parallelism, DualPipe/DualPipeV (DeepSeek), V-Shape Schedule, MGRIT and layer-parallel training of ResNets and transformers (Sandia, XBraid/TorchBraid), SNLP and its application to homomorphic encryption.
Numerical examples, memory and communication formulas, comparative schedule tables, and experimental results are given according to the cited sources. Quotes and references are provided in limited volume for review and critical analysis purposes.
When a model no longer fits on a single GPU, the engineer usually has two reflex answers: replicate the model across devices and shard the data (data parallelism), or slice matrices within layers (tensor parallelism). Both are built into Megatron-LM, DeepSpeed, and torchtitan, and are well described. But a third axis stays out of the spotlight — the depth of the model itself. Until layer k finishes computing, layer k+1 cannot start, and no amount of batch enlargement cures that.
Two phenomena are constantly conflated and must be separated immediately. The first is pipeline parallelism: an industrial practice in which the model is split into stages, distributed across devices, and processes microbatches in a pipeline. It is mature and widely used to train large language models. The second is algorithmic layer-parallelism: a family of numerical methods that replace the sequential chain of layers itself with an iterative solver, letting all layers compute at the same time.
Worth a separate mention is the fourth axis — context parallelism: it shards a long sequence across devices and addresses the quadratic-in-context growth of attention activations. It only tangentially belongs to this article's subject — but when reading reviews it helps to keep the full map in mind: data, tensor, context, and pipeline/layer are four different answers to four different constraints, with very different levels of maturity.
Data: full model per device, sharded batches. Tensor: matrices split inside a layer. Layer: depth split across devices.
A neural network's forward pass is a chain of full data dependencies: hk+1 = fk(hk). In graph-theoretic terms, the computational graph has height L, and the critical path along depth cannot be shortened by any intra-layer optimization — only by changing the semantics of the computation. That is what layer-parallel methods do: they reformulate the problem so that depth stops being the critical path.
Sequentiality has a second, less obvious cost — activation memory. Autograd must store everything the backward pass will need. For a transformer layer in mixed precision, the standard Megatron-LM estimate is:
Mact ≈ s·b·h · (34 + 5·a·s/h) bytes per layer
where s is sequence length, b is batch size, h is hidden size, and a is the number of attention heads. Total stack memory:
s·b·h·L·(10 + 24/t + 5·a·s/h)s·b·h·L·(10 + 24/t)2·s·b·h·L bytes, where t is tensor-parallel degree.The term 5·a·s²·b is the quadratic-in-context weight of attention matrices; FlashAttention removes it entirely by working in tiles in SRAM and never materializing the [b, a, s, s] tensor.
After activation optimization, the dominant cost in a deep network becomes precisely the sequential computation — the critical path time. This is the niche layer parallelism fills.
The simplest variant — distribute layers across devices and pass activations along the chain — is transparent but deeply flawed: for a single sample, one stage out of d is active, giving cluster utilization 1/d. Activations and gradients are still shipped between machines at each step. Independent framework reviews show that this naive approach consistently loses to data-parallel solutions like DDP and ZeRO, and to pipelined schemes as well, in epoch time.
Worth remembering: across a stage boundary, one microbatch transfers an [s, b, h] tensor, i.e. 2 · s · b · h bytes in fp16. With s = b = 4096 and h = 4096, that is 128 MB per boundary in one direction — and the same back on the reverse pass.
This arithmetic shows why interconnect topology (NVLink inside a node vs. InfiniBand across nodes) must dictate where to cut the model. Cutting at the lowest-traffic boundary is not optimization but hygiene.
The pipeline idea is to split a minibatch into m microbatches and push them through d stages so that idling disappears. Over two decades, a ladder of schedules has formed, each solving a specific defect of the previous one.
GPipe → 1F1B → Interleaved 1F1B → Zero Bubble → DualPipe. Amber = forward, cyan = backward, hatched = bubble.
GPipe runs all m forwards, then all m backwards, synchronously summing gradients at the end of the batch. Bubble fraction:
bubble = (d − 1) / (m + d − 1)
With m > 4d, overhead becomes nearly invisible — but only with activation recomputation, because otherwise GPipe stores all microbatches' activations simultaneously and memory grows proportionally to m.
The PipeDream-flush / 1F1B schedule, now standard in Megatron-LM and DeepSpeed, changes the phase portrait: after warm-up, each stage alternates one forward and one backward. The key property is that in-flight microbatches — those whose backward has not yet run and whose activations are held — are bounded by pipeline depth d, not batch size m. This fundamentally changes the memory curve: it stops growing with batch.
Megatron-LM added a trick: each device owns not one contiguous span of layers but v "model chunks" scattered along the pipeline (e.g., instead of layers [4..7], pairs [4,5] and [12,13]). The bubble shrinks roughly proportionally to the number of chunks, at the cost of proportionally more point-to-point communication. The authors report over 10% throughput gain at comparable memory footprint; independent measurements show interleaved 1F1B with factor 4 typically shrinks the bubble 3–4× versus plain 1F1B, with 10–20% more communication.
Until 2024, the bubble was considered unavoidable under synchronous semantics. Zero Bubble Pipeline Parallelism noticed that backward splits into two independent parts — the gradient with respect to the input B and the gradient with respect to the weights W. The former is a data chain; the latter is an accumulation that can be deferred. By splitting them in the schedule and bypassing optimizer-step synchronization, the authors obtained a bubble-free pipeline; the algorithm automatically chooses an optimal schedule for the model configuration and memory budget. In the published version, the gain versus 1F1B is up to 15% in throughput at comparable memory, and up to 30% under a relaxed memory cap.
A development of the same idea — V-Shape schedules: analysis showed that peak activation memory is governed by the "lifespan" of schedule blocks, giving a controllable lever. V-Min compresses memory to ~1/3 of 1F1B, V-Half to ~1/2, and V-ZB keeps 1F1B memory while killing the bubble: on a 9.6B model with 16 microbatches, V-ZB reached 45.8% MFU versus 30.0% for 1F1B.
The most notable addition to the ladder in recent years is DualPipe, a bidirectional schedule released by DeepSeek that became a production standard for frontier training: DeepSeek-V3 trained with 16-way pipeline parallelism and 64-way expert parallelism, and DualPipe is credited as one of the levers behind the famous training cost savings. The idea is to run forwards and backwards towards each other from both ends of the pipeline and overlap the all-to-all communication phases of MoE models with computation. The bubble factor drops from (PP−1) in 1F1B to (PP/2−1) — roughly half at the same rank count. Mechanically, DualPipe relies on the same backward decomposition into "backward for input" and "backward for weights" as Zero Bubble, and it is precisely this that lets communication move into the "free" halves of a step. A development of the same idea is DualPipeV: a V-shaped simplified variant compatible with the "cut-in-half" trick that avoids keeping two copies of parameters per device. The price of DualPipe is memory: each device holds two copies of the parameters of active directions, so the 1F1B memory profile is not preserved.
| Schedule | Bubble | Activation memory | Communication | When to choose |
|---|---|---|---|---|
| GPipe | (d−1)/(m+d−1) | ∝ m — grows with batch | minimal | small models, debugging |
| 1F1B | same, but smaller via tf, tb | bounded by d in-flight | moderate | workhorse, default |
| Interleaved 1F1B (v chunks) | ~v× lower | comparable to 1F1B | +10–20% P2P | large pipelines, costly warm-up |
| Zero Bubble (ZB-V/ZB1P) | ≈ 0 | 1×–2× of 1F1B | higher | frontier training, memory cap |
| V-Min / V-Half | block-dependent | 1/3–1/2 of 1F1B | comparable | memory is the hard limit |
| DualPipe | (PP/2−1)·(F&B + B − 3W) — ≈ half of 1F1B | 2× of 1F1B (parameters + activations) | overlapped with all-to-all | MoE models with heavy all-to-all |
| DualPipeV | between 1F1B and DualPipe | closer to 1F1B | partially overlapped | when DualPipe memory is unavailable |
Enter model parameters and pipeline configuration — get an estimate of memory, communication, bubble, and efficiency.
s·b·h·L·(10 + 24/t) for selective recomputation. Numbers are an order-of-magnitude estimate, not a replacement for profiling.
In an independent framework benchmark, PipeDream and TorchGPipe showed worse and less predictable epoch times than DDP and ZeRO — partly due to missing mixed-precision support in the implementations compared. The pipeline is a mature but not magical tool; gains depend heavily on implementation quality.
Now the main subject. The idea is to look at a deep network through the eyes of a computational mathematician. A residual network
hk+1 = hk + fk(hk)
is an explicit discretization (forward Euler) of a continuous dynamical system, where each layer is a step in "time". And the scientific computing community has a ready arsenal for such problems: parallel-in-time methods that solve the time problem iteratively — as conjugate gradient solves a system without zeroing components one by one.
MGRIT (Multigrid-Reduction-in-Time) transfers a multigrid hierarchy onto the depth axis. Layer points are partitioned into C-points (every cf-th) and F-points; cf is the coarsening factor. One iteration of a two-level cycle:
With one recursive call in step 3, you get a V-cycle; the cycle repeats to the desired tolerance. A crucial theorem: at convergence, the state and adjoint iterations of MGRIT recover exactly the same reduced gradient as sequential forward-backward. This is not a methodological approximation — it is a different computational scheme for the same result. In typical experiments, coarsening factor cf = 4 worked robustly.
C-points (every 4th) form the coarse grid. F-points inside blocks are computed in parallel.
# N layers, coarsening cf, hierarchy levels 0..L
for i in 1..max_iters:
FCF-relaxation(level 0) # parallel over N/cf blocks
for l in 0..L-1: # down the hierarchy
r[l+1] = restrict(residual(l))
sequential_solve(coarsest) # the only sequential piece
for l in L-1..0: # up the hierarchy
correct(l, prolong(error(l+1)))
N₀/cf-way parallelism along the depth axis. Typical cf = 4.
At convergence, state and adjoint iterations yield the same reduced gradient as sequential forward-backward.
For 3D image classification — roughly 10× versus sequential execution.
The implementation is a PyTorch interface on a C XBraid backend, glued through MPI with GPU acceleration. A paper on high-performance training with MPI and GPUs appeared in ACM Transactions on Mathematical Software. Practically important: TorchBraid requires CUDA-aware MPI — direct GPU-to-GPU transfer without host staging. The repository ships a startup test that checks GPU Direct Communication availability.
ompi_info --parsable -l 9 --all | grep mpi_built_with_cuda_support:value
# expected PASS: "PASSED: GPU aware MPI is available"
The approach's strength is a new axis of scaling: layer-parallel combines with data and tensor parallelism rather than replacing them. And there is an honest caveat: a crossover point exists — with too few processors, sequential execution remains faster.
Sandia applied layer-parallel MGRIT to transformer pretraining and extracted two important engineering lessons.
First: exact gradients are unnecessary over much of the training trajectory. In early regimes where a coarse approximation is still tolerable, the parallel solver provides a speedup — reasonable for hyperparameter search and early training.
Second: near the loss minimum, losses begin to diverge if gradients are inexact. The solution is to switch from parallel to sequential mode, and — crucially — the switch detector is built into the method: MGRIT's residual shows how far the approximation still is from the exact value. By increasing solver iterations every few hundred training steps and watching the residual, you can see on the fly when the accelerator should be turned off.
This is a rare case of an algorithm that tells you when it stops working. For production engineering, that is worth more than a beautiful peak-speed number.
Depth also hurts inference — especially autoregressive transformers, where a per-token dependency overlays the layer pipeline. SNLP (Structured Newton Layer Parallelism) attacks the problem differently: it treats the depth-wise trace of hidden states as the solution of a nonlinear system
Gl(h) = hl − fl(hl−1) = 0, l = 1, …, L
and solves it with parallel Newton iterations. On each iteration k, all suffix layers compute independently and in parallel: h̃l(k) = fl(hl−1(k)), followed by a structural correction:
hl(k+1) = h̃l(k) + Al(k) · (hl−1(k+1) − hl−1(k))
where Al(k) is a surrogate for the layer Jacobian. With Al = Jl you would get exact DEER/Newton, but materializing the Jacobian is expensive. Instead, cheap architecture-induced surrogates are used: for residual transformers this is Identity Newton (IDN) — the correction degenerates into a prefix-sum-like update; for mHC architectures it is HC Newton (HCN), using the model's mixing matrix. Expensive block forwards are parallelized; only light structural recurrence remains on the critical path.
Expensive blocks fl compute in parallel; the critical path is only the light recurrence Al.
In fully homomorphic encryption (FHE), the sequential composition of L nonlinear blocks implies a cascade of ciphertext bootstraps — the most expensive FHE operation. SNLP changes the picture: nonlinear sequential depth drops from L blocks to a few solver iterations plus linear structural corrections.
Numbers on a 0.5B model with IDN training: bootstraps shrink from 53 to 20 (2.65×) at only 1.2% perplexity degradation, and approximation error accumulation under SNLP turned out to be even lower than under sequential inference (error amplification 1.36× versus 1.42×) — a pattern that held across all 8 tested models from 4 architectural families. Ablations show that softmax approximation dominates the error budget while CKKS arithmetic noise is negligible — meaning SNLP is complementary to FHE-friendly operator design rather than a replacement.
All the FHE numbers above are simulation-level: the Chebyshev approximations of nonlinearities were evaluated in modeling, not on a real FHE engine, and the tested 0.5B model is orders of magnitude smaller than production deployments. The correct reading is "a promising architectural idea with simulation-level evidence", not a production-ready characteristic. Any deployment attempt must be validated on a real cryptographic stack.
The term also lives in other worlds, each in its own way. In hardware accelerators, one distinguishes intra-layer parallelism (parallelism within a single layer) from inter-layer pipelining (pipeline between layers): the research architecture FLIP2M for AR/VR workloads combines both modes on a tiled accelerator, distributing layers across compute units and streaming data between them.
In classical layered systems — protocol stacks, for instance — the layers (transport, network, link) can run on different compute elements, with packets flowing in a pipeline: while one layer processes packet n, the next is already working on packet n−1.
Functions within a layer can run in parallel, but functions from different layers cannot simultaneously work on the same data element. This is what distinguishes layer parallelism from purely horizontal sharding, and it explains why the methods in the previous sections do not "compress" depth for free.
Instead of abstract scenarios, a concrete sequence from mature to experimental. Don't skip rungs: the upper ones are cheaper and almost always sufficient.
Move bottom-up. Apply upper rungs only after exhausting lower ones.
Layer parallelism is not a single method but a family with different maturity and theory. Pipeline parallelism masks layer sequentiality with microbatches and clever schedules, but does not eliminate it. Algorithmic layer-parallelism in the spirit of MGRIT and TorchBraid goes further: it redefines the very semantics of the computation — with an honest theorem that, at convergence, the gradient matches the sequential one. SNLP carries the same idea into transformer inference and opens an unexpected direction in homomorphic encryption.
Data, tensor and layer parallelism are independent scaling axes. Layer-parallel combines with the first two rather than replacing them.
Pipeline parallelism masks sequentiality with microbatches. Algorithmic layer-parallelism (MGRIT, SNLP) redefines computational semantics.
GPipe → 1F1B → Interleaved → Zero Bubble → DualPipe → V-Shape. Each shrinks the bubble and/or memory; DualPipe adds bidirectionality and all-to-all overlap. 1F1B bounds memory by pipeline depth d, not batch size m.
A residual network is a forward Euler ODE. Multigrid along the layer axis gives a new parallelism axis with a strict gradient-equivalence theorem at convergence.
Sandia showed exact gradients are unnecessary over most of the trajectory. Parallel→sequential switching on the MGRIT residual is a built-in failure detector.
Parallel blocks + structural correction via a Jacobian surrogate. 2.3× on inference; bootstraps shrink 53→20 at 1.2% perplexity degradation.
Diagnose first (memory? communication? sequentiality?), then pick the tool. Exotica on the wrong rung is an exponentially expensive mistake.
The simple takeaway for an engineer: if you've hit a performance ceiling and classical parallelism axes are exhausted, ask whether sequential depth is the resource you haven't yet touched. But start with diagnosis: is the bottleneck memory, communication, or computation's own sequentiality? The answer determines the tool — and prevents an exponentially expensive exotic solution where a schedule switch would suffice.
Key sources: TorchBraid (GitHub, Multilevel-NN), layer-parallel ResNet training via MGRIT (arXiv:1812.04352), Sandia's layer-parallel transformer presentation (2025), SNLP (arXiv:2605.17842), SNLP for FHE (arXiv:2607.04819), Zero Bubble Pipeline Parallelism (ICLR 2024), Megatron activation-memory formula (arXiv:2205.05198), V-Shape Schedule (NeurIPS 2024), FlashAttention (Dao et al.).