gpt4 book ai didi

python - 通过 Cython 将 C++ vector 传递给 Numpy,无需自动复制和处理内存管理

转载 作者:IT老高 更新时间:2023-10-28 23:16:56 26 4
gpt4 key购买 nike

处理大型矩阵(NxM 与 1K <= N <= 20K & 10K <= M <= 200K),我经常需要通过 Cython 将 Numpy 矩阵传递给 C++ 以完成工作,这可以按预期工作&无需复制。

然而,有时我需要在 C++ 中启动和预处理矩阵并将其传递给 Numpy (Python 3.6)。让我们假设矩阵是线性化的(所以大小是 N*M 并且它是一维矩阵 - col/row 主要在这里无关紧要)。按照这里的信息:exposing C-computed arrays in Python without data copies &修改它以实现 C++ 兼容性,我能够传递 C++ 数组。

问题是如果我想使用标准 vector 而不是初始化数组,我会得到段错误。例如,考虑以下文件:

fast.h

#include <iostream>
#include <vector>

using std::cout; using std::endl; using std::vector;
int* doit(int length);

fast.cpp

#include "fast.h"
int* doit(int length) {
// Something really heavy
cout << "C++: doing it fast " << endl;

vector<int> WhyNot;

// Heavy stuff - like reading a big file and preprocessing it
for(int i=0; i<length; ++i)
WhyNot.push_back(i); // heavy stuff

cout << "C++: did it really fast" << endl;
return &WhyNot[0]; // or WhyNot.data()
}

faster.pyx

cimport numpy as np
import numpy as np
from libc.stdlib cimport free
from cpython cimport PyObject, Py_INCREF

np.import_array()

cdef extern from "fast.h":
int* doit(int length)

cdef class ArrayWrapper:
cdef void* data_ptr
cdef int size

cdef set_data(self, int size, void* data_ptr):
self.data_ptr = data_ptr
self.size = size

def __array__(self):
print ("Cython: __array__ called")
cdef np.npy_intp shape[1]
shape[0] = <np.npy_intp> self.size
ndarray = np.PyArray_SimpleNewFromData(1, shape,
np.NPY_INT, self.data_ptr)
print ("Cython: __array__ done")
return ndarray

def __dealloc__(self):
print("Cython: __dealloc__ called")
free(<void*>self.data_ptr)
print("Cython: __dealloc__ done")


def faster(length):
print("Cython: calling C++ function to do it")
cdef int *array = doit(length)
print("Cython: back from C++")
cdef np.ndarray ndarray
array_wrapper = ArrayWrapper()
array_wrapper.set_data(length, <void*> array)
print("Ctyhon: array wrapper set")
ndarray = np.array(array_wrapper, copy=False)
ndarray.base = <PyObject*> array_wrapper
Py_INCREF(array_wrapper)
print("Cython: all done - returning")
return ndarray

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy

ext_modules = [Extension(
"faster",
["faster.pyx", "fast.cpp"],
language='c++',
extra_compile_args=["-std=c++11"],
extra_link_args=["-std=c++11"]
)]

setup(
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
include_dirs=[numpy.get_include()]
)

如果你用

构建这个
python setup.py build_ext --inplace

并运行 Python 3.6 解释器,如果您输入以下内容,则在尝试几次后会出现 seg 错误。

>>> from faster import faster
>>> a = faster(1000000)
Cython: calling C++ function to do it
C++: doing it fast
C++: did it really fast
Cython: back from C++
Ctyhon: array wrapper set
Cython: __array__ called
Cython: __array__ done
Cython: all done - returning
>>> a = faster(1000000)
Cython: calling C++ function to do it
C++: doing it fast
C++: did it really fast
Cython: back from C++
Ctyhon: array wrapper set
Cython: __array__ called
Cython: __array__ done
Cython: all done - returning
Cython: __dealloc__ called
Segmentation fault (core dumped)

需要注意的几点:

  • 如果您使用数组而不是 vector (在 fast.cpp 中),这将非常有效!
  • 如果您调用 faster(1000000) 并将结果放入 variable a 以外的其他内容中,这将起作用。

如果您输入较小的数字,例如 faster(10),您将获得更详细的信息,例如:

Cython: calling C++ function to do it
C++: doing it fast
C++: did it really fast
Cython: back from C++
Ctyhon: array wrapper set
Cython: __array__ called
Cython: __array__ done
Cython: all done - returning
Cython: __dealloc__ called <--- Perhaps this happened too early or late?
*** Error in 'python': double free or corruption (fasttop): 0x0000000001365570 ***
======= Backtrace: =========
More info here ....

令人费解的是,为什么数组不会发生这种情况?无论如何!

我经常使用 vector ,并且希望能够在这些场景中使用它们。

最佳答案

我认为@FlorianWeimer 的回答提供了一个不错的解决方案(分配一个 vector 并将其传递给您的 C++ 函数)但应该可以从 doit 返回一个 vector 并使用移动构造函数避免复制。

from libcpp.vector cimport vector

cdef extern from "<utility>" namespace "std" nogil:
T move[T](T) # don't worry that this doesn't quite match the c++ signature

cdef extern from "fast.h":
vector[int] doit(int length)

# define ArrayWrapper as holding in a vector
cdef class ArrayWrapper:
cdef vector[int] vec
cdef Py_ssize_t shape[1]
cdef Py_ssize_t strides[1]

# constructor and destructor are fairly unimportant now since
# vec will be destroyed automatically.

cdef set_data(self, vector[int]& data):
self.vec = move(data)
# @ead suggests `self.vec.swap(data)` instead
# to avoid having to wrap move

# now implement the buffer protocol for the class
# which makes it generally useful to anything that expects an array
def __getbuffer__(self, Py_buffer *buffer, int flags):
# relevant documentation http://cython.readthedocs.io/en/latest/src/userguide/buffer.html#a-matrix-class
cdef Py_ssize_t itemsize = sizeof(self.vec[0])

self.shape[0] = self.vec.size()
self.strides[0] = sizeof(int)
buffer.buf = <char *>&(self.vec[0])
buffer.format = 'i'
buffer.internal = NULL
buffer.itemsize = itemsize
buffer.len = self.v.size() * itemsize # product(shape) * itemsize
buffer.ndim = 1
buffer.obj = self
buffer.readonly = 0
buffer.shape = self.shape
buffer.strides = self.strides
buffer.suboffsets = NULL

然后您应该可以将其用作:

cdef vector[int] array = doit(length)
cdef ArrayWrapper w
w.set_data(array) # "array" itself is invalid from here on
numpy_array = np.asarray(w)

编辑: Cython 不太擅长使用 C++ 模板 - 它坚持编写 std::move<vector<int>>(...)而不是 std::move(...)然后让 C++ 推断类型。这有时会导致 std::move 出现问题。 .如果您遇到问题,那么最好的解决方案通常是只告诉 Cython 您想要的重载:

 cdef extern from "<utility>" namespace "std" nogil:
vector[int] move(vector[int])

关于python - 通过 Cython 将 C++ vector 传递给 Numpy,无需自动复制和处理内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45133276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com