pytorch-fsdp2
Was er macht
Dieser Skill erklärt, wie du die FSDP2-Sharding-Funktion von PyTorch in ein Trainingsskript einbaust, damit ein Modell, das nicht auf eine GPU passt, auf mehrere verteilt trainiert werden kann. Er richtet sich an Machine-Learning-Ingenieurinnen und -Ingenieure, die mit großen Modellen arbeiten.
Wann du ihn nutzt
- ✓Wenn ein Modell zu groß für den Speicher einer einzelnen GPU ist.
- ✓Wenn du das Training mit paramterweisem Sharding auf mehrere GPUs verteilen willst, das sich leichter prüfen lässt.
- ✓Wenn du Checkpoints brauchst, die mit dem geteilten Modell funktionieren.
Link zum Skill
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/08-distributed-training/pytorch-fsdp2/SKILL.mdKopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.
So nutzt du ihn
Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.
Fertige Nachricht zum Einfügen
Für Claude Code, Codex oder Cursor: Führe den Befehl in deinem Projektordner aus, dann wird der Skill installiert.
Lade die SKILL.md herunter und lege sie in den Skills-Ordner deines Agenten.
Beispielanfrage an deine KI
“Kannst du mir helfen, FSDP2 in mein Trainingsskript einzubauen, damit mein großes Modell auf zwei GPUs trainieren kann?”
5 neue Skills pro Woche. 1 Minute Lesezeit.
So funktioniert es
Der Agent richtet die verteilte Umgebung ein, wendet das Sharding auf das Modell an und ergänzt bei Bedarf Mixed Precision, Auslagerung und Checkpoint-Einstellungen.
Technischer Inhalt (originale SKILL.md)
Originaltext des Autors, auf Englisch, direkt von 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
Häufige Fragen
Was bedeutet Sharding?
Die Gewichte, Gradienten und der Optimiererzustand eines Modells werden auf mehrere GPUs verteilt, sodass jede nur einen Teil hält.
Wann sollte ich FSDP2 nicht nutzen?
Der Skill warnt davor, wenn Checkpoints über viele PyTorch-Versionen funktionieren müssen oder du an einer älteren PyTorch-Version ohne den FSDP2-Stack hängst.
Was sind die Alternativen?
Das übliche Daten-Parallel-Training mit DDP oder das ursprüngliche FSDP für einfachere Setups.
Details
Originalbeschreibung des Autors
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.
Beliebtheit
- GitHub-Sterne
- 14k
- Platz im Ranking
- #11161
- Lizenz
- MIT
- Aktualisiert
- 10.10.2026
Kommentare
- …
Weitere Skills aus diesem Repository
autoresearch
14kFührt deinen Agenten durch ein vollständiges KI-Forschungsprojekt, von der Literaturübersicht über Experimente bis zum Schreiben, mit einem wiederkehrenden Zyklus aus Test und Prüfung.
prompt-guard
14kLässt deinen Agenten Texte auf Prompt-Injection und Jailbreak-Versuche prüfen, bevor sie deine KI-App erreichen, mit dem kleinen Klassifikator von Meta.
ml-training-recipes
14kGibt deinem Agenten bewährte Trainingsrezepte für neuronale Netze, mit Modellwahl, Optimierern, Lernraten und dem Beheben von Loss-Spitzen.
experiment-tracking-swanlab
14kHilft deinem Agenten, SwanLab einzurichten, um Experimente des maschinellen Lernens lokal oder auf eigenem Server aufzuzeichnen, zu vergleichen und darzustellen.
Ähnliche Skills
pytorch-patterns
280kHilft deinem Agenten, PyTorch für Machine-Learning-Modelle einzusetzen. Er wendet Best Practices für effizientes Training und reproduzierbare Ergebnisse an.
evm-token-decimals
280kHilft deinem Agenten, Fehler bei Dezimalzahlen in verschiedenen Blockchain-Netzwerken zu vermeiden. Sorgt dafür, dass Token-Werte stimmen.
ito-inference
280kHilft deinem Agenten, die Verfügbarkeit von KI-Modellen zu prüfen. Er verbindet Rechenanfragen mit einem bereiten Modellservice.