如何在非并行方式下运行Pytorch模型?

我正在研究这个脚本,其中有一个代码块考虑了两种选项,即DataParallelDistributedDataParallel,如下所示:

if not args.distributed:    if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):        model.features = torch.nn.DataParallel(model.features)        model.cuda()    else:        model = torch.nn.DataParallel(model).cuda()else:    model.cuda()    model = torch.nn.parallel.DistributedDataParallel(model)

如果我不想使用这两种选项,并且我想在没有DataParallel的情况下运行它,我该怎么做呢?

我该如何定义我的模型,使其作为普通的nn运行,而不进行任何并行化处理呢?


回答:

  • DataParallel是一个包装对象,用于在同一台机器的多个GPU上并行计算,详见这里
  • DistributedDataParallel也是一个包装对象,允许你在多个设备上分配数据,详见这里

如果你不想使用这些功能,你可以简单地移除包装器,直接使用模型本身:

if not args.distributed:    if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):        model.features = model.features        model.cuda()    else:        model = model.cuda()else:    model.cuda()    model = model

这样做可以将代码修改降到最低。当然,由于你对并行化不感兴趣,你可以将整个if语句简化为类似于下面的形式:

if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):    model.features = model.featuresmodel = model.cuda()

请注意,这段代码假设你在GPU上运行。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注