pytorch-fsdp2
하는 일
이 스킬은 PyTorch FSDP2 샤딩을 학습 스크립트에 추가하는 방법을 설명합니다. 한 GPU에 들어가기에는 큰 모델을 여러 GPU에서 학습할 수 있게 합니다. 대형 모델을 다루는 머신러닝 엔지니어를 위한 스킬입니다.
사용하는 경우
- ✓모델이 단일 GPU의 메모리에 들어가기에 너무 클 때.
- ✓검사하기 쉬운 파라미터 단위 샤딩으로 여러 GPU에 학습을 나누고 싶을 때.
- ✓샤딩된 모델과 함께 작동하는 방식으로 체크포인트를 저장해야 할 때.
스킬 링크
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/08-distributed-training/pytorch-fsdp2/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“내 대형 모델이 GPU 두 개에서 학습할 수 있도록 FSDP2를 학습 스크립트에 추가하는 것을 도와줄 수 있나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 분산 환경을 설정하고, 모델에 샤딩을 적용하며, 필요한 곳에 혼합 정밀도, 오프로딩, 체크포인트 설정을 추가합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Skill: Use PyTorch FSDP2 (fully_shard) correctly in a training script
This skill teaches a coding agent how to add PyTorch FSDP2 to a training loop with correct initialization, sharding, mixed precision/offload configuration, and checkpointing.
FSDP2 in PyTorch is exposed primarily via
torch.distributed.fsdp.fully_shardand theFSDPModulemethods it adds in-place to modules. See:references/pytorch_fully_shard_api.md,references/pytorch_fsdp2_tutorial.md.
When to use this skill
Use FSDP2 when:
- Your model doesn’t fit on one GPU (parameters + gradients + optimizer state).
- You want an eager-mode sharding approach that is DTensor-based per-parameter sharding (more inspectable, simpler sharded state dicts) than FSDP1.
- You may later compose DP with Tensor Parallel using DeviceMesh.
Avoid (or be careful) if:
- You need strict backwards-compatible checkpoints across PyTorch versions (DCP warns against this).
- You’re forced onto older PyTorch versions without the FSDP2 stack.
Alternatives (when FSDP2 is not the best fit)
- DistributedDataParallel (DDP): Use the standard data-parallel wrapper when you want classic distributed data parallel training.
- FullyShardedDataParallel (FSDP1): Use the original FSDP wrapper for parameter sharding across data-parallel workers.
Reference: references/pytorch_ddp_notes.md, references/pytorch_fsdp1_api.md.
Contract the agent must follow
- Launch with
torchrunand set the CUDA device per process (usually viaLOCAL_RANK). - Apply
fully_shard()bottom-up, i.e., shard submodules (e.g., Transformer blocks) before the root module. - Call
model(input), notmodel.forward(input), so the FSDP2 hooks run (unless you explicitlyunshard()or register the forward method). - Create the optimizer after sharding and make sure it is built on the DTensor parameters (post-
fully_shard). - Checkpoint using Distributed Checkpoint (DCP) or the distributed-state-dict helpers, not naïve
torch.save(model.state_dict())unless you deliberately gather to full tensors.
(Each of these rules is directly described in the official API docs/tutorial; see references.)
Step-by-step procedure
0) Version & environment sanity
- Prefer a recent stable PyTorch where the docs show FSDP2 and DCP updated recently.
- Use
torchrun --nproc_per_node <gpus_per_node> ...and ensureRANK,WORLD_SIZE,LOCAL_RANKare visible.
Reference: references/pytorch_fsdp2_tutorial.md (launch commands and setup), references/pytorch_fully_shard_api.md (user contract).
1) Initialize distributed and set device
Minimal, correct pattern:
dist.init_process_group(backend="nccl")torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))- Optionally create a
DeviceMeshto describe the data-parallel group(s)
Reference: references/pytorch_device_mesh_tutorial.md (why DeviceMesh exists & how it manages process groups).
2) Build model on meta device (recommended for very large models)
For big models, initialize on meta, apply sharding, then materialize weights on GPU:
with torch.device("meta"): model = ...- apply
fully_shard(...)on submodules, thenfully_shard(model) model.to_empty(device="cuda")model.reset_parameters()(or your init routine)
Reference: references/pytorch_fsdp2_tutorial.md (migration guide shows this flow explicitly).
3) Apply fully_shard() bottom-up (wrapping policy = “apply where needed”)
Do not only call fully_shard on the topmost module.
Recommended sharding pattern for transformer-like models:
- iterate modules,
if isinstance(m, TransformerBlock): fully_shard(m, ...) - then
fully_shard(model, ...)
Why:
fully_shardforms “parameter groups” for collective efficiency and excludes params already grouped by earlier calls. Bottom-up gives better overlap and lower peak memory.
Reference: references/pytorch_fully_shard_api.md (bottom-up requirement and why).
4) Configure reshard_after_forward for memory/perf trade-offs
Default behavior:
NonemeansTruefor non-root modules andFalsefor root modules (good default).
Heuristics:
- If you’re memory-bound: keep defaults or force
Trueon many blocks. - If you’re throughput-bound and can afford memory: consider keeping unsharded params longer (root often
False). - Advanced: use an
intto reshard to a smaller mesh after forward (e.g., intra-n
자주 묻는 질문
샤딩이란 무엇인가요?
모델의 가중치, 기울기, 옵티마이저 상태를 여러 GPU에 나누어, 각 GPU가 그중 일부만 보관하게 하는 것입니다.
언제 FSDP2를 쓰지 말아야 하나요?
여러 PyTorch 버전에서 작동하는 체크포인트가 필요할 때, 또는 FSDP2 스택이 없는 오래된 PyTorch 버전을 쓰고 있을 때에는 쓰지 말라고 스킬이 경고합니다.
대안은 무엇인가요?
DDP를 사용하는 표준 데이터 병렬 학습이나, 더 단순한 설정을 위한 원래의 FSDP입니다.
상세 정보
작성자의 원본 설명
Adds PyTorch FSDP2 (fully_shard) to training scripts with correct init, sharding, mixed precision/offload config, and distributed checkpointing. Use when models exceed single-GPU memory or when you need DTensor-based sharding with DeviceMesh.
인기도
- GitHub 스타
- 14k
- 순위
- #11161
- 라이선스
- MIT
- 업데이트
- 2026. 10. 10.
댓글
- …
이 저장소의 다른 스킬
autoresearch
14k에이전트가 문헌 검토부터 실험과 글쓰기까지 AI 연구 프로젝트 전체를 진행하도록 안내합니다. 테스트와 검토를 반복하는 주기를 따릅니다.
prompt-guard
14k에이전트가 Meta의 작은 분류기로, AI 앱에 도달하기 전에 텍스트에서 프롬프트 인젝션과 탈옥 시도를 검사하도록 돕습니다.
ml-training-recipes
14k에이전트에게 모델 선택, 옵티마이저, 학습률, 손실 급등 해결 등 신경망 학습의 검증된 방법을 알려 줍니다.
experiment-tracking-swanlab
14k에이전트가 SwanLab을 설정해 머신러닝 실험을 내 컴퓨터나 자체 서버에서 기록하고, 비교하고, 차트로 그리도록 돕습니다.