使用 Python 多处理解决令人尴尬的并行问题

Posted

技术标签:

【中文标题】使用 Python 多处理解决令人尴尬的并行问题【英文标题】:Solving embarassingly parallel problems using Python multiprocessing 【发布时间】:2011-01-22 11:43:18 【问题描述】:

如何使用multiprocessing 对付embarrassingly parallel problems?

令人尴尬的并行问题通常由三个基本部分组成:

    读取输入数据(来自文件、数据库、tcp 连接等)。 对输入数据运行计算,其中每个计算独立于任何其他计算写入计算结果(到文件、数据库、tcp 连接等)。

我们可以在两个维度上并行化程序:

第 2 部分可以在多个内核上运行,因为每个计算都是独立的;处理顺序无关紧要。 每个部分都可以独立运行。第 1 部分可以将数据放入输入队列,第 2 部分可以将数据从输入队列中拉出并将结果放入输出队列,第 3 部分可以将结果从输出队列中拉出并写出。

这似乎是并发编程中最基本的模式,但我仍然无法解决它,所以让我们编写一个规范的示例来说明如何使用多处理来完成此操作

这是一个示例问题:给定一个CSV file,输入整数行,计算它们的总和。把问题分成三部分,都可以并行运行:

    将输入文件处理成原始数据(整数列表/可迭代) 并行计算数据的总和 输出总和

以下是解决这三个任务的传统单进程绑定 Python 程序:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# basicsums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file.
"""

import csv
import optparse
import sys

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    return cli_parser


def parse_input_csv(csvfile):
    """Parses the input CSV and yields tuples with the index of the row
    as the first element, and the integers of the row as the second
    element.

    The index is zero-index based.

    :Parameters:
    - `csvfile`: a `csv.reader` instance

    """
    for i, row in enumerate(csvfile):
        row = [int(entry) for entry in row]
        yield i, row


def sum_rows(rows):
    """Yields a tuple with the index of each input list of integers
    as the first element, and the sum of the list of integers as the
    second element.

    The index is zero-index based.

    :Parameters:
    - `rows`: an iterable of tuples, with the index of the original row
      as the first element, and a list of integers as the second element

    """
    for i, row in rows:
        yield i, sum(row)


def write_results(csvfile, results):
    """Writes a series of results to an outfile, where the first column
    is the index of the original row of data, and the second column is
    the result of the calculation.

    The index is zero-index based.

    :Parameters:
    - `csvfile`: a `csv.writer` instance to which to write results
    - `results`: an iterable of tuples, with the index (zero-based) of
      the original row as the first element, and the calculated result
      from that row as the second element

    """
    for result_row in results:
        csvfile.writerow(result_row)


def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")
    infile = open(args[0])
    in_csvfile = csv.reader(infile)
    outfile = open(args[1], 'w')
    out_csvfile = csv.writer(outfile)
    # gets an iterable of rows that's not yet evaluated
    input_rows = parse_input_csv(in_csvfile)
    # sends the rows iterable to sum_rows() for results iterable, but
    # still not evaluated
    result_rows = sum_rows(input_rows)
    # finally evaluation takes place as a chain in write_results()
    write_results(out_csvfile, result_rows)
    infile.close()
    outfile.close()


if __name__ == '__main__':
    main(sys.argv[1:])

让我们使用这个程序并重写它以使用多处理来并行化上述三个部分。下面是这个新的并行化程序的骨架,需要对其进行充实以解决 cmets 中的各个部分:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# multiproc_sums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file, using multiple processes if desired.
"""

import csv
import multiprocessing
import optparse
import sys

NUM_PROCS = multiprocessing.cpu_count()

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    cli_parser.add_option('-n', '--numprocs', type='int',
            default=NUM_PROCS,
            help="Number of processes to launch [DEFAULT: %default]")
    return cli_parser


