PyTorch Tutorials: 60 minute blitz

Author: Chris Shih


In [1]:
import torch

Creating Tensors


In [6]:
x = torch.Tensor(5,3)
print(x)


-4.2051e+13  4.5600e-41 -4.2051e+13
 4.5600e-41  0.0000e+00  0.0000e+00
 0.0000e+00  0.0000e+00  0.0000e+00
 0.0000e+00  4.6243e-44  0.0000e+00
 3.4500e-37  0.0000e+00 -4.2052e+13
[torch.FloatTensor of size 5x3]


In [16]:
x = torch.rand(5,3)
print(x)


 0.3030  0.7690  0.8078
 0.0780  0.9124  0.1232
 0.6176  0.0084  0.3921
 0.8525  0.3894  0.4966
 0.9041  0.9550  0.3723
[torch.FloatTensor of size 5x3]


In [13]:
print(x.size())


torch.Size([5, 3])

Operations on Tensors


In [17]:
y = torch.rand(5,3)
result = x + y

In [18]:
print(result)


 0.4938  1.3079  1.7434
 1.0029  1.4707  0.2873
 0.7920  0.5774  1.3026
 1.1678  0.5457  0.6172
 1.0862  1.2530  0.9273
[torch.FloatTensor of size 5x3]


In [20]:
# INPLACE!
result.add_(x)
print(result)


 1.0997  2.8459  3.3589
 1.1588  3.2954  0.5337
 2.0271  0.5941  2.0867
 2.8729  1.3245  1.6104
 2.8944  3.1631  1.6719
[torch.FloatTensor of size 5x3]

Test CUDA!!


In [24]:
%%time
a = torch.randn(10).cuda()
print(a)
print(a+2)


-0.3239
 1.4139
-1.0504
 0.2035
-0.4520
 1.7124
 0.4678
-0.5901
-1.7107
 0.6969
[torch.cuda.FloatTensor of size 10 (GPU 0)]


 1.6761
 3.4139
 0.9496
 2.2035
 1.5480
 3.7124
 2.4678
 1.4099
 0.2893
 2.6969
[torch.cuda.FloatTensor of size 10 (GPU 0)]

CPU times: user 0 ns, sys: 4 ms, total: 4 ms
Wall time: 628 µs