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

fix_tensor_from_numpy_mem_leak_bug #8391

Merged
merged 9 commits into from
Jun 9, 2022
1 change: 1 addition & 0 deletions oneflow/api/python/framework/tensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ static PyObject* PyTensorObject_type(PyObject* self, PyObject* args, PyObject* k
ASSERT(CopyBetweenMirroredTensorAndNumpy<T>(PyTensor_Unpack(self), copied, \
BlobNumpyCopyUtil<T>::From, "mut", \
/*block_host_until_done=*/false)); \
Py_DECREF(copied); \
Py_RETURN_NONE; \
END_HANDLE_ERRORS \
}
Expand Down
10 changes: 7 additions & 3 deletions oneflow/api/python/functional/tensor_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ class LocalTensorSharedNumpyDataFunctor {
if (!PyArray_IS_C_CONTIGUOUS(array)) {
OF_LOG_ONCE(LOG(WARNING) << "OneFlow don't support non-contiguous array now, "
"and we will copy the array to a contiguous one.");
// PyArray_GETCONTIGUOUS will return a reference if array is already contiguous,
// otherwise return a (contiguous) copy of the array.
// Note: Increment the reference count for array occurs whether the array is continuous or not
array = PyArray_GETCONTIGUOUS(array);
} else {
Py_INCREF(obj);
}

// Build TensorMeta
Expand All @@ -264,13 +269,12 @@ class LocalTensorSharedNumpyDataFunctor {
auto tensor_meta = std::make_shared<MirroredTensorMeta>(shape, strides, data_type, device, 0);

// Build TensorBuffer
const auto& Free = [obj](char* dptr) {
const auto& Free = [array](char* dptr) {
CHECK_JUST(Global<ForeignLockHelper>::Get()->WithScopedAcquire([&]() -> Maybe<void> {
Py_DECREF(obj);
Py_DECREF(array);
return Maybe<void>::Ok();
}));
};
Py_INCREF(obj); // make TensorBuffer hold ndarray
hjchen2 marked this conversation as resolved.
Show resolved Hide resolved
void* data_ptr = PyArray_DATA(array);
auto array_size_in_bytes = PyArray_NBYTES(array);
auto tensor_data = std::make_shared<vm::TensorStorage>();
Expand Down