8

我在使用 Multiprocessing 包(Amazon EC2 上的 Ubuntu 12.04 上的 python 2.73 和 numpy 1.7.0)并行执行一些简单的基于 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()
4

1 回答 1

6

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

由于您在 unix 平台上,您可以通过利用fork()(用于创建多处理工作人员)的内存继承行为来避免这种行为。正如评论所描述的,我在这个 hack(从这个项目中删除)取得了巨大的成功。

### 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]
于 2013-03-01T23:40:52.883 回答