| 1 | import torch |
| 2 | import math |
| 3 | |
| 4 | |
| 5 | def torchtest(): |
| 6 | dtype = torch.float |
| 7 | # device = torch.device("cpu") |
| 8 | # device = torch.device("cuda:0") # Uncomment this to run on GPU |
| 9 | # device = torch.device("cuda") # Uncomment this to run on GPU |
| 10 | device = torch.device("mps") |
| 11 | |
| 12 | # Create Tensors to hold input and outputs. |
| 13 | # By default, requires_grad=False, which indicates that we do not need to |
| 14 | # compute gradients with respect to these Tensors during the backward pass. |
| 15 | # x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype) |
| 16 | q = torch.linspace(-math.pi, math.pi, 5000000, device=device, dtype=dtype) |
| 17 | x = torch.linspace(-math.pi, math.pi, 5000000, device=device, dtype=dtype) |
| 18 | y = torch.sin(x) |
| 19 | |
| 20 | # Create random Tensors for weights. For a third order polynomial, we need |
| 21 | # 4 weights: y = a + b x + c x^2 + d x^3 |
| 22 | # Setting requires_grad=True indicates that we want to compute gradients with |
| 23 | # respect to these Tensors during the backward pass. |
| 24 | a = torch.randn((), device=device, dtype=dtype, requires_grad=True) |
| 25 | b = torch.randn((), device=device, dtype=dtype, requires_grad=True) |
| 26 | c = torch.randn((), device=device, dtype=dtype, requires_grad=True) |
| 27 | d = torch.randn((), device=device, dtype=dtype, requires_grad=True) |
| 28 | |
| 29 | learning_rate = 1e-6 |
| 30 | for t in range(2000): |
| 31 | # Forward pass: compute predicted y using operations on Tensors. |
| 32 | y_pred = a + b * x + c * x**2 + d * x**3 |
| 33 | |
| 34 | # Compute and print loss using operations on Tensors. |
| 35 | # Now loss is a Tensor of shape (1,) |
| 36 | # loss.item() gets the scalar value held in the loss. |
| 37 | # loss = (y_pred - y).pow(2).sum() |
| 38 | loss = (y_pred - y).sum() |
| 39 | if t % 100 == 99: |
| 40 | print(t, loss.item()) |
| 41 | |
| 42 | # Use autograd to compute the backward pass. This call will compute the |
| 43 | # gradient of loss with respect to all Tensors with requires_grad=True. |
| 44 | # After this call a.grad, b.grad. c.grad and d.grad will be Tensors holding |
| 45 | # the gradient of the loss with respect to a, b, c, d respectively. |
| 46 | loss.backward() |
| 47 | |
| 48 | # Manually update weights using gradient descent. Wrap in torch.no_grad() |
| 49 | # because weights have requires_grad=True, but we don't need to track this |
| 50 | # in autograd. |
| 51 | with torch.no_grad(): |
| 52 | a -= learning_rate * a.grad |
| 53 | b -= learning_rate * b.grad |
| 54 | c -= learning_rate * c.grad |
| 55 | d -= learning_rate * d.grad |
| 56 | |
| 57 | # Manually zero the gradients after updating weights |
| 58 | a.grad = None |
| 59 | b.grad = None |
| 60 | c.grad = None |
| 61 | d.grad = None |
| 62 | |
| 63 | print(f"Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3") |
| 64 | |
| 65 | |
| 66 | torchtest() |