pytorch配置双显卡方式,使用双显卡跑代码

 更新时间:2024年06月26日 09:12:53   作者:好好好好饭  
这篇文章主要介绍了pytorch配置双显卡方式,使用双显卡跑代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

项目场景

Linux系统,pytorch环境

问题描述

使用的服务器有两张显卡,感觉一张显卡跑代码比较慢,想配置两张显卡同时跑代码,只需要在你的代码中添加几行,就可以使用双显卡,亲测有效。

解决方案

提示:这里填写该问题的具体解决方案:

先看以下官方示例代码,插入添加的地方是需要我们添加在代码中的代码行

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import os 
#######添加
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' # 这里输入你的GPU_id
 
# Parameters and DataLoaders
input_size = 5
output_size = 2
 
batch_size = 30
data_size = 100
#######添加
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
# Dummy DataSet
class RandomDataset(Dataset):
 
    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)
 
    def __getitem__(self, index):
        return self.data[index]
 
    def __len__(self):
        return self.len
 
rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),
                         batch_size=batch_size, shuffle=True)
 
# Simple Model
class Model(nn.Module):
    # Our model
 
    def __init__(self, input_size, output_size):
        super(Model, self).__init__()
        self.fc = nn.Linear(input_size, output_size)
 
    def forward(self, input):
        output = self.fc(input)
        print("\tIn Model: input size", input.size(),
              "output size", output.size())
 
        return output
################添加
# Create Model and DataParallel
model = Model(input_size, output_size)
if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  model = nn.DataParallel(model)
model.to(device)
 
 
#Run the Model
for data in rand_loader:
    input = data.to(device)
    output = model(input)
    print("Outside: input size", input.size(),
          "output_size", output.size())

其中我将model = nn.DataParallel(model)修改为model = nn.DataParallel(model.cuda()),这一步直接参照网上修改的,因此这一步没有报错。

比如我自己在我代码中添加如下

from model.hash_model import DCMHT as DCMHT
import os
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import scipy.io as scio
 
 
from .base import TrainBase
from model.optimization import BertAdam
from utils import get_args, calc_neighbor, cosine_similarity, euclidean_similarity
from utils.calc_utils import calc_map_k_matrix as calc_map_k
from dataset.dataloader import dataloader
###############添加
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' # 这里输入你的GPU_id
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
class Trainer(TrainBase):
 
    def __init__(self,
                rank=0):
        args = get_args()
        super(Trainer, self).__init__(args, rank)
        self.logger.info("dataset len: {}".format(len(self.train_loader.dataset)))
        self.run()
 
    def _init_model(self):
        self.logger.info("init model.")
        linear = False
        if self.args.hash_layer == "linear":
            linear = True
 
        self.logger.info("ViT+GPT!")
        HashModel = DCMHT
        self.model = HashModel(outputDim=self.args.output_dim, clipPath=self.args.clip_path,
                            writer=self.writer, logger=self.logger, is_train=self.args.is_train, linear=linear).to(self.rank)
####################################添加
        self.model= nn.DataParallel(self.model.cuda())
        if torch.cuda.device_count() >1:
            print("Lets use",torch.cuda.device_count(),"GPUs!")
        self.model.to(device)
 
        if self.args.pretrained != "" and os.path.exists(self.args.pretrained):
            self.logger.info("load pretrained model.")
            self.model.load_state_dict(torch.load(self.args.pretrained, map_location=f"cuda:{self.rank}"))
        
        self.model.float()
        self.optimizer = BertAdam([
                    {'params': self.model.clip.parameters(), 'lr': self.args.clip_lr},
                    {'params': self.model.image_hash.parameters(), 'lr': self.args.lr},
                    {'params': self.model.text_hash.parameters(), 'lr': self.args.lr}
                    ], lr=self.args.lr, warmup=self.args.warmup_proportion, schedule='warmup_cosine', 
                    b1=0.9, b2=0.98, e=1e-6, t_total=len(self.train_loader) * self.args.epochs,
                    weight_decay=self.args.weight_decay, max_grad_norm=1.0)
                
        print(self.model)

添加以上代码后一般还会报如下错误

“AttributeError: ‘DataParallel’ object has no attribute ‘xxx’”

解决办法为先在dataparallel后的model调用module模块,然后再调用xxx

比如在上述我自己的代码中会报错

AttributeError: ‘DataParallel’ object has no attribute ‘clip’

解决办法:

是将model,修改为model.module.,后续报错大致相同,将你的代码中涉及到model.的地方修改为model.module.即可。

self.optimizer = BertAdam([
                    {'params': self.model.module.clip.parameters(), 'lr': self.args.clip_lr},
                    {'params': self.model.module.image_hash.parameters(), 'lr': self.args.lr},
                    {'params': self.model.module.text_hash.parameters(), 'lr': self.args.lr}
                    ], lr=self.args.lr, warmup=self.args.warmup_proportion, 

检查显卡使用情况

打开终端,在终端输入nvidia-smi命令可查看显卡使用情况

成功使用双显卡跑代码!

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Pytorch出现错误Attribute Error:module ‘torch‘ has no attribute '_six'解决

    Pytorch出现错误Attribute Error:module ‘torch‘ has no attrib

    这篇文章主要给大家介绍了关于Pytorch出现错误Attribute Error:module ‘torch‘ has no attribute '_six'解决的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-11-11
  • Pycharm终端显示PS而不显示虚拟环境名的解决

    Pycharm终端显示PS而不显示虚拟环境名的解决

    这篇文章主要介绍了Pycharm终端显示PS而不显示虚拟环境名的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Python闭包原理与nonlocal关键字实战指南

    Python闭包原理与nonlocal关键字实战指南

    闭包是Python中一个强大而优雅的特性,掌握它能让你写出更灵活、更模块化的代码,本文将深入解析闭包的原理,并通过实战案例带你彻底理解nonlocal关键字,感兴趣的朋友跟随小编一起看看吧
    2026-03-03
  • Python dataframe如何设置index

    Python dataframe如何设置index

    这篇文章主要介绍了Python dataframe如何设置index,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • wxPython中wx.gird.Gird添加按钮的实现

    wxPython中wx.gird.Gird添加按钮的实现

    本文主要介绍了wxPython中wx.gird.Gird添加按钮的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • Python爬虫beautifulsoup4常用的解析方法总结

    Python爬虫beautifulsoup4常用的解析方法总结

    今天小编就为大家分享一篇关于Python爬虫beautifulsoup4常用的解析方法总结,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Python如何批量获取文件夹的大小并保存

    Python如何批量获取文件夹的大小并保存

    这篇文章主要介绍了Python如何批量获取文件夹的大小并保存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • Flask框架的学习指南之制作简单blog系统

    Flask框架的学习指南之制作简单blog系统

    本文是Flask框架的学习指南系列文章的第二篇主要给大家讲述制作一个简单的小项目blog系统的过程,有需要的小伙伴可以参考下
    2016-11-11
  • Linux下使用python调用top命令获得CPU利用率

    Linux下使用python调用top命令获得CPU利用率

    这篇文章主要介绍了Linux下使用python调用top命令获得CPU利用率,本文直接给出实现代码,需要的朋友可以参考下
    2015-03-03
  • Django框架实现分页显示内容的方法详解

    Django框架实现分页显示内容的方法详解

    这篇文章主要介绍了Django框架实现分页显示内容的方法,结合实例形式详细分析了Django框架引入bootstrap样式进行分页显示相关步骤、实现方法与操作注意事项,需要的朋友可以参考下
    2019-05-05

最新评论