Skip to content

Commit 347a7d9

Browse files
albanDpytorchmergebot
authored andcommitted
Deprecate decorating classes with torch.no_grad and similar (#89522)
Fixes #89450 I would have completely removed it but I don't think this is particularly urgent and there are some use of it in the wild: https://github.com/search?q=%2Ftorch%5C.no_grad%5C%28%5C%29%5Cnclass%2F&type=code So we might as well take one release to do it. Pull Request resolved: #89522 Approved by: https://github.com/lezcano, https://github.com/soulitzer, https://github.com/janeyx99
1 parent 2de38a0 commit 347a7d9

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

test/test_autograd.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,30 @@ def graph_desc(fn):
6363

6464
class TestAutograd(TestCase):
6565

66+
def test_grad_mode_class_decoration(self):
67+
# Decorating class is deprecated and should not be used
68+
with self.assertWarnsRegex(UserWarning, "Decorating classes is deprecated"):
69+
@torch.no_grad()
70+
class Foo():
71+
pass
72+
73+
# Decorating functions or methods is fine though
74+
with warnings.catch_warnings(record=True) as w:
75+
@torch.no_grad()
76+
def foo():
77+
pass
78+
79+
class Foo2():
80+
@torch.no_grad()
81+
def __init__(self):
82+
pass
83+
84+
@torch.no_grad()
85+
def foo(self):
86+
pass
87+
88+
self.assertEqual(len(w), 0)
89+
6690
def test_tensor_grad_warnings(self):
6791
dummy = torch.empty(1)
6892

torch/autograd/grad_mode.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import torch
33
import functools
44
import inspect
5+
import warnings
56
from typing import Any, Callable, TypeVar, cast
67

78
__all__ = ['no_grad', 'enable_grad', 'set_grad_enabled',
@@ -18,6 +19,12 @@ class _DecoratorContextManager:
1819
"""Allow a context manager to be used as a decorator"""
1920

2021
def __call__(self, func: F) -> F:
22+
if inspect.isclass(func):
23+
warnings.warn("Decorating classes is deprecated and will be disabled in "
24+
"future versions. You should only decorate functions or methods. "
25+
"To preserve the current behavior of class decoration, you can "
26+
"directly decorate the `__init__` method and nothing else.")
27+
2128
if inspect.isgeneratorfunction(func):
2229
return self._wrap_generator(func)
2330

0 commit comments

Comments
 (0)