gpt4 book ai didi

python - Cython 并行计算中可变数量的 worker

转载 作者:行者123 更新时间:2023-11-28 18:46:09 27 4
gpt4 key购买 nike

我编写了以下代码作为 Cython 中并行计算的一个简单示例。在我的示例中,我创建了两个工作对象并让它们并行运行。我想概括此实现以使用可变数量的 worker 。问题是我找不到存储 Worker 对象数组并使用 nogil 访问它们的方法。有办法吗?显然,我可以使用下面的技术(最多达到一些合理的硬编码数量的 worker )一起破解一些合理的东西,但如果存在的话,我想要一些更优雅和可维护的东西。

这是代码。关键部分在 if use_parallel 下:

# distutils: language = c
# cython: cdivision = True
# cython: boundscheck = False
# cython: wraparound = False
# cython: profile = False

cimport numpy as cnp
import numpy as np
from cython.parallel import parallel, prange
from libc.math cimport sin
cimport openmp
cnp.import_array()

ctypedef cnp.float64_t FLOAT_t
ctypedef cnp.intp_t INT_t
ctypedef cnp.ulong_t INDEX_t
ctypedef cnp.uint8_t BOOL_t

cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef Worker worker1
cdef Worker worker2

def __init__(Parent self, list numbers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)
self.worker1 = Worker()
self.worker2 = Worker()

cpdef run(Parent self, bint use_parallel):
cdef unsigned int i
cdef float best
cdef int num_threads
cdef cnp.ndarray[FLOAT_t, ndim=1] numbers = <cnp.ndarray[FLOAT_t, ndim=1]> self.numbers
cdef FLOAT_t[:] buffer1 = self.numbers[:(len(numbers)//2)]
buffer_size1 = buffer1.shape[0]
cdef FLOAT_t[:] buffer2 = self.numbers[(len(numbers)//2):]
buffer_size2 = buffer2.shape[0]

# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(2, num_threads=2):
if i == 0:
self.worker1.run(buffer1, buffer_size1)
elif i == 1:
self.worker2.run(buffer2, buffer_size2)

else:
print 'serial'
self.worker1.run(buffer1, buffer_size1)
self.worker2.run(buffer2, buffer_size2)

#Make sure they both ran
print self.worker1.output, self.worker2.output

# Choose the worker that had the best solution
best = min(self.worker1.output, self.worker2.output)

return best

cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0

cdef void run(Worker self, FLOAT_t[:] numbers, unsigned int buffer_size) nogil:
cdef unsigned int i
cdef unsigned int j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value
for i in range(n):
for j in range(n):
value = sin(numbers[i]*numbers[j])
if first or (value < best):
best = value
first = False
self.output = best

我的测试脚本是这样的:

from parallel import Parent
import time
data = list(range(20000))
parent = Parent(data)

t0 = time.time()
output = parent.run(False)
t1 = time.time()

print 'Serial Result: %f' % output
print 'Serial Time: %f' % (t1-t0)

t0 = time.time()
output = parent.run(True)
t1 = time.time()

print 'Parallel Result: %f' % output
print 'Parallel Time: %f' % (t1-t0)

它产生这个输出:

serial
-1.0 -1.0
Serial Result: -1.000000
Serial Time: 6.428081
parallel
-1.0 -1.0
Parallel Result: -1.000000
Parallel Time: 4.006907

最后,这是我的 setup.py:

from distutils.core import setup
from distutils.extension import Extension
import sys
import numpy

#Determine whether to use Cython
if '--cythonize' in sys.argv:
cythonize_switch = True
del sys.argv[sys.argv.index('--cythonize')]
else:
cythonize_switch = False

#Find all includes
numpy_include = numpy.get_include()

#Set up the ext_modules for Cython or not, depending
if cythonize_switch:
from Cython.Distutils import build_ext
from Cython.Build import cythonize
ext_modules = cythonize([Extension("parallel.parallel", ["parallel/parallel.pyx"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])])
else:
ext_modules = [Extension("parallel.parallel", ["parallel/parallel.c"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])]

#Create a dictionary of arguments for setup
setup_args = {'name':'parallel-test',
'version':'0.1.0',
'author':'Jason Rudy',
'author_email':'jcrudy@gmail.com',
'packages':['parallel',],
'license':'LICENSE.txt',
'description':'Let\'s try some parallel programming in Cython',
'long_description':open('README.md','r').read(),
'py_modules' : [],
'ext_modules' : ext_modules,
'classifiers' : ['Development Status :: 3 - Alpha'],
'requires':[]}

#Add the build_ext command only if cythonizing
if cythonize_switch:
setup_args['cmdclass'] = {'build_ext': build_ext}

#Finally
setup(**setup_args)

必须用gcc编译,mac上可以用

export CC=gcc

在运行 setup.py 之前。

最佳答案

据我所知,nogil 不支持 Python 对象的索引(以及强制转换,...​​)。因此,在将 Workers 存储在内置 Python list 中时,我们会收到以下消息:

cdef list workers
workers = [Worker(), Worker(), Worker(), Worker()]

留言:

Indexing Python object not allowed without gil



您可以尝试这样的操作 (经过测试,似乎工作正常):

此处的解决方法是对 nogil 部分中要使用的所有内容使用 C 语法:

cdef PyObject ** workers
cdef int * buf_sizes
cdef FLOAT_t ** buffers

并使用来自 libc.stdlib 的旧式 malloc 分配这些数组。

代码:

# distutils: language = c
# cython: cdivision = True
# cython: boundscheck = False
# cython: wraparound = False
# cython: profile = False

cimport numpy as cnp
import numpy as np
from cython.parallel import parallel, prange
from libc.math cimport sin
cimport openmp
cnp.import_array()

ctypedef cnp.float64_t FLOAT_t
ctypedef cnp.intp_t INT_t
ctypedef cnp.ulong_t INDEX_t
ctypedef cnp.uint8_t BOOL_t

# Pyobject is the C representation of a Python object
# This allows casts in both ways...
cimport cython
from cpython cimport PyObject

# C memory alloc features
from libc.stdlib cimport malloc, free


cdef FLOAT_t MAXfloat64 = np.float64(np.inf)


cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef PyObject ** workers
cdef int nb_workers

cdef int * buf_sizes
cdef FLOAT_t ** buffers

def __init__(Parent self, list numbers, int n_workers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)

# Define number of workers
self.nb_workers = n_workers
self.workers = <PyObject **>malloc(self.nb_workers*cython.sizeof(cython.pointer(PyObject)))

# Populate pool
cdef int i
cdef PyObject py_obj
cdef object py_workers
py_workers = [] # For correct ref count
for i in xrange(self.nb_workers):
py_workers.append(Worker())
self.workers[i] = <PyObject*>py_workers[i]

self.init_buffers()

cdef init_buffers(Parent self):
cdef int i, j
cdef int num_threads
cdef int pos, pos_end
cdef int buf_size

num_threads = self.nb_workers
buf_size = len(self.numbers) // num_threads

# Init buffers
self.buffers = <FLOAT_t **>malloc(self.nb_workers * cython.sizeof(cython.pointer(FLOAT_t)))
self.buf_sizes = <int *>malloc(self.nb_workers * cython.sizeof(int))
pos = 0
buf_size = len(self.numbers) // num_threads

for i in xrange(self.nb_workers):

# If we are treating the last worker do everything left
if (i == self.nb_workers-1):
buf_size = len(self.numbers) - pos

self.buf_sizes[i] = buf_size
pos_end = pos + buf_size

self.buffers[i] = <FLOAT_t *>malloc(buf_size * cython.sizeof(FLOAT_t))

for j in xrange(pos, pos_end):
self.buffers[i][j-pos] = <FLOAT_t>self.numbers[j]

pos = pos + buf_size



cpdef run(Parent self, bint use_parallel):

cdef int i
cdef FLOAT_t best

# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(self.nb_workers, num_threads=self.nb_workers):
# Changed "FLOAT_t[:]" python object to C array "FLOAT_t *"
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])

else:
print 'serial'
for i in xrange(self.nb_workers):
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])

