python - 为什么 multiprocessing 在执行一定数量的任务后突然停止?

标签 python multiprocessing pytorch

我正在尝试编写一些代码来并行处理一堆任务。基本上,脚本组织如下。

import multiprocessing as mp


def obj_train(x):
    return x.train()


class ServerModel(nn.Module):
    self.S = nn.Parameter(torch.rand(x, y), requires_grad=True)


class ClientModel(nn.Module):
    self.S = nn.Parameter(torch.rand(x, y), requires_grad=True)
    self.U = nn.Parameter(torch.rand(x, y), requires_grad=True)


class Server:
    def __init__(self, model):
        self.model = model
        ...

    def train(clients):
        for i, c in enumerate(clients):
            sd = c.model.state_dict()
            sd['S'] = self.model.S
            c.model.load_state_dict(sd)
        self.c_list = random.sample(clients, 200)
        pool = mp.Pool(mp.cpu_count()-1)
        results = pool.map(obj_train, self.c_list)
        pool.close()
        pool.join()
        print("Training complete")


class Client:
    def __init__(self, client_id, model, train_set):
        self.id = client_id
        self.model = model
        self.train_set = train_set

    def train(self):
        self.optimizer = optim.SGD([self.model.S, self.model.U])
        for i in self.train_set:
            loss = self.model(i)
            loss.backward()
            self.optimizer.step()
        print("Trained client %d", self.id)

        return self.model.S


if __name__ == '__main__':
    ...
    server = Server(server_model)
    clients = [Client(u, ClientModel(), train_set[u]) for u in range(n_clients)]
    server.train(clients)

好的,问题出在多处理中。我尝试了很多方法,但所有方法都给了我同样的问题。服务器应该管理 200 个客户端的训练,但经过一定数量的训练(这取决于方法,但大约 50-100),脚本完全卡住,CPU 核心停止工作。

你有什么想法吗?我尝试过的其他方法例如 mp.PoolProcessPoolExecutor

感谢您的帮助。

最佳答案

您是否达到了机器能够处理的最大进程/线程数? 例如,当将网络爬虫从开发转移到生产时,机器不允许更多进程是很常见的。

我会看一下文件

/etc/sysctl.d

并以防增加机器处理的可能进程数。

另一个原因可能是您限制了 RAM 限制或类似的东西,尝试再次快速查看命令

htop

其次是

free -m 

看看他们告诉你什么。这可能是硬件问题。虽然来自软件,但可能是您正在使用的库 https://docs.python.org/2/library/multiprocessing.html有一个硬编码限制。同样在这里,您可以轻松地在库参数中将其设置得更高。

最后但同样重要的是,尝试逐步查找问题。我将使用 2 个进程对其进行测试并缓慢增加以查看应用程序何时开始出现问题。到那时可能会更清楚问题是什么。祝你好运!

关于python - 为什么 multiprocessing 在执行一定数量的任务后突然停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068181/

相关文章:

Python 管道子进程在连接后挂起

python - 在pytorch中连接数据集

python-3.x - Pytorch 中缺乏 L1 正则化的稀疏解决方案

python - pandas滚动窗口: variable length from start to x

python - 统一 python 列表中的所有对

python - 如何让多处理稍等一下?

python - 通过 python 的多处理模块 : surely I've done something wrong 进行明显的时间旅行

python - PyTorch - 运行时错误 : Assertion 'cur_target >= 0 && cur_target < n_classes' failed

python - 将我的字典变成 pandas 数据框

python - 在 Python 中打印字符串,不带句号进入下一行