From 4a6c178f73f523410f237dc16da4eb1ed34a427d Mon Sep 17 00:00:00 2001 From: Leon Voland <31935319+leonvol@users.noreply.github.com> Date: Tue, 5 Jan 2021 15:22:35 -0800 Subject: [PATCH] Improve documentation and warning message for creation of a tensor with 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 https://github.com/pytorch/pytorch/issues/46741. Pull Request resolved: https://github.com/pytorch/pytorch/pull/49516 Reviewed By: mrshenli Differential Revision: D25746115 Pulled By: mruberry fbshipit-source-id: 3e534a8f2bc1f083a2835440d324bd6f30798ad4 --- torch/_torch_docs.py | 3 +++ torch/csrc/utils/tensor_numpy.cpp | 11 ++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/torch/_torch_docs.py b/torch/_torch_docs.py index 4a1c36df7497..7d34b080e252 100644 --- a/torch/_torch_docs.py +++ b/torch/_torch_docs.py @@ -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]) diff --git a/torch/csrc/utils/tensor_numpy.cpp b/torch/csrc/utils/tensor_numpy.cpp index c2a67f8df06b..01471d3b62ac 100644 --- a/torch/csrc/utils/tensor_numpy.cpp +++ b/torch/csrc/utils/tensor_numpy.cpp @@ -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."); }