Skip to content

Commit

Permalink
Improve documentation and warning message for creation of a tensor wi…
Browse files Browse the repository at this point in the history
…th from_numpy() (#49516)

Summary:
Implements very simple changes suggested in the short discussion of the issue. Updated documentation to inform user that creation of tensor with memory mapped read only numpy arrays will probably cause a crash of the program. The displayed warning message was also updated to contain the information about issues concerning the use of a memory mapped read only numpy array. Closes #46741.

Pull Request resolved: #49516

Reviewed By: mrshenli

Differential Revision: D25746115

Pulled By: mruberry

fbshipit-source-id: 3e534a8f2bc1f083a2835440d324bd6f30798ad4
  • Loading branch information
leonvol authored and facebook-github-bot committed Jan 5, 2021
1 parent 9529ae3 commit 4a6c178
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
3 changes: 3 additions & 0 deletions torch/_torch_docs.py
Expand Up @@ -3080,6 +3080,9 @@ def merge_dicts(*dicts):
``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``,
and ``numpy.bool``.
.. warning::
Writing to a tensor created from a read-only NumPy array is not supported and
will result in undefined behavior.
Example::
>>> a = numpy.array([1, 2, 3])
Expand Down
11 changes: 6 additions & 5 deletions torch/csrc/utils/tensor_numpy.cpp
Expand Up @@ -136,11 +136,12 @@ at::Tensor tensor_from_numpy(PyObject* obj, bool warn_if_not_writeable/*=true*/)
if (!PyArray_ISWRITEABLE(array) && warn_if_not_writeable) {
TORCH_WARN_ONCE(
"The given NumPy array is not writeable, and PyTorch does "
"not support non-writeable tensors. This means you can write to the "
"underlying (supposedly non-writeable) NumPy array using the tensor. "
"You may want to copy the array to protect its data or make it writeable "
"before converting it to a tensor. This type of warning will be "
"suppressed for the rest of this program.");
"not support non-writeable tensors. Writing to this tensor is not "
"supported and will result in undefined behavior. "
"You may want to copy the "
"array to protect its data or make it writeable before converting it to "
"a tensor. "
"This type of warning will be suppressed for the rest of this program.");

}

Expand Down

0 comments on commit 4a6c178

Please sign in to comment.