pytorch配置雙顯卡方式,使用雙顯卡跑代碼
項(xiàng)目場(chǎng)景
Linux系統(tǒng),pytorch環(huán)境
問(wèn)題描述
使用的服務(wù)器有兩張顯卡,感覺(jué)一張顯卡跑代碼比較慢,想配置兩張顯卡同時(shí)跑代碼,只需要在你的代碼中添加幾行,就可以使用雙顯卡,親測(cè)有效。
解決方案
提示:這里填寫(xiě)該問(wèn)題的具體解決方案:
先看以下官方示例代碼,插入添加的地方是需要我們添加在代碼中的代碼行
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()),這一步直接參照網(wǎng)上修改的,因此這一步?jīng)]有報(bào)錯(cuò)。
比如我自己在我代碼中添加如下
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)
添加以上代碼后一般還會(huì)報(bào)如下錯(cuò)誤
“AttributeError: ‘DataParallel’ object has no attribute ‘xxx’”
解決辦法為先在dataparallel后的model調(diào)用module模塊,然后再調(diào)用xxx
比如在上述我自己的代碼中會(huì)報(bào)錯(cuò)
AttributeError: ‘DataParallel’ object has no attribute ‘clip’
解決辦法:
是將model,修改為model.module.,后續(xù)報(bào)錯(cuò)大致相同,將你的代碼中涉及到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,
檢查顯卡使用情況
打開(kāi)終端,在終端輸入nvidia-smi命令可查看顯卡使用情況
成功使用雙顯卡跑代碼!
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Python參數(shù)解析器argparse的應(yīng)用場(chǎng)景
這篇文章主要介紹了關(guān)于Python參數(shù)解析器argparse的應(yīng)用場(chǎng)景,argparse 模塊使編寫(xiě)用戶友好的命令行界面變得容易,程序定義了所需的參數(shù),而 argparse 將找出如何從 sys.argv 中解析這些參數(shù),需要的朋友可以參考下2023-08-08linux環(huán)境下安裝python虛擬環(huán)境及注意事項(xiàng)
這篇文章主要介紹了linux環(huán)境下安裝python虛擬環(huán)境,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01Python實(shí)現(xiàn)圖片格式轉(zhuǎn)換
經(jīng)常會(huì)遇到圖片格式需要轉(zhuǎn)換的情況,這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)圖片格式轉(zhuǎn)換,文中示例代碼介紹的非常詳細(xì)、實(shí)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08tensorflow 1.X遷移至tensorflow2 的代碼寫(xiě)法
本文主要介紹了tensorflow 1.X遷移至tensorflow2 的代碼寫(xiě)法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12python尋找list中最大值、最小值并返回其所在位置的方法
今天小編就為大家分享一篇python尋找list中最大值、最小值并返回其所在位置的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06在pandas中一次性刪除dataframe的多個(gè)列方法
下面小編就為大家分享一篇在pandas中一次性刪除dataframe的多個(gè)列方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04關(guān)于pycharm找不到MySQLdb模塊的解決方法
MySQLdb是用于Python鏈接Mysql數(shù)據(jù)庫(kù)的接口,它實(shí)現(xiàn)了Python數(shù)據(jù)庫(kù)API規(guī)范V2.0,基于MySql C API上建立的,本文給大家介紹pycharm找不到MySQLdb模塊解決方法,需要的朋友參考下吧2021-06-06