Fix the issue that Bad interaction between no_grad and numpy conversi… (#38906)

Summary:
…on(https://github.com/pytorch/pytorch/issues/37000)
Pull Request resolved: https://github.com/pytorch/pytorch/pull/38906

Differential Revision: D21722033

Pulled By: albanD

fbshipit-source-id: f22aec8106e4546e828aba15be606e9d9f3eeffa
This commit is contained in:
chengjinfang
2020-05-26 16:14:54 -07:00
committed by Facebook GitHub Bot
parent 2e6ee853ab
commit f188b52b59
2 changed files with 15 additions and 4 deletions

View File

@ -84,10 +84,10 @@ PyObject* tensor_to_numpy(const at::Tensor& tensor) {
"can't convert %s layout tensor to numpy."
"convert the tensor to a strided layout first.", c10::str(tensor.layout()).c_str());
}
if (tensor.requires_grad()) {
if (at::GradMode::is_enabled() && tensor.requires_grad()) {
throw std::runtime_error(
"Can't call numpy() on Variable that requires grad. "
"Use var.detach().numpy() instead.");
"Can't call numpy() on Tensor that requires grad. "
"Use tensor.detach().numpy() instead.");
}
auto dtype = aten_to_numpy_dtype(tensor.scalar_type());
auto sizes = to_numpy_shape(tensor.sizes());