Wie benutzt man multiprocessing, um embarrassingly parallel problems anzugehen?Peinlich parallele Probleme mit Python Multiprocessing lösen
Peinlicher parallel Probleme bestehen typischerweise aus drei Hauptteilen:
- lesen Eingangsdaten (aus einer Datei, Datenbank, TCP-Verbindung, etc.).
- Führen Sie Berechnungen für die Eingabedaten durch, wobei jede Berechnung unabhängig von einer anderen Berechnung ist.
- Schreiben Sie Ergebnisse von Berechnungen (zu einer Datei, Datenbank, Tcp-Verbindung, etc.).
wir das Programm in zwei Dimensionen parallelisieren können:
- Teil 2 auf mehrere Kerne ausgeführt werden kann, da jede Berechnung unabhängig ist; Reihenfolge der Verarbeitung spielt keine Rolle.
- Jeder Teil kann unabhängig voneinander ausgeführt werden. Teil 1 kann Daten in eine Eingabewarteschlange stellen, Teil 2 kann Daten aus der Eingabewarteschlange ziehen und Ergebnisse in eine Ausgabewarteschlange stellen, und Teil 3 kann Ergebnisse aus der Ausgabewarteschlange ziehen und aufschreiben.
Dies scheint ein grundlegendes Muster in paralleler Programmierung, aber ich bin immer noch bei dem Versuch, es verloren zu lösen, so sie ein kanonisches Beispiel schreiben zu veranschaulichen, wie diese Verwendung erfolgt Multiprozessing.
Hier ist das Beispielproblem: Gegeben eine CSV file mit Reihen von ganzen Zahlen als Eingabe, berechnen Sie ihre Summen. Trennen Sie das Problem in drei Teile, die alle parallel ausgeführt werden können:
- Prozess die Eingabedatei in Rohdaten (Listen/Iterables von ganzen Zahlen)
- Berechnen Sie die Summe der Daten, parallel
- Ausgang die Summen
unten traditionelle, Single-Process-Python-Programm gebunden, die diese drei Aufgaben lösen:
#!/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:])
Nehmen wir dieses Programm und schreiben es um, um Multiprocessing zu verwenden, um die drei oben beschriebenen Teile zu parallelisieren. Unten ist ein Skelett dieser neuen, parallelisierte Programm, das die Teile in den Kommentaren zur Adresse werden muss konkretisiert:
#!/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:])
Diese Teile des Codes können sowie another piece of code that can generate example CSV files für Testzwecke, found on github sein.
Ich würde mich über jede Einsicht freuen, wie Sie sich mit Nebenläufigkeitsgurus diesem Problem nähern würden.
Hier sind einige Fragen, die ich hatte, als über dieses Problem nachzudenken. Bonuspunkte für die Adressierung jeden/alle:
- Soll ich untergeordnete Prozesse in den Daten zu lesen und sie in die Warteschlange platzieren, oder kann der Hauptprozess tut dies ohne, bis alle Eingänge Blockierung gelesen wird?
- Soll ich einen untergeordneten Prozess zum Schreiben der Ergebnisse aus der verarbeiteten Warteschlange haben, oder kann der Hauptprozess dies tun, ohne auf alle Ergebnisse warten zu müssen?
- Sollte ich eine processes pool für die Summenoperationen verwenden?
- Wenn ja, welche Methode rufe ich den Pool auf, damit er mit der Verarbeitung der Ergebnisse in der Eingabewarteschlange beginnt, ohne die Eingabe- und Ausgabeprozesse zu blockieren? apply_async()? map_async()? imap()? imap_unordered()?
- Angenommen, wir mussten die Eingabe- und Ausgabewarteschlangen nicht als Daten eingeben, sondern konnten warten, bis alle Eingaben analysiert wurden und alle Ergebnisse berechnet wurden (z. B. weil wir alle Ein- und Ausgaben kennen in den Systemspeicher passen). Sollten wir den Algorithmus in irgendeiner Weise ändern (z. B. keine Prozesse gleichzeitig mit I/O ausführen)?
Haha, ich liebe den Begriff peinlich-parallel. Ich bin überrascht, dass dies das erste Mal ist, dass ich den Begriff gehört habe, es ist eine großartige Möglichkeit, sich auf dieses Konzept zu beziehen. –