85

マルチプロセッシングを使用して、驚異的並列の問題にどのように取り組むのでしょうか。

驚異的並列問題は通常、次の3つの基本部分で構成されます。

  1. 入力データを読み取ります(ファイル、データベース、tcp接続などから)。
  2. 入力データに対して計算を実行します。各計算は他の計算から独立しています
  3. 計算結果を(ファイル、データベース、tcp接続などに)書き込みます。

プログラムを2次元で並列化できます。

  • 各計算は独立しているため、パート2は複数のコアで実行できます。処理の順序は関係ありません。
  • 各パーツは独立して実行できます。パート1はデータを入力キューに配置し、パート2はデータを入力キューからプルして結果を出力キューに配置し、パート3は結果を出力キューからプルして書き出すことができます。

これは並行プログラミングの最も基本的なパターンのようですが、それを解決しようとするとまだ迷っています。そこで、マルチプロセッシングを使用してこれがどのように行われるかを示す標準的な例を書いてみましょう

問題の例を次に示します。入力として整数の行を含むCSVファイルが与えられた場合、それらの合計を計算します。問題を3つの部分に分けます。これらはすべて、並行して実行できます。

  1. 入力ファイルを生データ(整数のリスト/反復可能ファイル)に処理します
  2. 並行してデータの合計を計算します
  3. 合計を出力します

以下は、これら3つのタスクを解決する従来の単一プロセスバインド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:])

このプログラムを書き直して、マルチプロセッシングを使用して上記の3つの部分を並列化してみましょう。以下は、この新しい並列化されたプログラムのスケルトンであり、コメントの部分に対処するために具体化する必要があります。

#!/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:])

これらのコード、およびテスト目的でサンプルCSVファイルを生成できる別のコードは、githubにあります。

並行性の達人がこの問題にどのように取り組むかについて、ここで洞察をいただければ幸いです。


この問題について考えるときに私が持っていたいくつかの質問があります。いずれか/すべてに対処するためのボーナスポイント:

  • データを読み込んでキューに入れるための子プロセスが必要ですか、それともメインプロセスがすべての入力が読み取られるまでブロックせずにこれを行うことができますか?
  • 同様に、処理されたキューから結果を書き出すための子プロセスが必要ですか、それともメインプロセスがすべての結果を待たずにこれを行うことができますか?
  • 合計操作に プロセスプールを使用する必要がありますか?
  • データが入力されたときに入力キューと出力キューを吸い上げる必要はなかったが、すべての入力が解析され、すべての結果が計算されるまで待つことができたとします(たとえば、すべての入力と出力がシステムメモリに収まることがわかっているため)。アルゴリズムを何らかの方法で変更する必要がありますか(たとえば、I / Oと同時にプロセスを実行しないでください)?
4

5 に答える 5

73

私のソリューションには、出力の順序が入力の順序と同じであることを確認するための追加のベルとホイッスルがあります。multiprocessing.queueを使用してプロセス間でデータを送信し、停止メッセージを送信して、各プロセスがキューのチェックを終了することを認識できるようにします。ソースのコメントは何が起こっているのかを明確にするはずだと思いますが、そうでない場合は私に知らせてください。

#!/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:])
于 2010-03-02T16:16:29.283 に答える
7

パーティーに遅れて来る...

joblibには、マルチプロセッシングの上にレイヤーがあり、forループを並列化するのに役立ちます。非常に単純な構文に加えて、ジョブの遅延ディスパッチやより優れたエラー報告などの機能を提供します。

免責事項として、私はjoblibの最初の作者です。

于 2014-01-15T08:13:10.277 に答える
5

パーティーに少し遅れていることに気づきましたが、最近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は、 (もちろん並列に)のsum.pyすべての行に対して実行され、結果をに出力します。面倒よりも明らかに良いinput.csvsumsmultiprocessing

于 2013-08-23T11:00:50.367 に答える
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

はい、シェルはこれらをOSレベルで結び付けています。それは私には簡単に思え、とてもうまく機能します。

はい、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の複数のコピーを簡単に実行することはできません。

ファンアウトとファンインの2つの問題があります。P1.pyは、どういうわけか複数のP2.pyにファンアウトする必要があります。そして、P2.pyはどういうわけかそれらの結果を単一のP3.pyにマージする必要があります。

ファンアウトへの昔ながらのアプローチは「プッシュ」アーキテクチャであり、これは非常に効果的です。

理論的には、共通のキューから複数のP2.pyをプルすることが、リソースの最適な割り当てです。これは多くの場合理想的ですが、かなりの量のプログラミングでもあります。プログラミングは本当に必要ですか?それとも、ラウンドロビン処理で十分でしょうか?

実際には、P1.pyに複数のP2.py間での単純な「ラウンドロビン」処理を実行させるのは非常に良い場合があります。名前付きパイプを介してP2.pyのn個のコピーを処理するようにP1.pyを構成します。P2.pyは、それぞれ適切なパイプから読み取ります。

1つのP2.pyがすべての「最悪の場合」のデータを取得し、大幅に遅れている場合はどうなりますか?はい、ラウンドロビンは完璧ではありません。ただし、P2.pyが1つしかない場合よりも優れており、単純なランダム化でこのバイアスに対処できます。

複数のP2.pyから1つのP3.pyへのファンインは、まだ少し複雑です。この時点で、昔ながらのアプローチは有利ではなくなります。P3.pyは、selectライブラリを使用して複数の名前付きパイプから読み取りを行い、読み取りをインターリーブする必要があります。

于 2010-03-01T21:55:50.367 に答える
0

パート1にも少し並列処理を導入することはおそらく可能です。CSVのように単純な形式ではおそらく問題にはなりませんが、入力データの処理がデータの読み取りよりも著しく遅い場合は、より大きなチャンクを読み取ってから、「行区切り文字」が見つかるまで読み取りを続けることができます( CSVの場合は改行ですが、これも読み取った形式によって異なります。形式が十分に複雑な場合は機能しません)。

これらのチャンクは、それぞれ複数のエントリを含む可能性があり、キューからジョブを読み取る並列プロセスの群集にファームオフされ、そこで解析および分割されてから、ステージ2のキューに配置されます。

于 2010-03-10T16:39:09.467 に答える