[英]Multiprocessing in Python: Is there a way to use pool.imap without accumulating memory?
我在 Python 中使用multiprocessing
模块来并行训练带有keras
神经网络,使用Pool(processes = 4)
对象和imap
。 这在每个“循环”后稳定地使用越来越多的内存,即每 4 个进程,直到它最终崩溃。
我使用memory_profiler
模块随着时间的推移跟踪我的内存使用情况,训练了 12 个网络。 这是使用香草imap
:
如果我将maxtasksperchild = 1
放入Pool
:
如果我使用imap(chunksize = 3)
:
在后一种情况下,一切正常,我只向池中的每个进程发送一个批次,因此问题似乎是这些进程携带有关先前批次的信息。 如果是这样,我可以强制池不这样做吗?
即使块解决方案似乎有效,我也不想使用它,因为
tqdm
模块跟踪进度,在块的情况下,它只会在每个块之后更新,这实际上意味着它根本不会真正跟踪任何东西,因为所有块同时完成(在此例子) 这是香草案例中的代码片段。 在其他两种情况下,我只是更改了Pool
的maxtasksperchild
参数和imap
的chunksize
参数:
def train_network(network):
(...)
return score
pool = Pool(processes = 4)
scores = pool.imap(train_network, networks)
scores = tqdm(scores, total = networks.size)
for (network, score) in zip(networks, scores):
network.score = score
pool.close()
pool.join()
不幸的是,python 中的multiprocessing
模块需要付出很大的代价。 数据大多不在进程之间共享,需要复制。 这将从 python 3.8 开始改变。
https://docs.python.org/3.8/library/multiprocessing.shared_memory.html
虽然,python 3.8 的正式发布时间是 2019 年 10 月 21 日,但你已经可以在github上下载了
我想出了一个似乎有效的解决方案。 我放弃了游泳池并制作了自己的简单排队系统。 除了不增加(虽然它确实增加了一点点,但我认为这是我将一些字典存储为日志),它甚至比上面的块解决方案消耗更少的内存:
我不知道为什么会这样。 也许Pool
对象只是占用了大量内存? 无论如何,这是我的代码:
def train_network(network):
(...)
return score
# Define queues to organise the parallelising
todo = mp.Queue(size = networks.size + 4)
done = mp.Queue(size = networks.size)
# Populate the todo queue
for idx in range(networks.size):
todo.put(idx)
# Add -1's which will be an effective way of checking
# if all todo's are finished
for _ in range(4):
todo.put(-1)
def worker(todo, done):
''' Network scoring worker. '''
from queue import Empty
while True:
try:
# Fetch the next todo
idx = todo.get(timeout = 1)
except Empty:
# The queue is never empty, so the silly worker has to go
# back and try again
continue
# If we have reached a -1 then stop
if idx == -1:
break
else:
# Score the network and store it in the done queue
score = train_network(networks[idx])
done.put((idx, score))
# Construct our four processes
processes = [mp.Process(target = worker,
args = (todo, done)) for _ in range(4)]
# Daemonise the processes, which closes them when
# they finish, and start them
for p in processes:
p.daemon = True
p.start()
# Set up the iterable with all the scores, and set
# up a progress bar
idx_scores = (done.get() for _ in networks)
pbar = tqdm(idx_scores, total = networks.size)
# Compute all the scores in parallel
for (idx, score) in pbar:
networks[idx].score = score
# Join up the processes and close the progress bar
for p in processes:
p.join()
pbar.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.