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

Use variable_data() in tensor_to_numpy #22214

Closed
wants to merge 2 commits into from
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
7 changes: 1 addition & 6 deletions tools/autograd/templates/python_variable_methods.cpp
Expand Up @@ -428,12 +428,7 @@ static PyObject * THPVariable_numpy(PyObject* self, PyObject* arg)
HANDLE_TH_ERRORS
jit::tracer::warn("Converting a tensor to a NumPy array", jit::tracer::WARN_PYTHON_DATAFLOW);
auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
if (self_.requires_grad()) {
throw std::runtime_error(
"Can't call numpy() on Variable that requires grad. "
"Use var.detach().numpy() instead.");
}
return torch::utils::tensor_to_numpy(self_.tensor_data());
return torch::utils::tensor_to_numpy(self_);
END_HANDLE_TH_ERRORS
}

Expand Down
8 changes: 7 additions & 1 deletion torch/csrc/utils/tensor_numpy.cpp
Expand Up @@ -85,6 +85,11 @@ PyObject* tensor_to_numpy(const at::Tensor& tensor) {
if (tensor.type().backend() != Backend::CPU) {
throw TypeError("NumPy conversion for %s is not supported", tensor.type().toString().c_str());
}
if (tensor.requires_grad()) {
throw std::runtime_error(
"Can't call numpy() on Variable that requires grad. "
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error message is outdated. There are no more Variables in PyTorch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are in C++ still, see #13638. We should fix these once that proposal is implemented, though.

"Use var.detach().numpy() instead.");
}
auto dtype = aten_to_numpy_dtype(tensor.scalar_type());
auto sizes = to_numpy_shape(tensor.sizes());
auto strides = to_numpy_shape(tensor.strides());
Expand All @@ -110,7 +115,8 @@ PyObject* tensor_to_numpy(const at::Tensor& tensor) {
// object of the ndarray to the tensor and disabling resizes on the storage.
// This is not sufficient. For example, the tensor's storage may be changed
// via Tensor.set_, which can free the underlying memory.
PyObject* py_tensor = THPVariable_Wrap(make_variable(tensor, false));
TORCH_INTERNAL_ASSERT(tensor.is_variable());
PyObject* py_tensor = THPVariable_Wrap(tensor);
if (!py_tensor) throw python_error();
if (PyArray_SetBaseObject((PyArrayObject*)array.get(), py_tensor) == -1) {
return nullptr;
Expand Down