def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")
    infile = open(args[0])
    in_csvfile = csv.reader(infile)
    outfile = open(args[1], 'w')
    out_csvfile = csv.writer(outfile)

    # Parse the input file and add the parsed data to a queue for
    # processing, possibly chunking to decrease communication between
    # processes.

    # Process the parsed data as soon as any (chunks) appear on the
    # queue, using as many processes as allotted by the user
    # (opts.numprocs); place results on a queue for output.
    #
    # Terminate processes when the parser stops putting data in the
    # input queue.

    # Write the results to disk as soon as they appear on the output
    # queue.

    # Ensure all child processes have terminated.

    # Clean up files.
    infile.close()
    outfile.close()


if __name__ == '__main__':
    main(sys.argv[1:])

这些代码,以及用于测试目的的another piece of code that can generate example CSV files,可以是found on github。

如果您能提供任何有关并发专家如何解决此问题的见解,我将不胜感激。


以下是我在考虑这个问题时遇到的一些问题。解决任何/所有问题的奖励积分:

我应该有子进程来读取数据并将其放入队列中,还是主进程可以在读取所有输入之前不阻塞地执行此操作? 同样,我应该有一个子进程来将结果从已处理队列中写出,还是主进程可以这样做而不必等待所有结果? 我应该使用processes pool 进行求和运算吗? 如果是,我应该在池上调用什么方法来让它开始处理进入输入队列的结果,而不阻塞输入和输出进程? apply_async()? map_async()? imap()? imap_unordered()? 假设我们不需要在数据进入时从输入和输出队列中抽出,而是可以等到所有输入都被解析并计算出所有结果(例如,因为我们知道所有输入和输出都适合系统记忆)。我们是否应该以任何方式更改算法(例如,不要在 I/O 的同时运行任何进程)?

【问题讨论】:

哈哈,我喜欢 embarrassingly-parallel 这个词。我很惊讶这是我第一次听到这个词,它是指代这个概念的好方法。 【参考方案1】:

我的解决方案有一个额外的花里胡哨,以确保输出的顺序与输入的顺序相同。我使用 multiprocessing.queue 在进程之间发送数据,发送停止消息,以便每个进程都知道退出检查队列。我认为源中的 cmets 应该清楚发生了什么,但如果不让我知道。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# multiproc_sums.py
"""A program that reads integer values from a CSV file and writes out their
sums to another CSV file, using multiple processes if desired.
"""

import csv
import multiprocessing
import optparse
import sys

NUM_PROCS = multiprocessing.cpu_count()

def make_cli_parser():
    """Make the command line interface parser."""
    usage = "\n\n".join(["python %prog INPUT_CSV OUTPUT_CSV",
            __doc__,
            """
ARGUMENTS:
    INPUT_CSV: an input CSV file with rows of numbers
    OUTPUT_CSV: an output file that will contain the sums\
"""])
    cli_parser = optparse.OptionParser(usage)
    cli_parser.add_option('-n', '--numprocs', type='int',
            default=NUM_PROCS,
            help="Number of processes to launch [DEFAULT: %default]")
    return cli_parser

class CSVWorker(object):
    def __init__(self, numprocs, infile, outfile):
        self.numprocs = numprocs
        self.infile = open(infile)
        self.outfile = outfile
        self.in_csvfile = csv.reader(self.infile)
        self.inq = multiprocessing.Queue()
        self.outq = multiprocessing.Queue()

        self.pin = multiprocessing.Process(target=self.parse_input_csv, args=())
        self.pout = multiprocessing.Process(target=self.write_output_csv, args=())
        self.ps = [ multiprocessing.Process(target=self.sum_row, args=())
                        for i in range(self.numprocs)]

        self.pin.start()
        self.pout.start()
        for p in self.ps:
            p.start()

        self.pin.join()
        i = 0
        for p in self.ps:
            p.join()
            print "Done", i
            i += 1

        self.pout.join()
        self.infile.close()

    def parse_input_csv(self):
            """Parses the input CSV and yields tuples with the index of the row
            as the first element, and the integers of the row as the second
            element.

            The index is zero-index based.

            The data is then sent over inqueue for the workers to do their
            thing.  At the end the input process sends a 'STOP' message for each
            worker.
            """
            for i, row in enumerate(self.in_csvfile):
                row = [ int(entry) for entry in row ]
                self.inq.put( (i, row) )

            for i in range(self.numprocs):
                self.inq.put("STOP")

    def sum_row(self):
        """
        Workers. Consume inq and produce answers on outq
        """
        tot = 0
        for i, row in iter(self.inq.get, "STOP"):
                self.outq.put( (i, sum(row)) )
        self.outq.put("STOP")

    def write_output_csv(self):
        """
        Open outgoing csv file then start reading outq for answers
        Since I chose to make sure output was synchronized to the input there
        is some extra goodies to do that.

        Obviously your input has the original row number so this is not
        required.
        """
        cur = 0
        stop = 0
        buffer = 
        # For some reason csv.writer works badly across processes so open/close
        # and use it all in the same process or else you'll have the last
        # several rows missing
        outfile = open(self.outfile, "w")
        self.out_csvfile = csv.writer(outfile)

        #Keep running until we see numprocs STOP messages
        for works in range(self.numprocs):
            for i, val in iter(self.outq.get, "STOP"):
                # verify rows are in order, if not save in buffer
                if i != cur:
                    buffer[i] = val
                else:
                    #if yes are write it out and make sure no waiting rows exist
                    self.out_csvfile.writerow( [i, val] )
                    cur += 1
                    while cur in buffer:
                        self.out_csvfile.writerow([ cur, buffer[cur] ])
                        del buffer[cur]
                        cur += 1

        outfile.close()

