distributed-training-pytorch-fsdp
Что он делает
Этот скилл объясняет, как обучать большие модели PyTorch, разделяя их параметры между GPU, с вариантами смешанной точности и выгрузки на CPU. Он нужен инженерам ML, которые работают с PyTorch и должны уместить более крупные модели.
Когда использовать
- ✓Когда модель PyTorch слишком велика для памяти одного GPU.
- ✓Когда команде нужно уменьшить потребление памяти с помощью выгрузки на CPU во время обучения.
- ✓Когда нужно настроить обучение со смешанной точностью для модели с шардингом в PyTorch.
Ссылка на скилл
https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/distributed-training-pytorch-fsdp/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Помоги обернуть мою модель трансформера PyTorch в FSDP, чтобы она помещалась на двух GPU.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Скилл объясняет, как FSDP делит параметры (шардинг), как задать смешанную точность и выгрузку, а также как работает более новый подход FSDP2. Он опирается на официальную документацию PyTorch.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Pytorch-Fsdp Skill
Comprehensive assistance with pytorch-fsdp development, generated from official documentation.
When to Use This Skill
This skill should be triggered when:
- Working with pytorch-fsdp
- Asking about pytorch-fsdp features or APIs
- Implementing pytorch-fsdp solutions
- Debugging pytorch-fsdp code
- Learning pytorch-fsdp best practices
Quick Reference
Common Patterns
Pattern 1: Generic Join Context Manager# Created On: Jun 06, 2025 | Last Updated On: Jun 06, 2025 The generic join context manager facilitates distributed training on uneven inputs. This page outlines the API of the relevant classes: Join, Joinable, and JoinHook. For a tutorial, see Distributed Training with Uneven Inputs Using the Join Context Manager. class torch.distributed.algorithms.Join(joinables, enable=True, throw_on_early_termination=False, **kwargs)[source]# This class defines the generic join context manager, which allows custom hooks to be called after a process joins. These hooks should shadow the collective communications of non-joined processes to prevent hanging and erroring and to ensure algorithmic correctness. Refer to JoinHook for details about the hook definition. Warning The context manager requires each participating Joinable to call the method notify_join_context() before its own per- iteration collective communications to ensure correctness. Warning The context manager requires that all process_group attributes in the JoinHook objects are the same. If there are multiple JoinHook objects, then the device of the first is used. The process group and device information is used for checking for non- joined processes and for notifying processes to throw an exception if throw_on_early_termination is enabled, both of which using an all- reduce. Parameters joinables (List[Joinable]) – a list of the participating Joinable s; their hooks are iterated over in the given order. enable (bool) – a flag enabling uneven input detection; setting to False disables the context manager’s functionality and should only be set when the user knows the inputs will not be uneven (default: True). throw_on_early_termination (bool) – a flag controlling whether to throw an exception upon detecting uneven inputs (default: False). Example: >>> import os >>> import torch >>> import torch.distributed as dist >>> import torch.multiprocessing as mp >>> import torch.nn.parallel.DistributedDataParallel as DDP >>> import torch.distributed.optim.ZeroRedundancyOptimizer as ZeRO >>> from torch.distributed.algorithms.join import Join >>> >>> # On each spawned worker >>> def worker(rank): >>> dist.init_process_group("nccl", rank=rank, world_size=2) >>> model = DDP(torch.nn.Linear(1, 1).to(rank), device_ids=[rank]) >>> optim = ZeRO(model.parameters(), torch.optim.Adam, lr=0.01) >>> # Rank 1 gets one more input than rank 0 >>> inputs = [torch.tensor([1.]).to(rank) for _ in range(10 + rank)] >>> with Join([model, optim]): >>> for input in inputs: >>> loss = model(input).sum() >>> loss.backward() >>> optim.step() >>> # All ranks reach here without hanging/erroring static notify_join_context(joinable)[source]# Notifies the join context manager that the calling process has not yet joined. Then, if throw_on_early_termination=True, checks if uneven inputs have been detected (i.e. if one process has already joined) and throws an exception if so. This method should be called from a Joinable object before its per-iteration collective communications. For example, this should be called at the beginning of the forward pass in DistributedDataParallel. Only the first Joinable object passed into the context manager performs the collective communications in this method, and for the others, this method is vacuous. Parameters joinable (Joinable) – the Joinable object calling this method. Returns An async work handle for the all-reduce meant to notify the context manager that the process has not yet joined if joinable is the first one passed into the context manager; None otherwise. class torch.distributed.algorithms.Joinable[source]# This defines an abstract base class for joinable classes. A joinable class (inheriting from Joinable) should implement join_hook(), which returns a JoinHook instance, in addition to join_device() and join_process_group() that return device and process group information, respectively. abstract property join_device: device# Return the device from which to perform collective communications needed by the join context manager. abstr
Частые вопросы
Что здесь значит шардинг?
Шардинг делит параметры модели между GPU, так что каждое устройство хранит только часть модели.
Поддерживается ли выгрузка на CPU?
Да. Скилл рассматривает выгрузку на CPU как способ снизить потребление памяти GPU.
Есть ли более новая версия?
Да. Скилл описывает FSDP2 наряду с исходной версией.
Подробности
Оригинальное описание автора
Expert guidance for Fully Sharded Data Parallel training with PyTorch FSDP - parameter sharding, mixed precision, CPU offloading, FSDP2
Популярность
- Звёзды на GitHub
- 33k
- Место в рейтинге
- #8546
- Лицензия
- MIT
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
owasp-security
33kУчит агента рекомендациям OWASP по безопасности для веб-приложений, API, мобильных приложений, контейнеров и ИИ-агентов: поиск слабостей и исправления.
agent-management
33kПозволяет агенту создавать, перечислять, усыплять, будить, переименовывать и удалять ИИ-агентов через AI Maestro, управляя жизненным циклом каждого.
agent-messaging
33kПозволяет агенту отправлять, получать и отвечать на подписанные сообщения между ИИ-агентами по протоколу Agent Messaging Protocol, в основном на вашем компьютере.
docs-search
33kПозволяет агенту искать по сгенерированной документации кода: сигнатуры функций, классы и комментарии, чтобы проверить реальный API до изменения кода.
Похожие скиллы
pytorch-patterns
280kПомогает агенту использовать PyTorch для моделей машинного обучения: эффективное обучение и воспроизводимые результаты.
evm-token-decimals
280kПомогает агенту избегать ошибок с десятичными знаками в разных блокчейн-сетях, чтобы суммы токенов были точными.
ito-inference
280kАгент проверяет доступность моделей ИИ и связывает запрос на вычисления с готовым сервисом модели.