nn.Dataparallel pytorch 平行計算的兩種方法

1. nn.Dataparallel

多GPU加速訓練

原理:
模型分別復制到每個卡中,然后把輸入切片,分別放入每個卡中計算,然后再用第一塊卡進行匯總求loss,反向傳播更新參數。

第一塊卡占用的內存多一點,因為output loss每次都會在第一塊GPU相加計算,這就造成了第一塊GPU的負載遠遠大于剩余其他的顯卡。

要求:
batch_size > GPU 數量

第一種方法:

os.environment['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'
device_ids = [0,1,2,3]
net  = torch.nn. Dataparallel(net, device_ids =device_ids)
net = net.cuda()

第二種方法

os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2"
if torch.cuda.is_available():self.device = "cuda"if torch.cuda.device_count() > 1:self.G = nn.DataParallel(self.G)self.D_A = nn.DataParallel(self.D_A)self.D_B = nn.DataParallel(self.D_B)self.vgg = nn.DataParallel(self.vgg)self.criterionHis = nn.DataParallel(self.criterionHis)self.criterionGAN = nn.DataParallel(self.criterionGAN)self.criterionL1 = nn.DataParallel(self.criterionL1)self.criterionL2 = nn.DataParallel(self.criterionL2)self.criterionGAN = nn.DataParallel(self.criterionGAN)self.G.cuda()self.vgg.cuda()self.criterionHis.cuda()self.criterionGAN.cuda()self.criterionL1.cuda()self.criterionL2.cuda()self.D_A.cuda()self.D_B.cuda()

2.模型分別單獨放入每個指定的GPU中

把模型分別放到指定的GPU中,然后在運算的過程中,需要把利用**.to(cuda:x)** 去轉移數據。這樣暫用的內存比平行計算小。但是配置復雜一點。

	vgg_encoder = VGGEncoder().to('cuda:0')attn=CoAttention(channel=512).to('cuda:1')decoder = Decoder().to('cuda:2')optimizer_decoder = Adam(decoder.parameters(), lr=args.learning_rate)optimizer_attn = Adam(attn.parameters(), lr=args.learning_rate)content = content.cuda()  # 默認的是cuda:0style = style.cuda()content_features = vgg_encoder(content, output_last_feature=True)style_features = vgg_encoder(style, output_last_feature=True)content_features, style_features=attn(content_features.to('cuda:1'),style_features.to('cuda:1')) # 因為attn在cuda:1中

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/535233.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/535233.shtml
英文地址,請注明出處:http://en.pswp.cn/news/535233.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ERROR: Cannot uninstall ‘PyYAML‘. 安裝 fvcore

直接安裝 pip install fvcore 會出現錯誤 解決辦法 先這樣安裝 pip install --ignore-installed PyYAML然后安裝 pip install fvcore

Ubunt 配置網絡服務

ifconfig 不顯示 處理方法:聯網安裝 sudo apt-get install openssh-server ps -e|grep ssh 服務器不能聯網 可以用手機連著數據線插到電腦上面 服務器

torch.view(), squeeze, unsqueeze

1. torch.view() data.view(a,b) # 把data 轉換成 a*b 維的矩陣 data.view(k,-1)2. torch.squeeze() data.squeeze(0) # 表示在第一維度壓縮,如果第一維度是1,則直接去掉imgcontent img.shape torch.Size([1,3, 800, 600])imgcontent.squee…

如何寫會議 Rebuttal

reviewer 類型 Rebuttal時,不同review類型: (1)噴「novelty」:這類最為麻煩但也是作者們遇到可能最多的意見,作此類rebuttal時不妨重新梳理和強調文章的重要貢獻,然后澄清并不是trivial的簡單…

Pycharm遠程連接服務器,操作代碼

1. Pycharm連接遠程服務器 1.1 進入配置頁面 Pycharm菜單欄,如下圖所示,依次點擊 Tools -> Deployment -> Configration… 1.2 配置連接服務器 如下圖。name隨便寫個就行。 Connection下,協議最好選擇sftp,接下來填寫服務器…

關于“xxx”object is not callable的異常

所謂callable對象是指一個后邊可以加()的對象,比如函數, 所以這種異常肯定是某對象多加了(), 比如:把一個變量用了函數名來命名,結果再調這個函數的時候就會報這個異常 image.size()就會出現這樣的錯誤 這個時候把括…

Latex調整表格與標題表名之間的間距

調整前 調整后 方法 \begin{table}[t]\setlength{\abovecaptionskip}{0cm} # 調整間距\setlength{\belowcaptionskip}{-0.2cm}\small\caption{Mean computation time on different style transfer methods for 256 $\times$ 256 and 512 $\times$ 512 images. }\centering\beg…

Pytorch 報錯: The size of tensor a (4) must match the size of tensor b (3) at non-singleton

原因分析 1.讀取的是.png 圖片 是32位深度的,一般我們讀取的是.jpg 24位深度的 2.轉換為RGB就行了 test_image Image.open(test_image_name).convert(RGB)

python 遍歷文件中的文件,文件名

1.利用pathlib 中的Path import os from pathlib impot Path path ./image paths list(Path(path).glob(*))for in in paths:print(i.name) # 打印文件名

Python hasattr() getattr() setattr() 函數使用

1.setattr(object, name, values) 給對象設置屬性,如果對象不存在,則創建對象 layers nn.Sequential(nn.Conv2d(curr_dim, curr_dim * 2, kernel_size4, stride2, padding1, biasFalse),nn.InstanceNorm2d(curr_dim * 2, affineTrue),nn.ReLU(inplace…

Python-import導入上級 本級 目錄文件

假設有如下目錄結構: -- dir0| file1.py| file2.py| dir3| file3.py| dir4| file4.pydir0文件夾下有file1.py、file2.py兩個文件和dir3、dir4兩個子文件夾,dir3中有file3.py文件,dir4中有file4.py文件。 1.導入同級模塊 python導入同級模塊…

python 判斷數據類型,是否與已知相同

1. 判斷數據類型type(x) x torch.randint(1,2,[2,2]) print(type(x))<class torch.Tensor>2.判斷是否與已知一樣 isinstance(x,type) 函數isinstance 作用是判斷類型是否與已知一樣 print(isinstance(x,torch.Tensor))Truex[] print(isinstance(x,lsit)True

Pytorch RuntimeERROR: Given groups=1 weights of size [256,64,1,1] expected input[1,16,256,256] to

錯誤 Pytorch RuntimeERROR: Given groups1 weights of size [256,64,1,1] expected input[1,16,256,256] to have 64 channels, but got 16 channels instead.錯誤分析 Given groups1 weights of size [256,64,1,1] 代表卷積核的channel 大小為 64->256 &#xff0c;大…

pytorch 訓練過程學習率設置衰減

設置學習率衰減 if (self.e1) > (self.num_epochs - self.num_epochs_decay):g_lr - (self.g_lr / float(self.num_epochs_decay))d_lr - (self.d_lr / float(self.num_epochs_decay))self.update_lr(g_lr, d_lr)print(Decay learning rate to g_lr: {}, d_lr:{}..format(g_…

ModuleNotFoundError: No module named ‘torch.utils.serialization‘

這是因為在torch新版本中刪除了load_lua 解決辦法:首先命令行運行pip install torchfile安裝torchfile,然后將utils.py第7行中的from torch.utils.serialization import load_lua改為import torchfile,最后將utils.py第90行中的load_lua改為torchfile.load

使用conda/pip安裝pytorch 0.3.1教程(mac/windos/linux) pytorch 0.2.1

#寫的很好 https://ptorch.com/news/145.html conda create -n torch_0.3.1 # 創建一個新的環境 pip3 install http://download.pytorch.org/whl/cpu/torch-0.3.1-cp36-cp36m-linux_x86_64.whl pip install torchvision0.2.1安裝torch0.2.1 conda create -n torch_0.2.1 # …

Latex的表格注釋

調用threeparttable包 在文檔的最前面加入以下命令&#xff1a; \usepackage{threeparttable}在表格處插入命令 \begin{table*} \label{table:number} \centering \caption{....} \begin{threeparttable} \begin{tabular}{lc}\hlineA & B \\\hline A & B\tnote{*} \…

Latex 插入目錄 設置首頁頁碼為空

插入目錄 \begin{document} \maketitle\tableofcontents \newpage # 從下一頁開始\end{document}\maketitle \tableofcontents \textbf{\ \\\\\\\\\\$*$ means that it is a supplementary experimental results for the manuscript.\\ $**$ means that it is a newly added …

Pytorch GPU內存占用很高,但是利用率很低

1.GPU 占用率&#xff0c;利用率 輸入nvidia-smi來觀察顯卡的GPU內存占用率&#xff08;Memory-Usage&#xff09;&#xff0c;顯卡的GPU利用率&#xff08;GPU-util&#xff09; GPU內存占用率&#xff08;Memory-Usage&#xff09; 往往是由于模型的大小以及batch size的大…