在两个不同的GPU上并行运行一部分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)运行脚本,足以在两个不同的终端中运行以下命令:

CUDA_VISIBLE_DEVICES=0 python program.py --method method1
CUDA_VISIBLE_DEVICES=1 python program.py --method method2

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

# 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)

是否可以为每种方法并行运行它吗?非常感谢您的帮助!

我想最简单的方法是在下面修复种子。

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

这应该迫使数据加载程序每次获取相同的样本。并行的方法是使用多线程,但我几乎看不到您发布的问题值得麻烦。

最新更新