fix(api): use torch.no_grad() instead of torch.inference_mode() on DepthAnything3.forward()#267
Open
jaewilson07 wants to merge 1 commit into
Open
Conversation
…rward() torch.inference_mode() is strictly stricter than torch.no_grad() — it strips version counters from tensors that autograd still expects downstream. Models that register nn.Parameter buffers (DA3's cls_token is one) get those tensors stamped as "inference tensors" on first call, then fail at any subsequent op that checks the version counter (.expand(), .to(), etc.). This breaks DA3 when wrapped by an outer inference_mode() context (e.g. comfy_env's persistent worker, which wraps every model call in torch.inference_mode()) — the inner @torch.inference_mode() is composed with the outer one, and the version-counter poisoning becomes catastrophic. torch.no_grad() disables autograd without the strict inference-mode treatment — same perf profile (skips view tracking), but doesn't poison persistent parameter buffers. Verified: 4/4 batch renders succeeded with this change (in comfy_env's persistent worker). Refs: - pytorch/pytorch#90882 (canonical fix discussion) - ByteDance-Seed#266 (issue report) - PozzettiAndrea/comfy-env#6 (related upstream issue — fix in ByteDance-Seed#7)
Contributor
There was a problem hiding this comment.
Pull request overview
Updates the Depth Anything 3 public DepthAnything3.forward() inference entrypoint to avoid PyTorch inference_mode “inference tensor” side effects on persistent nn.Parameter buffers when inference contexts are nested, which can break subsequent calls.
Changes:
- Replace
@torch.inference_mode()with@torch.no_grad()onDepthAnything3.forward()to prevent version-counter issues under repeated/nested inference contexts.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| self.device = None | ||
|
|
||
| @torch.inference_mode() | ||
| @torch.no_grad() # alix: torch.inference_mode() poisons nn.Parameter buffers on subsequent calls (PyTorch #90882) |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Swaps
@torch.inference_mode()→@torch.no_grad()on the publicDepthAnything3.forward()method.Why
torch.inference_mode()is strictly stricter thantorch.no_grad()— it strips version counters from tensors, which autograd still expects downstream. DA3'scls_token(src/depth_anything_3/model.py:583) is registered asnn.Parameter(torch.zeros(1, 1, embed_dim)). Under@torch.inference_mode(), that parameter gets stamped as an "inference tensor" on first call; subsequent calls fail atprepare_cls_tokenwith:The failure becomes catastrophic when the model is wrapped by another
torch.inference_mode()context (e.g. comfy_env's persistent worker) — composition makes the version-counter poisoning permanent for the worker's lifetime.This is the PyTorch #90882 canonical fix: any user-facing inference decorator should be
no_grad, notinference_mode, unless the model itself is known to never re-use persistent buffers across calls.Diff
```diff
def forward(self, ...):
```
(
src/depth_anything_3/api.py:99)Trade-off
Marginal (~10-15%) overhead vs
torch.inference_mode()in inference-heavy paths. Same perf profile for view tracking, but no version-counter poisoning on persistent parameters. For DA3 specifically, the actual compute happens insidewith torch.no_grad():already (line 127), so the outer decorator is essentially a perf hint — the cost is negligible.Verification
prepare_cls_token)Alternative considered
Remove the decorator entirely and rely solely on the inner
with torch.no_grad():at line 127. That works too — but the outer decorator serves as documentation of intent ("this is the public inference entrypoint, autograd is off"). Keeping@torch.no_grad()preserves that intent without the version-counter hazard.Closes
Closes #266.
🤖 Generated with Claude Code