Как каждый использует многопроцессорную обработку для занятия смущающе параллельными проблемами?
Проблемы параллели Embarassingly обычно состоят из трех базовых деталей:
Мы можем параллелизировать программу в двух размерах:
Это кажется самым основным шаблоном в параллельном программировании, но я все еще потерян в попытке решить его, поэтому давайте запишем канонический пример, чтобы проиллюстрировать, как это сделано с помощью многопроцессорной обработки.
Вот проблема в качестве примера: Учитывая файл CSV со строками целых чисел, как введено, вычислите их суммы. Разделите проблему на три части, которые могут все работать параллельно:
Ниже является традиционным, единственный процесс связал программу 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:])
Давайте возьмем эту программу и перепишем ее для использования многопроцессорной обработки для параллелизации этих трех частей, обрисованных в общих чертах выше. Ниже скелет этой новой, параллелизированной программы, которая должна быть изложена в деталях для обращения к частям в комментариях:
#!/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.
Я ценил бы любое понимание здесь относительно того, как Вы гуру параллелизма приблизитесь к этой проблеме.
Вот некоторые вопросы, которые я имел при размышлении об этой проблеме. Бонусные очки для обращения к любому/всему:
В моем решении есть дополнительный колокольчик и свисток, чтобы убедиться, что порядок вывода совпадает с порядком ввода. Я использую 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:])
Old School.
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
Да, оболочка объединила их вместе на уровне ОС. Мне это кажется проще и работает очень красиво.
Да, использование 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 настроен для работы с n копиями P2.py через именованные каналы. Каждый P2.py будет читать из своего канала.
Что делать, если один P2.py получает все данные «наихудшего случая» и сильно отстает? Да, круговая система не идеальна. Но это лучше, чем один P2.py, и вы можете решить эту проблему с помощью простой рандомизации.
Разветвление нескольких P2.py на один P3.py все же немного сложнее. На этом этапе старый подход перестает быть выгодным. P3.py необходимо читать из нескольких именованных каналов, используя библиотеку select
, чтобы чередовать чтения.
Вероятно, можно ввести немного параллелизма в часть 1. Вероятно, это не проблема с форматом, который так же прост, как CSV, но если обработка входных данных заметно медленнее, чем чтение данных, вы можете читать большие куски, а затем продолжать чтение, пока не найдете «разделитель строк» (новая строка в случае CSV, но опять же, это зависит от формата чтения; не работает, если формат достаточно сложный).
Эти блоки, каждый из которых, вероятно, содержит несколько записей, затем могут быть переданы толпе параллельных процессов, считывающих задания из очереди, где они анализированы и разделены, а затем помещены в очередь на этапе 2.