Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 18 additions & 14 deletions test/test_autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,24 +169,28 @@ def backward(self, grad_output):
self.assertEqual(v.grad.data, torch.zeros(shape))

def test_legacy_function_deprecation_warning(self):
with warnings.catch_warnings(record=True) as w:
# Ensure warnings are being shown
warnings.simplefilter("always")
def check_warning(func):
with warnings.catch_warnings(record=True) as w:
# Ensure warnings are being shown
warnings.simplefilter("always")

# Trigger Warning
class MyFunction(Function):
def forward(self, x):
return x
# Trigger Warning
func()

# Check warning occurs
self.assertIn(
'Legacy autograd function with non-static forward method is deprecated',
str(w[0]))

def backward(self, grad_output):
return grad_output
class MyFunction(Function):
def forward(self, x):
return x

MyFunction()(torch.randn(3, 4))
def backward(self, grad_output):
return grad_output

# Check warning occurs
self.assertIn(
'Legacy autograd function with non-static forward method is deprecated',
str(w[0]))
check_warning(lambda: MyFunction()(torch.randn(3, 4)))
check_warning(lambda: MyFunction.apply(torch.randn(3, 4)))

def test_invalid_gradients(self):
class MyFunction(Function):
Expand Down
7 changes: 7 additions & 0 deletions torch/csrc/autograd/python_function.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,13 @@ PyObject *THPFunction_apply(PyObject *cls, PyObject *inputs)
std::vector<c10::IValue>(),
autograd::Node::peek_at_next_sequence_nr());

THPObjectPtr _legacy(PyObject_GetAttrString(cls, "_is_legacy"));
if (_legacy == Py_True) {
TORCH_WARN("Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3. ",
"Please use new-style autograd function with static forward method. ",
"(Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)");
}

THPObjectPtr backward_cls(PyObject_GetAttrString(cls, "_backward_cls"));
if (!backward_cls) return nullptr;
THPObjectPtr ctx_obj(PyObject_CallFunctionObjArgs(backward_cls, nullptr));
Expand Down