# Make sure they ran
for i in xrange(self.nb_workers):
print (<Worker>self.workers[i]).output

# Choose the worker that had the best solution
best = MAXfloat64
for i in xrange(self.nb_workers):
if ((<Worker>self.workers[i]).output < best):
best = (<Worker>self.workers[i]).output

return best


cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0


# Changed "FLOAT_t[:]" python object to C dyn array "FLOAT_t *"
cdef void run(Worker self, FLOAT_t * numbers, unsigned int buffer_size) nogil:
cdef unsigned int i, j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value

# Added initialization
best = MAXfloat64
for i in range(n):
for j in range(n):
value = sin(numbers[i]*numbers[j])
if first or (value < best):
best = value
first = False
self.output = best

测试:

from parallel import Parent
import time
data = list(range(20000))
parent = Parent(data, 7)

t0 = time.time()
output = parent.run(False)
t1 = time.time()

print 'Serial Result: %f' % output
print 'Serial Time: %f' % (t1-t0)

t0 = time.time()
output = parent.run(True)
t1 = time.time()

print 'Parallel Result: %f' % output
print 'Parallel Time: %f' % (t1-t0)

输出:

serial
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
Serial Result: -1.000000
Serial Time: 2.741364
parallel
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
Parallel Result: -1.000000
Parallel Time: 0.536419

希望这符合您的要求,或者至少提供了一些想法...请分享您的最终实现...

关于python - Cython 并行计算中可变数量的 worker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19783238/

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