def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if len(args) != 2:
        cli_parser.error("Please provide an input file and output file.")

    c = CSVWorker(opts.numprocs, args[0], args[1])

if __name__ == '__main__':
    main(sys.argv[1:])

【讨论】:

这是唯一实际使用multiprocessing的答案。赏金给你,先生。 真的有必要在输入和数字运算过程中调用join吗?难道你不能只加入输出过程而忽略其他过程吗?如果是这样,是否还有充分的理由在所有其他进程上调用 join " 所以线程知道要退出" -- " 在线程之间发送数据" -- 线程和进程非常不同。我看到这可能会让新手感到困惑。更重要的是在得到如此多投票的答案中使用正确的术语。您正在这里开始新的流程。您不仅仅是在当前进程中生成线程。 很公平。我已经修正了文本。 很棒的答案。非常感谢。【参考方案2】:

聚会迟到了……

joblib 在多处理之上有一个层来帮助实现并行 for 循环。除了非常简单的语法外,它还为您提供了诸如延迟调度作业和更好的错误报告等功能。

作为免责声明,我是joblib的原作者。

【讨论】:

那么 Joblib 是否能够并行处理 I/O,还是必须手动处理?你能提供一个使用 Joblib 的代码示例吗?谢谢!【参考方案3】:

我意识到我参加聚会有点晚了,但我最近发现了GNU parallel,并想展示用它完成这项典型任务是多么容易。

cat input.csv | parallel ./sum.py --pipe > sums

sum.py 可以这样做:

#!/usr/bin/python

from sys import argv

if __name__ == '__main__':
    row = argv[-1]
    values = (int(value) for value in row.split(','))
    print row, ':', sum(values)

Parallel 将为input.csv 中的每一行运行sum.py(当然是并行的),然后将结果输出到sums。明显优于multiprocessing麻烦

【讨论】:

GNU 并行文档将为输入文件中的每一行调用一个新的 Python 解释器。启动一个新的 Python 解释器的开销(在我的 i7 MacBook Pro 上使用固态驱动器,Python 2.7 大约需要 30 毫秒,Python 3.3 大约需要 40 毫秒)可能大大超过处理单个数据行并导致大量浪费的时间和比预期更差的收益。对于您的示例问题,我可能会联系multiprocessing.Pool。【参考方案4】:

老派。

p1.py

import csv
import pickle
import sys

with open( "someFile", "rb" ) as source:
    rdr = csv.reader( source )
    for line in eumerate( rdr ):
        pickle.dump( line, sys.stdout )

p2.py

import pickle
import sys

while True:
    try:
        i, row = pickle.load( sys.stdin )
    except EOFError:
        break
    pickle.dump( i, sum(row) )

p3.py

import pickle
import sys
while True:
    try:
        i, row = pickle.load( sys.stdin )
    except EOFError:
        break
    print i, row

