在两个不同的gpu上并行运行一部分Python代码

2024-04-27 12:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于以下内容的PyTorch脚本:

# Loading data
train_loader, test_loader = someDataLoaderFunction()

# Define the architecture
model = ResNet18()
model = model.cuda()  

# Get method from program argument
method = args.method

# Training
train(method, model, train_loader, test_loader)

为了使用两种不同的方法(method1method2)运行脚本,只需在两个不同的终端中运行以下命令即可:

^{pr2}$

问题是,上面的数据加载函数包含了一些随机性,这意味着这两种方法分别应用于两组不同的训练数据。我希望他们训练完全相同的数据集,所以我修改了脚本如下:

# Loading data
train_loader, test_loader = someDataLoaderFunction()

# Define the architecture
model = ResNet18()
model = model.cuda()  

## Run for the first method
method = 'method1'

 # Training
train(method, model, train_loader, test_loader)

## Run for the second method
method = 'method2'

# Must re-initialize the network first
model = ResNet18()
model = model.cuda()

 # Training
train(method, model, train_loader, test_loader)

有没有可能让它为每个方法并行运行? 非常感谢您的帮助!在


Tags: the数据方法test脚本datamodeltraining
1条回答
网友
1楼 · 发布于 2024-04-27 12:16:12

我想最简单的方法是把种子固定在下面。在

myseed=args.seed
np.random.seed(myseed)
torch.manual_seed(myseed)
torch.cuda.manual_seed(myseed)

这将迫使数据加载器每次都获取相同的样本。并行的方法是使用多线程,但我认为您发布的问题不值得为此而费心。在

相关问题 更多 >