初见PyTorch.pdf

    1. import torch
    2. from torch import autograd
    3. x = torch.tensor(1.)
    4. a = torch.tensor(1., requires_grad=True)
    5. b = torch.tensor(2., requires_grad=True)
    6. c = torch.tensor(3., requires_grad=True)
    7. y = a**2 * x + b * x + c
    8. print('before:', a.grad, b.grad, c.grad)
    9. grads = autograd.grad(y, [a, b, c])
    10. print('after :', grads[0], grads[1], grads[2])
    1. import torch
    2. import time
    3. print(torch.__version__)
    4. print(torch.cuda.is_available())
    5. # print('hello, world.')
    6. a = torch.randn(10000, 1000)
    7. b = torch.randn(1000, 2000)
    8. t0 = time.time()
    9. c = torch.matmul(a, b)
    10. t1 = time.time()
    11. print(a.device, t1 - t0, c.norm(2))
    12. device = torch.device('cuda')
    13. a = a.to(device)
    14. b = b.to(device)
    15. t0 = time.time()
    16. c = torch.matmul(a, b)
    17. t2 = time.time()
    18. print(a.device, t2 - t0, c.norm(2))
    19. t0 = time.time()
    20. c = torch.matmul(a, b)
    21. t2 = time.time()
    22. print(a.device, t2 - t0, c.norm(2))