Ex_treme's blog.

pytorch环境配置

2018/06/02 Share

pytorch环境配置

显卡驱动

更新显卡驱动

1
系统设置->软件更新->附加驱动->选择nvidia最新驱动(361)->应用更改

显卡驱动测试

1
2
3
4
5
6
7
重启
nvidia-settings
Operating System:Linux-x86_64
NVIDIA Driver Version:384.130
Graphics Processor:GeForce GTX 1060
CUDA Cores:1280
Total Memory:6144 MB

版本号查看

1
2
3
$ cat /proc/driver/nvidia/version
NVRM version: NVIDIA UNIX x86_64 Kernel Module 384.130 Wed Mar 21 03:37:26 PDT 2018
GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)

安装cuda(直接用pytorch一键安装,此一步可省去)

1
2
3
4
5
6
7
8
9
10
sudo apt install nvidia-cuda-toolkit
nvcc -V
版本是7.5的,已经和新版本的pytorch不兼容了...
所以只能去[NVIDA的官方网站](https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1604&target_type=deblocal)下载了,希望不会掉线把......唉
下载之后的软件包名字‘cuda-repo-ubuntu1604-9-2-local_9.2.88-1_amd64.deb’
安装流程:
+ sudo dpkg -i cuda-repo-ubuntu1604-9-2-local_9.2.88-1_amd64.deb
+ sudo apt-key add /var/cuda-repo-<version>/7fa2af80.pub
+ sudo apt-get update
+ sudo apt-get install cuda

Pytorch

conda一键安装pytorch

1
2
conda install pytorch=0.4.0 torchvision -c soumith
pytorch是框架,torchvision是包和库,pytorch=0.4.0对应CUDA版本的9.0,conda会自动帮你安装或者更新。

包测试

1
2
3
import torch
import torchvision
print(torch.cuda.is_available())

pytorch入门准备

1
2
3
$ git clone https://github.com/yunjey/pytorch-tutorial.git
$ cd pytorch-tutorial/tutorials/02-intermediate/language_model/main.py
$ python main.py

RNN-language model源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Some part of the code was referenced from below.
# https://github.com/pytorch/examples/tree/master/word_language_model
import torch
import torch.nn as nn
import numpy as np
from torch.nn.utils import clip_grad_norm
from data_utils import Dictionary, Corpus


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters
embed_size = 128
hidden_size = 1024
num_layers = 1
num_epochs = 5
num_samples = 1000 # number of words to be sampled
batch_size = 20
seq_length = 30
learning_rate = 0.002

# Load "Penn Treebank" dataset
corpus = Corpus()
ids = corpus.get_data('data/train.txt', batch_size)
vocab_size = len(corpus.dictionary)
num_batches = ids.size(1) // seq_length


# RNN based language model
class RNNLM(nn.Module):
def __init__(self, vocab_size, embed_size, hidden_size, num_layers):
super(RNNLM, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)

def forward(self, x, h):
# Embed word ids to vectors
x = self.embed(x)

# Forward propagate LSTM
out, (h, c) = self.lstm(x, h)

# Reshape output to (batch_size*sequence_length, hidden_size)
out = out.reshape(out.size(0)*out.size(1), out.size(2))

# Decode hidden states of all time steps
out = self.linear(out)
return out, (h, c)

model = RNNLM(vocab_size, embed_size, hidden_size, num_layers).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Truncated backpropagation
def detach(states):
return [state.detach() for state in states]

# Train the model
for epoch in range(num_epochs):
# Set initial hidden and cell states
states = (torch.zeros(num_layers, batch_size, hidden_size).to(device),
torch.zeros(num_layers, batch_size, hidden_size).to(device))

for i in range(0, ids.size(1) - seq_length, seq_length):
# Get mini-batch inputs and targets
inputs = ids[:, i:i+seq_length].to(device)
targets = ids[:, (i+1):(i+1)+seq_length].to(device)

# Forward pass
states = detach(states)
outputs, states = model(inputs, states)
loss = criterion(outputs, targets.reshape(-1))

# Backward and optimize
model.zero_grad()
loss.backward()
clip_grad_norm(model.parameters(), 0.5)
optimizer.step()

step = (i+1) // seq_length
if step % 100 == 0:
print ('Epoch [{}/{}], Step[{}/{}], Loss: {:.4f}, Perplexity: {:5.2f}'
.format(epoch+1, num_epochs, step, num_batches, loss.item(), np.exp(loss.item())))

# Test the model
with torch.no_grad():
with open('sample.txt', 'w') as f:
# Set intial hidden ane cell states
state = (torch.zeros(num_layers, 1, hidden_size).to(device),
torch.zeros(num_layers, 1, hidden_size).to(device))

# Select one word id randomly
prob = torch.ones(vocab_size)
input = torch.multinomial(prob, num_samples=1).unsqueeze(1).to(device)

for i in range(num_samples):
# Forward propagate RNN
output, state = model(input, state)

# Sample a word id
prob = output.exp()
word_id = torch.multinomial(prob, num_samples=1).item()

# Fill input with sampled word id for the next time step
input.fill_(word_id)

# File write
word = corpus.dictionary.idx2word[word_id]
word = '\n' if word == '<eos>' else word + ' '
f.write(word)

if (i+1) % 100 == 0:
print('Sampled [{}/{}] words and save to {}'.format(i+1, num_samples, 'sample.txt'))

# Save the model checkpoints
torch.save(model.state_dict(), 'model.ckpt')

QRNN深度学习框架测试

1
pip install cupy pynvrtc git+https://github.com/salesforce/pytorch-qrnn

实例测试

1
2
3
4
5
6
7
8
9
10
11
12
import torch
from torchqrnn import QRNN

seq_len, batch_size, hidden_size = 7, 20, 256
size = (seq_len, batch_size, hidden_size)
X = torch.autograd.Variable(torch.rand(size), requires_grad=True).cuda()

qrnn = QRNN(hidden_size, hidden_size, num_layers=2, dropout=0.4)
qrnn.cuda()
output, hidden = qrnn(X)

print(output.size(), hidden.size())
CATALOG
  1. 1. pytorch环境配置
    1. 1.1. 显卡驱动
    2. 1.2. Pytorch