使用多处理运行子进程时出现系统错误

时间:2013-02-27 17:26:01

标签: python numpy multiprocessing

我在使用Multiprocessing软件包(在Amazon EC2上的Ubuntu 12.04上使用numpy 1.7.0的python 2.73)并行执行一些简单的基于numpy的矩阵代数计算时遇到系统错误(如下所示)。我的代码适用于较小的矩阵大小,但崩溃较大的(具有足够的可用内存)

我使用的矩阵的大小是实质性的(我的代码运行良好的1000000x10浮点密集矩阵,但崩溃1000000x500 - 我顺便将这些矩阵传递到子进程/从子进程传递)。 10 vs 500是运行时参数,其他所有内容保持不变(输入数据,其他运行时参数等)。

我也尝试使用python3运行相同的(移植的)代码 - 对于更大的矩阵,子进程进入睡眠/空闲模式(而不是像在python 2.7中那样崩溃)并且程序/子进程只是挂在那里做没有。对于较小的矩阵,代码可以使用python3运行良好。

任何建议都会受到高度赞赏(我的想法已经不多了)

错误讯息:

Exception in thread Thread-5: Traceback (most recent call last):  
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()   File "/usr/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)   File "/usr/lib/python2.7/multiprocessing/pool.py", line 319, in _handle_tasks
    put(task) SystemError: NULL result without error in PyObject_Call

我使用的多处理代码:

def runProcessesInParallelAndReturn(proc, listOfInputs, nParallelProcesses):
    if len(listOfInputs) == 0:
        return
    # Add result queue to the list of argument tuples.
    resultQueue = mp.Manager().Queue()
    listOfInputsNew = [(argumentTuple, resultQueue) for argumentTuple in listOfInputs]
    # Create and initialize the pool of workers.
    pool = mp.Pool(processes = nParallelProcesses)
    pool.map(proc, listOfInputsNew)
    # Run the processes.
    pool.close()
    pool.join()
    # Return the results.
    return [resultQueue.get() for i in range(len(listOfInputs))]

下面是为每个子进程执行的“proc”。基本上,它使用numpy解决了许多线性方程组(它在子进程内部构造了所需的矩阵)并将结果作为另一个矩阵返回。再次,它适用于一个运行时参数的较小值,但对于较大的参数崩溃(或在python3中挂起)。

def solveForLFV(param):
    startTime = time.time()
    (chunkI, LFVin, XY, sumLFVinOuterProductLFVallPlusPenaltyTerm, indexByIndexPurch, outerProductChunkSize, confWeight), queue = param
    LFoutChunkSize = XY.shape[0]
    nLFdim = LFVin.shape[1]
    sumLFVinOuterProductLFVpurch = np.zeros((nLFdim, nLFdim))
    LFVoutChunk = np.zeros((LFoutChunkSize, nLFdim))
    for LFVoutIndex in xrange(LFoutChunkSize):
        LFVInIndexListPurch = indexByIndexPurch[LFVoutIndex]
        sumLFVinOuterProductLFVpurch[:, :] = 0.
        LFVInIndexChunkLow, LFVInIndexChunkHigh = getChunkBoundaries(len(LFVInIndexListPurch), outerProductChunkSize)
        for LFVInIndexChunkI in xrange(len(LFVInIndexChunkLow)):
            LFVinSlice = LFVin[LFVInIndexListPurch[LFVInIndexChunkLow[LFVInIndexChunkI] : LFVInIndexChunkHigh[LFVInIndexChunkI]], :]
            sumLFVinOuterProductLFVpurch += sum(LFVinSlice[:, :, np.newaxis] * LFVinSlice[:, np.newaxis, :])
        LFVoutChunk[LFVoutIndex, :] = np.linalg.solve(confWeight * sumLFVinOuterProductLFVpurch + sumLFVinOuterProductLFVallPlusPenaltyTerm, XY[LFVoutIndex, :])
    queue.put((chunkI, LFVoutChunk))
    print 'solveForLFV: ', time.time() - startTime, 'sec'
    sys.stdout.flush()

1 个答案:

答案 0 :(得分:6)

500,000,000非常大:如果你使用的是float64,那就是40亿字节,或大约4 GB。 (10,000,000浮点数组将是80万字节,或大约80 MB - 更小。)我预计这个问题与多处理有关,试图通过管道拾取数组发送到子进程。

由于您使用的是unix平台,因此可以通过利用fork()(用于创建多处理工作者)的内存继承行为来避免此行为。我已经取得了很大的成功,这个hack(被this project撕掉),由评论描述。

### A helper for letting the forked processes use data without pickling.
_data_name_cands = (
    '_data_' + ''.join(random.sample(string.ascii_lowercase, 10))
    for _ in itertools.count())
class ForkedData(object):
    '''
    Class used to pass data to child processes in multiprocessing without
    really pickling/unpickling it. Only works on POSIX.

    Intended use:
        - The master process makes the data somehow, and does e.g.
            data = ForkedData(the_value)
        - The master makes sure to keep a reference to the ForkedData object
          until the children are all done with it, since the global reference
          is deleted to avoid memory leaks when the ForkedData object dies.
        - Master process constructs a multiprocessing.Pool *after*
          the ForkedData construction, so that the forked processes
          inherit the new global.
        - Master calls e.g. pool.map with data as an argument.
        - Child gets the real value through data.value, and uses it read-only.
    '''
    # TODO: does data really need to be used read-only? don't think so...
    # TODO: more flexible garbage collection options
    def __init__(self, val):
        g = globals()
        self.name = next(n for n in _data_name_cands if n not in g)
        g[self.name] = val
        self.master_pid = os.getpid()

    @property
    def value(self):
        return globals()[self.name]

    def __del__(self):
        if os.getpid() == self.master_pid:
            del globals()[self.name]