Skip to content

[FSDP2] Guard _unsharded_param access in to_accumulated_grad_if_needed - #194058

Closed
khazic wants to merge 1 commit into
pytorch:mainfrom
khazic:khazic/fix/fsdp2-accumulated-grad-guard
Closed

khazic wants to merge 1 commit into
pytorch:mainfrom
khazic:khazic/fix/fsdp2-accumulated-grad-guard

Conversation

@khazic

@khazic khazic commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Fixes an AttributeError in FSDPParam.to_accumulated_grad_if_needed.

The bug

def to_accumulated_grad_if_needed(self) -> None:
    # Access `_unsharded_param` to bypass the sharded state check since we
    # prefer to reshard before upcasting the gradient to save memory
    if (
        self.reduce_dtype is None
        or self._unsharded_param.grad is None      # <-- unguarded
        or self._unsharded_param.grad.dtype == self.reduce_dtype
    ):
        return

_unsharded_param is created by init_unsharded_param and dropped by
free_unsharded_param, so it is not always present. init_unsharded_param
guards its own access with hasattr("_unsharded_param") for that reason; this
call site does not, and a parameter that has not been all-gathered raises

AttributeError: 'FSDPParam' object has no attribute '_unsharded_param'.
Did you mean: 'unsharded_param'?

How it shows up

Fine-tuning a 9.65B vision-language model with fully_shard and a mixed-precision
policy whose reduce_dtype differs from the parameter dtype. Gradient
accumulation then walks parameters that took no part in the forward pass, in this
case a vision tower under text-only batches, and those were never gathered.

It reproduces:

  • with optimizer offload enabled and disabled;
  • with reshard_after_forward=False.

The last one is the informative case: the attribute is not being freed after a
gather, it is never created at all for those parameters.

The fix

Read the attribute through getattr and fold "not gathered" into the condition
the method already returns early for. A parameter that was never gathered has no
unsharded gradient to upcast, so behaviour is unchanged for every parameter that
does have one, and the local variable also avoids three repeated attribute
lookups on the hot path.

Validation

Two full fine-tunes on the same code, data and configuration, one of which
previously failed at this line every time:

model before after
4.66B trains (never hit the path) unchanged, step 35, loss 0.209, grad-norm 0.68
9.65B AttributeError at step 1, three times trains, step 2, loss 0.234, grad-norm 7.24

The 9.65B loss and grad-norm land in the same range as the 4.66B run that was
never affected, so the guard is not masking a gradient that should have been
upcast.

`FSDPParam.to_accumulated_grad_if_needed` reads `self._unsharded_param`
without checking that it exists. The attribute is created by
`init_unsharded_param` and dropped again by `free_unsharded_param`, so a
parameter that has not been all-gathered does not have it, and the read raises

    AttributeError: 'FSDPParam' object has no attribute '_unsharded_param'

`init_unsharded_param` already guards its own access with `hasattr` for the same
reason; this call site does not.

Hit while fine-tuning a 9.65B vision-language model with fully_shard and mixed
precision, where gradient accumulation runs over parameters that took no part in
the forward pass (a vision tower under text-only batches). It reproduces with and
without optimizer offload and with `reshard_after_forward=False`, so it is not
specific to resharding: the attribute is simply never created for those
parameters.

A parameter that was never gathered has no unsharded gradient to upcast, which is
exactly the case the method already returns early for, so the guard extends the
existing condition rather than changing behaviour for parameters that do have
one.

Signed-off-by: khazic <[email protected]>
@khazic
khazic requested a review from weifengpy as a code owner August 19, 2026 10:01
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Aug 19, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194058

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (3 Unrelated Failures)

