Lightning-AI / Lightning-AI/pytorch-lightning
Support gradient clipping by norm with FSDP
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 31.4k
- Forks
- 3.8k
- Avg merge
- 6d 7h
- Merged PRs (30d)
- 6
Description
### Description & Motivation
Our current implementation of gradient clipping for FSDP is limited to clipping by value only. Norm is not supported:
https://github.com/Lightning-AI/pytorch-lightning/blob/f75f3bc1c65a2bb3388ffd68b1ee70ed9741525c/src/lightning/pytorch/plugins/precision/fsdp.py#L77-L84
The reason is that clipping by norm needs to be called through the FSDP API and this wasn't realized in Lightning yet, because it can't be done directly through the optimizer (the FSDP module reference is required): https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel.clip_grad_norm_
### Pitch
Support clipping by norm.
Change the API from
```py
class Precision:
...
def clip_grad_by_norm(self, optimizer: Optimizer, clip_val: Union[int, float]) -> None:
...
```
to
```py
class Precision:
...
def clip_grad_by_norm(self, module: Module, optimizer: Optimizer, clip_val: Union[int, float]) -> None:
...
```
to take the module as input. The implementation in `FSDPPrecision` would then call `module.clip_grad_norm()` instead of `torch.nn.utils.clip_grad_norm_`.
The `LightningModule.clip_gradients()` method should then pass `self.trainer.model` to `self.trainer.precision_plugin.clip_gradients()`.
### Alternatives
There is not much else we can do. I believe the proposal above will lead to the least amount of breaking changes (only affects the signature of the precision plugin methods.
### Additional context
In Fabric's precision plugins, this is already done. We would need to do this on the Trainer side anyway sooner or later, if we want to unify the precision/strategy implementations.
cc @borda @awaelchli @carmocca
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked src/lightning/pytorch/plugins/precision/fsdp.py implementation and the Precision.clip_grad_by_norm API. Trace LightningModule.clip_gradients() through self.trainer.model and self.trainer.precision_plugin, and compare the existing Fabric precision-plugin handling. Done means FSDP norm clipping receives the module and uses the FSDP API without breaking other precision plugins.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, pytorch
- Domain
- distributed-systems, machine-learning
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100