这是多处理的最终结构。

python p1.py | python p2.py | python p3.py

是的,shell 已在操作系统级别将这些组合在一起。这对我来说似乎更简单,而且效果很好。

是的,使用 pickle(或 cPickle)会产生更多开销。然而,这种简化似乎值得付出努力。

如果您希望文件名成为p1.py 的参数,那么更改很简单。

更重要的是,像下面这样的函数非常好用。

def get_stdin():
    while True:
        try:
            yield pickle.load( sys.stdin )
        except EOFError:
            return

这允许你这样做:

for item in get_stdin():
     process item

这很简单,但它很容易允许您运行多个 P2.py 副本。

你有两个问题:扇出和扇入。 P1.py 必须以某种方式扇出多个 P2.py。 P2.py 必须以某种方式将他们的结果合并到一个 P3.py 中。

老式的扇出方法是“推送”架构,非常有效。

理论上,多个 P2.py 从一个公共队列中拉取是资源的最优分配。这通常是理想的,但它也是相当多的编程。编程真的有必要吗?还是轮询处理就足够了?

实际上,您会发现让 P1.py 在多个 P2.py 之间进行简单的“循环”处理可能非常好。您将 P1.py 配置为通过命名管道处理 P2.py 的 n 个副本。 P2.py 将分别从其相应的管道中读取。

如果一个 P2.py 获得了所有“最坏情况”数据并远远落后怎么办?是的,循环赛并不完美。但它比只有一个 P2.py 要好,您可以通过简单的随机化来解决这种偏差。

从多个 P2.py 到一个 P3.py 的扇入仍然有点复杂。在这一点上,老派的方法不再是有利的。 P3.py 需要使用select 库从多个命名管道中读取,以交错读取。

【讨论】:

当我想启动 p2.py 的n 实例时,这会不会变得更麻烦,让它们消耗和处理由 p1.py 输出的 m 块的 r 行,并拥有p3.py 从所有n p2.py 实例中获取mxr 结果? 我没有在问题中看到这个要求。 (也许这个问题太长太复杂,无法突出该要求。)重要的是,您应该有充分的理由期望多个 p2 实际解决您的性能问题。虽然我们可以假设这种情况可能存在,但 *nix 架构从未有过这种情况,也没有人认为适合添加它。拥有多个 p2 可能会有所帮助。但是在过去的 40 年里,没有人认为有足够的必要让它成为外壳的一流部件。 那是我的错。让我编辑并澄清这一点。为了帮助我改进问题,混淆是否来自使用sum()?这是为了说明目的。我可以用do_something() 代替它,但我想要一个具体的、易于理解的例子(见第一句话)。实际上,我的 do_something() 占用大量 CPU 资源,但令人尴尬的是可并行化,因为每个调用都是独立的。因此,多个核心对此会有所帮助。 “混淆是否来自 sum() 的使用?”显然不是。我不知道你为什么会提到它。你说:“当我想启动 p2.py 的 n 个实例时,这会不会变得更麻烦”。我没有在问题中看到该要求。【参考方案5】:

可能也可以在第 1 部分中引入一些并行性。像 CSV 这样简单的格式可能不是问题,但如果输入数据的处理明显慢于数据的读取,您可以读取更大的块,然后继续读取,直到找到“行分隔符”( CSV 情况下的换行符,但这又取决于读取的格式;如果格式足够复杂,则不起作用)。

这些块,每个可能包含多个条目,然后可以被分配给一组并行进程,从队列中读取作业,在那里对其进行解析和拆分,然后放置在队列中以进行第 2 阶段。

【讨论】:

以上是关于使用 Python 多处理解决令人尴尬的并行问题的主要内容,如果未能解决你的问题,请参考以下文章

为啥这种令人尴尬的并行算法的性能没有随着多线程而提高?

python 令人尴尬的并行问题的进程/线程池

使用 NumPy 在 Python 中进行简单的多处理

为啥我没有看到通过 Python 中的多处理加速?

在 Python 中划分大文件以进行多处理的最佳方法是啥?

许多内核上令人尴尬的并行工作扩展性差