pytorch-fsdp2
Fungsinya
Skill ini menjelaskan cara menambahkan sharding FSDP2 PyTorch ke skrip pelatihan, sehingga model yang terlalu besar untuk satu GPU dapat dilatih di beberapa GPU. Untuk insinyur machine learning yang bekerja dengan model besar.
Kapan dipakai
- âSaat sebuah model terlalu besar untuk memori satu GPU.
- âSaat Anda ingin membagi pelatihan di antara GPU dengan sharding per parameter yang lebih mudah diperiksa.
- âSaat Anda membutuhkan checkpoint yang disimpan dengan cara yang bekerja dengan model yang di-shard.
Link skill
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/08-distributed-training/pytorch-fsdp2/SKILL.mdSalin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.
Cara pakai
Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.
Pesan siap tempel
Untuk Claude Code, Codex, atau Cursor: jalankan di folder proyek, lalu skill langsung terpasang.
Unduh SKILL.md lalu taruh di folder skill agen Anda.
Contoh permintaan ke AI
âBisakah Anda membantu saya menambahkan FSDP2 ke skrip pelatihan saya agar model besar saya bisa dilatih di dua GPU?â
5 skill baru setiap minggu. 1 menit baca.
Cara kerjanya
Agent menyiapkan lingkungan terdistribusi, menerapkan sharding pada model, dan menambahkan presisi campuran, offloading, dan pengaturan checkpoint jika diperlukan.
Konten teknis (SKILL.md asli)
Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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
Pertanyaan umum
Apa arti sharding?
Membagi bobot, gradien, dan state optimizer model ke beberapa GPU, sehingga setiap GPU hanya menyimpan sebagian.
Kapan sebaiknya tidak memakai FSDP2?
Skill memperingatkan agar tidak memakainya jika Anda membutuhkan checkpoint yang bekerja di banyak versi PyTorch, atau jika Anda terjebak di versi PyTorch lama tanpa tumpukan FSDP2.
Apa alternatifnya?
Pelatihan data parallel standar dengan DDP, atau FSDP asli untuk pengaturan yang lebih sederhana.
Detail
Deskripsi asli dari pembuat
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.
Popularitas
- Bintang GitHub
- 14k
- Peringkat
- #11161
- Lisensi
- MIT
- Diperbarui
- 10/10/2026
Komentar
- âŚ
Skill lain dari repositori ini
autoresearch
14kMemandu agent Anda melalui proyek riset AI lengkap, dari tinjauan literatur hingga eksperimen dan penulisan, dengan siklus pengujian dan tinjauan yang berulang.
prompt-guard
14kMemungkinkan agent Anda memeriksa teks dari prompt injection dan upaya jailbreak sebelum sampai ke aplikasi AI Anda, dengan classifier kecil dari Meta.
ml-training-recipes
14kMemberi agent Anda resep pelatihan jaringan saraf yang sudah terbukti, mencakup pemilihan model, optimizer, learning rate, dan cara memperbaiki lonjakan loss.
experiment-tracking-swanlab
14kMembantu agent Anda menyiapkan SwanLab untuk mencatat, membandingkan, dan membuat grafik eksperimen machine learning, secara lokal atau di server Anda sendiri.
Skill serupa
pytorch-patterns
280kMembantu agent Anda menggunakan PyTorch untuk model machine learning. Menerapkan praktik terbaik untuk pelatihan model yang efisien dan hasil yang dapat direproduksi.
evm-token-decimals
280kMembantu agent menghindari kesalahan angka desimal di berbagai jaringan blockchain. Memastikan nilai token akurat dalam transaksi dan perhitungan.
ito-inference
280kMemungkinkan agent Anda mengecek ketersediaan model AI untuk digunakan. Menghubungkan permintaan komputasi dengan layanan model yang siap.