pytorch-fsdp2
Adds PyTorch FSDP2 (fully_shard) to training scripts with correct init, sharding, mixed precision/offload config, and distributed checkpointing.
Skill by Orchestra-Research
Install
Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.
npx agentmarket install skill/orchestra-research-pytorch-fsdp2
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Use cases: ml
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/pytorch-fsdp2
What's inside
- Skill name
pytorch-fsdp2- Description
- 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.
- License
- MIT
- Instructions
- 223 lines in SKILL.md · view on GitHub
Files (13)
- SKILL.md
- pytorch_dcp_async_recipe.md · references/
- pytorch_dcp_overview.md · references/
- pytorch_dcp_recipe.md · references/
- pytorch_ddp_notes.md · references/
- pytorch_device_mesh_tutorial.md · references/
- pytorch_examples_fsdp2.md · references/
- pytorch_fsdp1_api.md · references/
- pytorch_fsdp2_tutorial.md · references/
- pytorch_fully_shard_api.md · references/
- pytorch_tp_tutorial.md · references/
- ray_train_fsdp2_example.md · references/
- torchtitan_fsdp_notes.md · references/
SKILL.md (first lines)
# 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_shard` and the `FSDPModule` methods 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
1. **Launch with `torchrun`** and set the CUDA device per process (usually via `LOCAL_RANK`).
2. **Apply `fully_shard()` bottom-up**, i.e., shard submodules (e.g., Transformer blocks) before the root module.
3. **Call `model(input)`**, not `model.forward(input)`, so the FSDP2 hooks run (unless you explicitly `unshard()` or register the forward method).
4. **Create the optimizer after sharding** and make sure it is built on the **DTensor parameters** (post-`fully_shard`).
5. **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 ensure `RANK`, `WORLD_SIZE`, `LOCAL_RANK` are 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 `DeviceMesh` to 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, then `fully_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_shard` forms “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:
- `None` means `True` for non-root modules and `False` for root modules (good default).
Heuristics:
- If you’re memory-bound: keep defaults or force `True` on many blocks.
- If you’re throughput-bound and can afford memory: consider keeping unsharded params longer (root often `False`).
- Advanced: use an `int` to reshard to a smaller mesh after forward (e.g., intra-node) if it’s a meaningful divisor.
Reference: `references/pytorch_fully_shard_api.md` (full semantics).
---
### 5) Mixed precision & offload (optional but common)
FSDP2 uses:
- `mp_policy=MixedPrecisionPolicy(param_dtype=..., reduce_dtype=..., output_dtype=..., cast_forward_inputs=...)`
- `offload_policy=CPUOffloadPolicy()` if you want CPU offload
Rules of thumb:
- Start with BF16 parameters/reductions on H100/A100-class GPUs (if numerically stable for your model).
- Keep `reduce_dtype` aligned with your gradient reduction expectations.
- If you use CPU offload, budget for PCIe/NVLink traffic and runtime overhead.
Reference: `references/pytorch_fully_shard_api.md` (MixedPrecisionPolicy / OffloadPolicy classes).
---
### 6) Optimizer, gradient clipping, accumulation
- Create the optimizer **after** sharding so it holds DTensor params.
- If you need gradient accumulation / no_sync:
- use the FSDP2 mechanism (`set_requires_gradient_sync`) instead of FSDP1’s `no_sync()`.
Gradient clipping:
- Use the approach shown in the FSDP2 tutorial (“Gradient Clipping and Optimizer with DTensor”), because parameters/gradients are DTensors.From Orchestra-Research/AI-Research-SKILLs, MIT.
More from Orchestra-Research/AI-Research-SKILLs
- 0.686score
pinecone
Orchestra-Research
Managed vector database for production AI applications.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
sentence-transformers
Orchestra-Research
Framework for state-of-the-art sentence, text, and image embeddings.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
chroma
Orchestra-Research
Open-source embedding database for AI applications.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
faiss
Orchestra-Research
Facebook's library for efficient similarity search and clustering of dense vectors.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
gptq
Orchestra-Research
Post-training 4-bit quantization for LLMs with minimal accuracy loss.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
ml-training-recipes
Orchestra-Research
Battle-tested PyTorch training recipes for all domains — LLMs, vision, diffusion, medical imaging, protein/drug discovery, spatial omics, genomics.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
sentencepiece
Orchestra-Research
Language-independent tokenizer treating text as raw Unicode.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
langchain
Orchestra-Research
Framework for building LLM-powered applications with agents, chains, and RAG.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
ray-data
Orchestra-Research
Scalable data processing for ML workloads.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
nemo-curator
Orchestra-Research
GPU-accelerated data curation for LLM training.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
pytorch-lightning
Orchestra-Research
High-level PyTorch framework with Trainer class, automatic distributed training (DDP/FSDP/DeepSpeed), callbacks system, and minimal boilerplate.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
clip
Orchestra-Research
OpenAI's model connecting vision and language.
SkillCFreshness: C★ 13.9KClaude Code +9
Compare and alternatives
Featured in
Signals
- Stars
- 13,906
- Forks
- 973
- Open issues
- 11
- Last commit (this folder)
- Jan 30, 2026 (9 months ago)
- Last release
- Jun 16, 2026 (4 months ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Website
- orchestra-research.com
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from Orchestra-Research
- 0.686score
gptq
Orchestra-Research
Post-training 4-bit quantization for LLMs with minimal accuracy loss.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
nemo-curator
Orchestra-Research
GPU-accelerated data curation for LLM training.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
ray-data
Orchestra-Research
Scalable data processing for ML workloads.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
pytorch-lightning
Orchestra-Research
High-level PyTorch framework with Trainer class, automatic distributed training (DDP/FSDP/DeepSpeed), callbacks system, and minimal boilerplate.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
sentencepiece
Orchestra-Research
Language-independent tokenizer treating text as raw Unicode.
SkillCFreshness: C★ 13.9KClaude Code +9 - 0.686score
ml-training-recipes
Orchestra-Research
Battle-tested PyTorch training recipes for all domains — LLMs, vision, diffusion, medical imaging, protein/drug discovery, spatial omics, genomics.
SkillCFreshness: C★ 13.9KClaude Code +9
Cite this page
pytorch-fsdp2 skill. Agent Mart. https://agentmart.dev/skills/orchestra-research-pytorch-fsdp2 (last updated 2026-10-24)