-
Notifications
You must be signed in to change notification settings - Fork 3.6k
feat: add support for fsdp2 strategy in trainer #21184
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
deependujha
wants to merge
18
commits into
Lightning-AI:master
Choose a base branch
from
deependujha:feat/add-support-for-fsdp2-strategy
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
9f537c1
update
deependujha d8a4d84
add fsdp2 precision plugin
deependujha 35bf1a2
time to test fsdp2
deependujha cc6de82
works. i'm still worthy
deependujha daa8667
update
deependujha 9279f49
fix mypy issues and install-pkg ci
deependujha caa2dd9
update
deependujha 28a2359
Merge branch 'master' into feat/add-support-for-fsdp2-strategy
deependujha 6487295
fsdp2 tests started
deependujha 9389669
fsdp2 tests
deependujha b3ce371
could it be
deependujha 224a125
update
deependujha 6b05701
meow
deependujha 3e76d9e
update
deependujha e400215
Update src/lightning/fabric/utilities/init.py
deependujha a84b9b1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] cf6bbf1
update
deependujha 029ebff
nitpick. and pause fsdp2 dev for now
deependujha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
# Copyright The Lightning AI team. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
from contextlib import AbstractContextManager | ||
from typing import Any | ||
|
||
import torch | ||
from lightning_utilities import apply_to_collection | ||
from torch import Tensor | ||
from torch.nn import Module | ||
from typing_extensions import get_args, override | ||
|
||
from lightning.fabric.plugins.precision.fsdp import _PRECISION_INPUT | ||
from lightning.fabric.plugins.precision.utils import _convert_fp_tensor, _DtypeContextManager | ||
from lightning.pytorch.plugins.precision.precision import Precision | ||
from lightning.pytorch.utilities.exceptions import MisconfigurationException | ||
|
||
|
||
class FSDP2Precision(Precision): | ||
"""Precision plugin for training with FSDP2 (Fully Sharded Data Parallel v2). | ||
|
||
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. | ||
|
||
Args: | ||
precision: Full precision (32-true), half precision (16-true, bf16-true) or | ||
mixed precision (16-mixed, bf16-mixed). | ||
scaler: An optional :class:`torch.distributed.fsdp.sharded_grad_scaler.ShardedGradScaler` to use. | ||
|
||
Raises: | ||
ValueError: | ||
If unsupported ``precision`` is provided. | ||
|
||
""" | ||
|
||
def __init__(self, precision: _PRECISION_INPUT, scaler: Any = None) -> None: | ||
supported_precision = get_args(_PRECISION_INPUT) | ||
if precision not in supported_precision: | ||
raise ValueError( | ||
f"`precision={precision!r})` is not supported in FSDP." | ||
f" `precision` must be one of: {supported_precision}." | ||
) | ||
|
||
if scaler is not None: | ||
raise ValueError( | ||
f"`scaler` is not supported in `{self.__class__.__name__}`, found {scaler}." | ||
"Use `mixed-precision policy` instead to configure the scaler." | ||
) | ||
|
||
if "mixed" in precision: | ||
raise ValueError( | ||
f"`precision={precision!r}` is not supported in `{self.__class__.__name__}`." | ||
"Only `true` precision is supported." | ||
"Use `mixed-precision policy (mp_policy)` instead to configure mixed precision." | ||
) | ||
|
||
self.precision = precision | ||
|
||
precision_to_type = { | ||
"bf16-true": torch.bfloat16, | ||
"16-true": torch.float16, | ||
"32-true": torch.float32, | ||
} | ||
self._desired_input_dtype = precision_to_type[self.precision] | ||
|
||
@override | ||
def convert_module(self, module: Module) -> Module: | ||
if "true" in self.precision: | ||
return module.to(dtype=self._desired_input_dtype) | ||
return module | ||
|
||
@override | ||
def clip_grad_by_norm(self, *_: Any, **__: Any) -> None: | ||
# see https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel.clip_grad_norm_ | ||
# section `Gradient Clipping`, using `torch.nn.utils.clip_grad_norm_` is incorrect with FSDP. | ||
# To overcome this we need to call root_sharded_module.clip_grad_norm(clip_val), but we don't have a reference | ||
# to the root module | ||
raise MisconfigurationException( | ||
f"`gradient_clip_algorithm='norm'` is currently not supported for `{self.__class__.__name__}`" | ||
) | ||
|
||
@override | ||
def tensor_init_context(self) -> AbstractContextManager: | ||
return _DtypeContextManager(self._desired_input_dtype) | ||
|
||
@override | ||
def module_init_context(self) -> AbstractContextManager: | ||
# Use float32 for module parameter initialization to ensure numerical stability | ||
return _DtypeContextManager(self._desired_input_dtype) | ||
|
||
@override | ||
def forward_context(self) -> AbstractContextManager: | ||
return _DtypeContextManager(self._desired_input_dtype) | ||
|
||
@override | ||
def convert_input(self, data: Any) -> Any: | ||
return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self._desired_input_dtype) | ||
|
||
@override | ||
def convert_output(self, data: Any) -> Any: | ||
return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.