[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,87 +2,167 @@
|
||||
id: wiki-2026-0508-pipeline-parallelism
|
||||
title: Pipeline Parallelism
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [SYS-PIPE-PAR-001]
|
||||
aliases: [PP, GPipe, 1F1B]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [infrastructure, Parallel-Computing, pipeline-parallelism, distributed-training, llm-training, gpu-Optimization]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [parallelism, distributed-training, deep-learning, llm]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: pytorch
|
||||
---
|
||||
|
||||
# Pipeline Parallelism (파이프라인 병렬성)
|
||||
# Pipeline Parallelism
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "거대한 모델을 한 그릇에 담으려 하지 말고, 여러 장치에 층층이 나누어 배치한 뒤 데이터의 컨베이어 벨트를 가동하라" — 모델의 레이어들을 여러 개의 GPU에 분산 배치하고, 데이터를 순차적으로 통과시켜 연산과 통신을 중첩함으로써 학습 효율을 높이는 분산 학습 기술.
|
||||
## 매 한 줄
|
||||
> **"매 모델을 layer-wise로 잘라 GPU pipeline 위로 micro-batch가 흐르게 한다"**. 매 GPipe(2018)에서 시작, PipeDream / 1F1B / Interleaved 1F1B로 진화. 매 2026 LLM 학습(>100B params)에서 TP+PP+DP 조합의 한 축.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Sequential Layer Partitioning and Micro-[[Batching|Batching]]" — 모델을 수직으로 쪼개어 장치별로 할당하고, 앞선 장치의 연산이 끝날 때까지 뒷 장치가 노는 시간(Bubble)을 줄이기 위해 미니 배치를 더 작은 마이크로 배치로 쪼개어 끊임없이 파이프라인을 채우는 패턴.
|
||||
- **핵심 알고리즘:**
|
||||
- **GPipe:** 마이크로 배치를 통해 유휴 시간을 줄인 최초의 표준 파이프라인 병렬화.
|
||||
- **PipeDream:** 전방 계산(Forward)과 후방 계산(Backward)을 비동기적으로 중첩시켜 효율 극대화.
|
||||
- **의의:** 단일 GPU 메모리 용량을 초과하는 수천억 파라미터 규모의 초거대 언어 모델(LLM) 학습을 가능케 하는 물리적 인프라의 필수 구성 요소.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순히 층을 나누면 통신 오버헤드 때문에 느려질 것이라는 우려를 '마이크로 배치'와 '비동기 통신' 기술로 극복하며, 이제는 데이터 병렬화(DP) 및 텐서 병렬화(TP)와 결합된 하이브리드 병렬화(3D Parallelism)가 표준이 됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 대규모 지식 모델의 파인튜닝 시, GPU 자원 점유율을 최적화하기 위해 파이프라인 병렬화 기반의 분산 학습 프레임워크(DeepSpeed 등)를 적극 활용함.
|
||||
### 매 왜 PP인가
|
||||
- 매 단일 GPU 의 memory(HBM3 80–192GB) 의 초과 → layer 분할 필수.
|
||||
- 매 Tensor Parallelism 의 NVLink 안 high-bandwidth requirement → 매 node 간 한계.
|
||||
- 매 Pipeline Parallelism 의 stage 간 activation 만 전달 → 매 inter-node OK.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Parallel-Computing-in-AI|Parallel-Computing-in-AI]], [[NVIDIA-CUDA-and-AI|NVIDIA-CUDA-and-AI]],[[_system|system]]-Design-for-AI-Scale, LLM-Training-Foundations
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Pipeline-Parallelism.md
|
||||
### 매 stage / micro-batch
|
||||
- Stage = 매 연속 layer 묶음, GPU 1개 차지.
|
||||
- Mini-batch 의 micro-batch K개로 split → 매 동시에 다른 stage에서 처리.
|
||||
- Bubble = 매 idle time. Bubble ratio ≈ (stages - 1) / K.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 schedule 계열
|
||||
1. **GPipe**: 매 forward all → backward all. 매 simple, 큰 bubble.
|
||||
2. **1F1B (PipeDream)**: 매 1 forward, 1 backward 교대. 매 activation memory 절감.
|
||||
3. **Interleaved 1F1B (Megatron)**: 매 stage 마다 여러 chunk → bubble 감소.
|
||||
4. **Zero Bubble PP (2024)**: 매 backward를 W/B로 split → 매 거의 0 bubble.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### PyTorch native PipelineStage (torch.distributed.pipelining)
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.distributed.pipelining import pipeline, ScheduleGPipe, SplitPoint
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
class Block(nn.Module):
|
||||
def __init__(self, d): super().__init__(); self.l = nn.Linear(d, d)
|
||||
def forward(self, x): return torch.relu(self.l(x))
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
class Net(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.b1 = Block(1024); self.b2 = Block(1024)
|
||||
self.b3 = Block(1024); self.b4 = Block(1024)
|
||||
def forward(self, x):
|
||||
return self.b4(self.b3(self.b2(self.b1(x))))
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
model = Net()
|
||||
example = torch.randn(8, 1024)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
pipe = pipeline(
|
||||
model, mb_args=(example,),
|
||||
split_spec={"b3": SplitPoint.BEGINNING}, # stage0: b1-b2, stage1: b3-b4
|
||||
)
|
||||
stage = pipe.build_stage(stage_index=rank, device=f"cuda:{rank}")
|
||||
sched = ScheduleGPipe(stage, n_microbatches=4, loss_fn=nn.MSELoss())
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 1F1B schedule 계산
|
||||
```python
|
||||
def schedule_1f1b(num_stages: int, num_microbatches: int):
|
||||
"""매 stage 별 forward/backward 순서 emit"""
|
||||
ops = [[] for _ in range(num_stages)]
|
||||
warmup = num_stages
|
||||
for s in range(num_stages):
|
||||
n_warm = min(warmup - s, num_microbatches)
|
||||
for mb in range(n_warm):
|
||||
ops[s].append(("F", mb))
|
||||
for mb in range(num_microbatches - n_warm):
|
||||
ops[s].append(("F", n_warm + mb))
|
||||
ops[s].append(("B", mb))
|
||||
for mb in range(num_microbatches - n_warm, num_microbatches):
|
||||
ops[s].append(("B", mb))
|
||||
return ops
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Megatron-LM virtual pipeline
|
||||
```python
|
||||
# v_chunks=2 → stage0 holds {layer 0-7, layer 16-23}, stage1 holds {8-15, 24-31}
|
||||
config = TransformerConfig(
|
||||
num_layers=32, hidden_size=8192,
|
||||
pipeline_model_parallel_size=4,
|
||||
virtual_pipeline_model_parallel_size=2, # interleaved chunks
|
||||
num_microbatches=64,
|
||||
)
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Activation recompute (memory bubble 완화)
|
||||
```python
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
class CheckpointedBlock(nn.Module):
|
||||
def forward(self, x):
|
||||
return checkpoint(self._fwd, x, use_reentrant=False)
|
||||
def _fwd(self, x): return self.attn(self.norm(x)) + x
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### DeepSpeed PipelineModule
|
||||
```python
|
||||
import deepspeed
|
||||
from deepspeed.pipe import PipelineModule, LayerSpec
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
specs = [LayerSpec(Block, 1024) for _ in range(8)]
|
||||
model = PipelineModule(layers=specs, num_stages=4, partition_method="uniform")
|
||||
engine, _, _, _ = deepspeed.initialize(model=model, config=ds_config)
|
||||
loss = engine.train_batch(data_iter)
|
||||
```
|
||||
|
||||
### 3D parallelism (TP × PP × DP)
|
||||
```python
|
||||
# 매 Megatron / NeMo 의 conventional layout
|
||||
# world_size = TP × PP × DP
|
||||
# Llama 3 405B 학습: TP=8, PP=16, DP=128 → 16384 GPUs
|
||||
mesh = init_device_mesh("cuda", (DP, PP, TP), mesh_dim_names=("dp","pp","tp"))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 single node, ≤8 GPU | TP only (NVLink) |
|
||||
| 매 multi-node, model > node mem | TP intra-node + PP inter-node |
|
||||
| 매 100B+ params | TP × PP × DP (3D) |
|
||||
| 매 inference latency 중요 | TP > PP (PP의 bubble 손해) |
|
||||
| 매 throughput 중심 training | PP + DP 큰 micro-batch |
|
||||
|
||||
**기본값**: 매 LLM 학습은 1F1B + activation recompute + 3D parallel.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed Training]] · [[Model Parallelism]]
|
||||
- 변형: [[Tensor Parallelism]] · [[Sequence Parallelism]] · [[Zero Bubble Pipeline]]
|
||||
- 응용: [[Megatron-LM]] · [[DeepSpeed]] · [[LLM Training]]
|
||||
- Adjacent: [[Data Parallelism]] · [[ZeRO Optimizer]] · [[FSDP]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 모델 weight 가 단일 GPU mem 초과 + 매 multi-node training. 매 cross-node bandwidth 가 TP에 부족할 때.
|
||||
**언제 X**: 매 단일 node 안 fits. 매 매우 작은 batch (bubble 비율 폭증). 매 inference latency-critical.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Bubble ignore**: 매 micro-batch K=1 → 매 GPU의 (stages-1)/stages 가 idle.
|
||||
- **Uneven partition**: 매 stage 별 FLOPs 불균형 → 매 가장 느린 stage 가 throughput 결정.
|
||||
- **PP only no DP**: 매 K 늘려도 batch size 한계 → 매 DP 병행 필수.
|
||||
- **Embedding 분리 무시**: 매 input/output embedding 의 같은 stage 배치 → tied weight sync 단순.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Megatron-LM paper, GPipe, PipeDream, PyTorch pipelining docs 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — PP schedules + 3D parallel patterns |
|
||||
|
||||
Reference in New Issue
Block a user