As of commit 3fb08a4 with merge base 1859e8b (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: khazic / name: khazic (3fb08a4)

@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@khazic

khazic commented Aug 23, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 23, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
pytorch#194058)

Fixes an `AttributeError` in `FSDPParam.to_accumulated_grad_if_needed`.

### The bug

```python
def to_accumulated_grad_if_needed(self) -> None:
    # Access `_unsharded_param` to bypass the sharded state check since we
    # prefer to reshard before upcasting the gradient to save memory
    if (
        self.reduce_dtype is None
        or self._unsharded_param.grad is None      # <-- unguarded
        or self._unsharded_param.grad.dtype == self.reduce_dtype
    ):
        return
```

`_unsharded_param` is created by `init_unsharded_param` and dropped by
`free_unsharded_param`, so it is not always present. `init_unsharded_param`
guards its own access with `hasattr("_unsharded_param")` for that reason; this
call site does not, and a parameter that has not been all-gathered raises

```
AttributeError: 'FSDPParam' object has no attribute '_unsharded_param'.
Did you mean: 'unsharded_param'?
```

### How it shows up

Fine-tuning a 9.65B vision-language model with `fully_shard` and a mixed-precision
policy whose `reduce_dtype` differs from the parameter dtype. Gradient
accumulation then walks parameters that took no part in the forward pass, in this
case a vision tower under text-only batches, and those were never gathered.

It reproduces:

* with optimizer offload enabled and disabled;
* with `reshard_after_forward=False`.

The last one is the informative case: the attribute is not being freed after a
gather, it is never created at all for those parameters.

### The fix

Read the attribute through `getattr` and fold "not gathered" into the condition
the method already returns early for. A parameter that was never gathered has no
unsharded gradient to upcast, so behaviour is unchanged for every parameter that
does have one, and the local variable also avoids three repeated attribute
lookups on the hot path.

### Validation

Two full fine-tunes on the same code, data and configuration, one of which
previously failed at this line every time:

| model | before | after |
|---|---|---|
| 4.66B | trains (never hit the path) | unchanged, step 35, loss 0.209, grad-norm 0.68 |
| 9.65B | AttributeError at step 1, three times | trains, step 2, loss 0.234, grad-norm 7.24 |

The 9.65B loss and grad-norm land in the same range as the 4.66B run that was
never affected, so the guard is not masking a gradient that should have been
upcast.

Pull Request resolved: pytorch#194058
Approved by: https://github.com/weifengpy
aeytkn pushed a commit to aeytkn/pytorch that referenced this pull request Sep 3, 2026
pytorch#194058)

Fixes an `AttributeError` in `FSDPParam.to_accumulated_grad_if_needed`.

### The bug

```python
def to_accumulated_grad_if_needed(self) -> None:
    # Access `_unsharded_param` to bypass the sharded state check since we
    # prefer to reshard before upcasting the gradient to save memory
    if (
        self.reduce_dtype is None
        or self._unsharded_param.grad is None      # <-- unguarded
        or self._unsharded_param.grad.dtype == self.reduce_dtype
    ):
        return
```

`_unsharded_param` is created by `init_unsharded_param` and dropped by
`free_unsharded_param`, so it is not always present. `init_unsharded_param`
guards its own access with `hasattr("_unsharded_param")` for that reason; this
call site does not, and a parameter that has not been all-gathered raises

```
AttributeError: 'FSDPParam' object has no attribute '_unsharded_param'.
Did you mean: 'unsharded_param'?
```

### How it shows up

Fine-tuning a 9.65B vision-language model with `fully_shard` and a mixed-precision
policy whose `reduce_dtype` differs from the parameter dtype. Gradient
accumulation then walks parameters that took no part in the forward pass, in this
case a vision tower under text-only batches, and those were never gathered.

It reproduces:

* with optimizer offload enabled and disabled;
* with `reshard_after_forward=False`.

The last one is the informative case: the attribute is not being freed after a
gather, it is never created at all for those parameters.

### The fix

Read the attribute through `getattr` and fold "not gathered" into the condition
the method already returns early for. A parameter that was never gathered has no
unsharded gradient to upcast, so behaviour is unchanged for every parameter that
does have one, and the local variable also avoids three repeated attribute
lookups on the hot path.

### Validation

Two full fine-tunes on the same code, data and configuration, one of which
previously failed at this line every time:

| model | before | after |
|---|---|---|
| 4.66B | trains (never hit the path) | unchanged, step 35, loss 0.209, grad-norm 0.68 |
| 9.65B | AttributeError at step 1, three times | trains, step 2, loss 0.234, grad-norm 7.24 |

The 9.65B loss and grad-norm land in the same range as the 4.66B run that was
never affected, so the guard is not masking a gradient that should have been
upcast.

Pull Request resolved: pytorch#194058
Approved by: https://github.com/weifengpy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants