Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[functorch] .data should not work for grad, jvp, vjp #94817

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion aten/src/ATen/functorch/TensorWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ c10::intrusive_ptr<TensorImpl> TensorWrapper::shallow_copy_and_detach(
}

void TensorWrapper::shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) {
TORCH_INTERNAL_ASSERT(false, "NYI");
TORCH_CHECK(false, "mutating directly with `.data` inside functorch transform is not allowed.");
}

TensorWrapper::TensorWrapper(
Expand Down
16 changes: 16 additions & 0 deletions test/functorch/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,22 @@ def test_jvpvjpvmap(self, device, dtype, op):
result = jvpvjpvmap_fn(*new_args)
self.assertEqual(result, expected)

def test_data_write_errors_under_transform(self, device):
t = torch.randn(3, 3, device=device)

def fn(t):
t.data = torch.randn(3, 3)
return t.sum()

msg = "mutating directly with `.data` inside functorch transform"
with self.assertRaisesRegex(RuntimeError, msg):
grad(fn)(t)

with self.assertRaisesRegex(RuntimeError, msg):
vjp(fn, t)

with self.assertRaisesRegex(RuntimeError, msg):
jvp(fn, (t,), (torch.randn_like(t),))


only_for = ("cpu", "cuda")
Expand Down