In [ ]:
import torch
In [ ]:
torch.cuda.is_available()
Out[ ]:
True
In [ ]:
import torch.nn.functional as F
from torch.autograd import grad

y = torch.tensor([1.0])
x1 = torch.tensor([1.1])
w1 = torch.tensor([2.2], requires_grad=True)
b = torch.tensor([0.0], requires_grad=True)

z = x1*w1 + b
a = torch.sigmoid(z)

loss = F.binary_cross_entropy(a, y)

grad_L_w1 = grad(loss, w1, retain_graph=True)
grad_L_b = grad(loss, b, retain_graph=True)

print(grad_L_w1)
print(grad_L_b)
(tensor([-0.0898]),)
(tensor([-0.0817]),)
In [ ]:
loss.backward() # The easy way
print(w1.grad)
print(b.grad)
tensor([-0.0898])
tensor([-0.0817])
In [ ]:
import torch.nn.functional as F
from torch.autograd import grad

y = torch.tensor([1.0, 1.0])
x1 = torch.tensor([1.1])
w1 = torch.tensor([2.2, 3.3], requires_grad=True)
b = torch.tensor([0.0, 0.0], requires_grad=True)

z = w1*x1 + b
a = torch.sigmoid(z)
print(a.grad_fn)

loss = F.binary_cross_entropy(a, y)
print(loss.grad_fn)

grad_L_w1 = grad(loss, w1, retain_graph=True)
grad_L_b = grad(loss, b, retain_graph=True)

print(grad_L_w1)
print(grad_L_b)
<SigmoidBackward0 object at 0x7c9e071f1a80>
<BinaryCrossEntropyBackward0 object at 0x7c9e07323640>
(tensor([-0.0449, -0.0142]),)
(tensor([-0.0408, -0.0129]),)
In [ ]:
class NeuralNetwork(torch.nn.Module):
  def __init__(self, num_inputs, num_outputs):
    super().__init__()

    self.layers = torch.nn.Sequential(
        # first hidden layer
        torch.nn.Linear(num_inputs, 30),
        torch.nn.ReLU(),

        # second hidden layer
        torch.nn.Linear(30, 20),
        torch.nn.ReLU(),

        # output layer
        torch.nn.Linear(20, num_outputs)
    )

  def forward(self, x):
    logits = self.layers(x)
    return logits
In [ ]:
model = NeuralNetwork(50, 3)
print(model)
NeuralNetwork(
  (layers): Sequential(
    (0): Linear(in_features=50, out_features=30, bias=True)
    (1): ReLU()
    (2): Linear(in_features=30, out_features=20, bias=True)
    (3): ReLU()
    (4): Linear(in_features=20, out_features=3, bias=True)
  )
)
In [ ]:
p = model.parameters()
q = next(p)
q.numel()
Out[ ]:
1500
In [ ]:
num_params = sum([p.numel() for p in model.parameters() if p.requires_grad])
print(num_params)
2213
In [ ]:
print(model.layers[0].weight)
Parameter containing:
tensor([[-0.0082, -0.0547,  0.1369,  ...,  0.0176,  0.0738,  0.1222],
        [-0.0353, -0.0381,  0.0007,  ..., -0.0873, -0.0254,  0.1021],
        [-0.0712,  0.0232, -0.1079,  ...,  0.0369,  0.0421,  0.0522],
        ...,
        [ 0.1249,  0.1045, -0.0093,  ...,  0.0402,  0.0079, -0.0752],
        [-0.0492, -0.0949,  0.0095,  ..., -0.0049,  0.1040,  0.0515],
        [ 0.1242,  0.0859,  0.1203,  ..., -0.0817, -0.0041, -0.0403]],
       requires_grad=True)
In [ ]:
print(model.layers[0])
Linear(in_features=50, out_features=30, bias=True)
In [ ]:
print(model.layers[0].weight.shape)
torch.Size([30, 50])
In [ ]:
print(model.layers[0].bias)
Parameter containing:
tensor([ 0.0214,  0.0271,  0.0977, -0.1119,  0.0430,  0.0557, -0.0228,  0.0450,
         0.1171, -0.0895,  0.0828,  0.0666, -0.0439, -0.0972, -0.0658,  0.0010,
         0.0505, -0.0840, -0.1035, -0.0178, -0.0104, -0.0219,  0.0562, -0.0741,
         0.0420,  0.0271, -0.0961, -0.1094, -0.0678,  0.1323],
       requires_grad=True)
In [ ]:
print(model.layers[0].bias.shape)
torch.Size([30])
In [ ]:
torch.manual_seed(123)
model = NeuralNetwork(50, 3)
print(model.layers[0].weight)
Parameter containing:
tensor([[-0.0577,  0.0047, -0.0702,  ...,  0.0222,  0.1260,  0.0865],
        [ 0.0502,  0.0307,  0.0333,  ...,  0.0951,  0.1134, -0.0297],
        [ 0.1077, -0.1108,  0.0122,  ...,  0.0108, -0.1049, -0.1063],
        ...,
        [-0.0787,  0.1259,  0.0803,  ...,  0.1218,  0.1303, -0.1351],
        [ 0.1359,  0.0175, -0.0673,  ...,  0.0674,  0.0676,  0.1058],
        [ 0.0790,  0.1343, -0.0293,  ...,  0.0344, -0.0971, -0.0509]],
       requires_grad=True)
In [ ]:
# put it to use
torch.manual_seed(123)
X = torch.rand([1, 50])
out = model(X)
print(out)
print(out.grad_fn)
tensor([[-0.1262,  0.1080, -0.1792]], grad_fn=<AddmmBackward0>)
<AddmmBackward0 object at 0x7c9e06aef970>
In [ ]:
# forward pass only, drop the backward-pass overhead (note the dropped gradient function)
with torch.no_grad():
  out = model(X)
out
Out[ ]:
tensor([[-0.1262,  0.1080, -0.1792]])
In [ ]:
# PyTorch networks conventionally outputs pre-activated logits for recisions of
# numerical efficiency and stability. So if we want the softmax we have to take
# it ourselves.
with torch.no_grad():
  out = torch.softmax(model(X), 1)
print(out)
print(torch.sum(out))
tensor([[0.3113, 0.3934, 0.2952]])
tensor(1.)
In [ ]:
# Some sample train/test data to illustrate data loading.
X_train = torch.tensor([
    [-1.2, 3.1],
    [-0.9, 2.9],
    [-0.5, 2.6],
    [2.3, -1.1],
    [2.7, -1.5]
])

X_test = torch.tensor([
    [-0.8, 2.8],
    [2.6, -1.6]
])

y_train = torch.tensor([0, 0, 0, 1, 1])

y_test = torch.tensor([0, 1])
In [ ]:
# Create a toy dataset for use with a dataloader.

from torch.utils.data import Dataset

class ToyDataset(Dataset):
  def __init__(self, X, y):
    self.features = X
    self.labels = y
    return

  def __len__(self):
    return self.labels.shape[0]

  def __getitem__(self, index):
    x = self.features[index]
    y = self.labels[index]
    return x, y

train_ds = ToyDataset(X_train, y_train)
test_ds = ToyDataset(X_test, y_test)
In [ ]:
print(len(train_ds))
5
In [ ]:
# Now create a DataLoader to sample from our DataSet.
# Note that we don't use any worker threads because
# that won't improve performance meaningfully for such
# tiny amounts of data, and in fact within a notebook
# it can cause performance and stability issues.

from torch.utils.data import DataLoader

torch.manual_seed(123)

train_loader = DataLoader(
    dataset=train_ds,
    batch_size=2,
    shuffle=True,
    num_workers=0
)

test_loader = DataLoader(
    dataset=test_ds,
    batch_size=2,
    shuffle=False,
    num_workers=0
)
In [ ]:
# Explorer the DataLoaders.

print(f"## Train")
for idx, (x, y) in enumerate(train_loader):
  print(f"**Batch:** {idx}")
  print(f"- Features: {x}")
  print(f"- Labels: {y}\n")

print(f"## Test")
for idx, (x, y) in enumerate(train_loader):
  print(f"**Batch:** {idx}")
  print(f"- Features: {x}")
  print(f"- Labels: {y}\n")
## Train
**Batch:** 0
- Features: tensor([[ 2.3000, -1.1000],
        [-0.9000,  2.9000]])
- Labels: tensor([1, 0])

**Batch:** 1
- Features: tensor([[-1.2000,  3.1000],
        [-0.5000,  2.6000]])
- Labels: tensor([0, 0])

**Batch:** 2
- Features: tensor([[ 2.7000, -1.5000]])
- Labels: tensor([1])

## Test
**Batch:** 0
- Features: tensor([[-1.2000,  3.1000],
        [-0.5000,  2.6000]])
- Labels: tensor([0, 0])

**Batch:** 1
- Features: tensor([[ 2.3000, -1.1000],
        [-0.9000,  2.9000]])
- Labels: tensor([1, 0])

**Batch:** 2
- Features: tensor([[ 2.7000, -1.5000]])
- Labels: tensor([1])

In [ ]:
# Empirically, if the last batch in an epoch is substantially smaller than
# earlier batches this disturbs training convergence. Create another
# training dataloader that drops the last batch to prevent this.

train_loader = DataLoader(
    dataset=train_ds,
    batch_size=2,
    shuffle=True,
    num_workers=0,
    drop_last=True
)
In [ ]:
print(f"## Train")
for idx, (x, y) in enumerate(train_loader):
  print(f"**Batch:** {idx}")
  print(f"- Features: {x}")
  print(f"- Labels: {y}\n")
## Train
**Batch:** 0
- Features: tensor([[-0.9000,  2.9000],
        [ 2.3000, -1.1000]])
- Labels: tensor([0, 1])

**Batch:** 1
- Features: tensor([[ 2.7000, -1.5000],
        [-0.5000,  2.6000]])
- Labels: tensor([1, 0])

In [ ]:
# Train a neural network on our training data set with stochastic gradient descent.

torch.manual_seed(123)
model = NeuralNetwork(num_inputs=2, num_outputs=2)
optimizer = torch.optim.SGD(
    model.parameters(), lr=0.5
)

num_epochs = 3
for epoch in range(num_epochs):

  print(f"## Epoch {epoch}")
  model.train()
  for batch, (features, labels) in enumerate(train_loader):

    # The following will call model.forward() along with pre/post hooks and take
    # care of some additional state management housekeeping.
    # Calling model.forward() directly is usually a no-no.
    logits = model(features)

    loss = F.cross_entropy(logits, labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    print(f"- Batch: {batch}, Loss: {loss:.2f}")

  print()
## Epoch 0
- Batch: 0, Loss: 0.75
- Batch: 1, Loss: 0.65

## Epoch 1
- Batch: 0, Loss: 0.44
- Batch: 1, Loss: 0.13

## Epoch 2
- Batch: 0, Loss: 0.03
- Batch: 1, Loss: 0.00

In [ ]:
# How many parameters does this neural network have?
n = sum([p.numel() for p in model.parameters() if p.requires_grad==True])
print(n)
752
In [ ]:
# Now make predictions, first putting the model into eval mode.
model.eval()
with torch.no_grad():
  outputs = model(X_train)
print(outputs)
tensor([[ 2.8569, -4.1618],
        [ 2.5382, -3.7548],
        [ 2.0944, -3.1820],
        [-1.4814,  1.4816],
        [-1.7176,  1.7342]])
In [ ]:
# Use softmax to get class membership probabilities.
torch.set_printoptions(sci_mode=False) # Don't print in scientific notation
probas = torch.softmax(outputs, dim=1) # Rows sum to 1
print(probas)
tensor([[0.9991, 0.0009],
        [0.9982, 0.0018],
        [0.9949, 0.0051],
        [0.0491, 0.9509],
        [0.0307, 0.9693]])
In [ ]:
# Convert to class labels by using argmax.
predictions = torch.argmax(probas, dim=1) # Row-wise argmax
print(predictions)
tensor([0, 0, 0, 1, 1])
In [ ]:
# Check for correctness
predictions == y_train
Out[ ]:
tensor([True, True, True, True, True])
In [ ]:
# Count correct predictions
torch.sum(predictions == y_train)
Out[ ]:
tensor(5)
In [ ]:
# Create a general function for computing model accuracy.

def compute_accuracy(model, dataloader):
  total_samples = 0
  total_correct = 0

  for idx, (features, labels) in enumerate(dataloader):
    with torch.no_grad():
      logits = model(features)
    probas = torch.softmax(logits, dim=1)
    predictions = torch.argmax(probas, dim=1)
    total_correct += torch.sum(predictions == labels).item()
    total_samples += len(predictions)

  result = total_correct / total_samples
  return result

acc = compute_accuracy(model, train_loader)
print(f"Accuracy on training data: {acc}")
Accuracy on training data: 1.0
In [ ]:
# Now evaluate our model against the test dataset.
acc = compute_accuracy(model, test_loader)
print(f"Accuracy on test data: {acc}")
Accuracy on test data: 1.0
In [ ]:
# Save our model to disk.
torch.save(model.state_dict(), "model.pth") # Extension is conventional.
In [ ]:
# To load a model we first create a model in code then load the state dict file.
new_model = NeuralNetwork(num_inputs=2, num_outputs=2)
state_dict = torch.load("model.pth")
new_model.load_state_dict(state_dict)
Out[ ]:
<All keys matched successfully>
In [ ]:
# Verify we have a GPU to work with.
print(torch.cuda.is_available())
True
In [ ]:
# Compare adding tensors on CPU vs GPU.
tensor1 = torch.tensor([1., 2., 3.])
tensor2 = torch.tensor([4., 5., 6.])
print("CPU:", tensor1 + tensor2)

# Now on GPU.
tensor1 = tensor1.to("cuda")
tensor2 = tensor1.to("cuda")
print("GPU:", tensor1 + tensor2)

# Can't mix CPU and GPU.
tensor1 = tensor1.to("cpu")
try:
  print("Mixed:", tensor1 + tensor2)
except Exception as e:
  print("Exception:", e)
CPU: tensor([5., 7., 9.])
GPU: tensor([2., 4., 6.], device='cuda:0')
Exception: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
In [ ]:
# Modify our training loop to use the CPU. Only three changes!

torch.manual_seed(123)
model = NeuralNetwork(num_inputs=2, num_outputs=2)
optimizer = torch.optim.SGD(
    model.parameters(), lr=0.5
)

# CHANGE 1: create a CUDA device if available, else fallback on the CPU.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# CHANGE 2: move the model to the device.
model.to(device)

num_epochs = 3
for epoch in range(num_epochs):

  print(f"## Epoch {epoch}")
  model.train()
  for batch, (features, labels) in enumerate(train_loader):

    # CHANGE 3: move data to the device.
    features, labels = features.to(device), labels.to(device)

    # The following will call model.forward() along with pre/post hooks and take
    # care of some additional state management housekeeping.
    # Calling model.forward() directly is usually a no-no.
    logits = model(features)

    loss = F.cross_entropy(logits, labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    print(f"- Batch: {batch}, Loss: {loss:.2f}")

  print()
## Epoch 0
- Batch: 0, Loss: 0.75
- Batch: 1, Loss: 0.65

## Epoch 1
- Batch: 0, Loss: 0.44
- Batch: 1, Loss: 0.13

## Epoch 2
- Batch: 0, Loss: 0.03
- Batch: 1, Loss: 0.00

Exercise A.4

Compare the run time of matrix multiplication on a CPU to a GPU. At what matrix size do you begin to see the matrix multiplication on the GPU being faster than on the CPU? Hint: use the %timeit command in Jupyter to compare the run time. For example, given matrices a and b, run the command %timeit a @ b in a new notebook cell.

In [ ]:
import time

torch.manual_seed(123)

print(f"{'Dim':<10} | {'CPU (s)':<10} | {'GPU (s)':<10} | {'Delta (s)':<10}")
print("-" * 50)

for i in range(1, 21):
    dim = i ** 2

    # CPU matrix multiplication benchmarking
    t1_cpu = torch.rand(dim, dim, device="cpu")
    t2_cpu = torch.rand(dim, dim, device="cpu")

    start_cpu = time.perf_counter()
    res_cpu = torch.matmul(t1_cpu, t2_cpu)
    end_cpu = time.perf_counter()
    cpu_time = end_cpu - start_cpu

    # GPU matrix multiplication benchmarking (with CUDA sync to ensure accurate timing)
    if torch.cuda.is_available():
        t1_gpu = torch.rand(dim, dim, device="cuda")
        t2_gpu = torch.rand(dim, dim, device="cuda")

        # Warmup
        _ = torch.matmul(t1_gpu, t2_gpu)
        torch.cuda.synchronize()

        start_gpu = time.perf_counter()
        res_gpu = torch.matmul(t1_gpu, t2_gpu)
        torch.cuda.synchronize()
        end_gpu = time.perf_counter()
        gpu_time = end_gpu - start_gpu
    else:
        gpu_time = float("nan")

    delta = cpu_time - gpu_time

    print(f"{f'{dim}x{dim}':<10} | {cpu_time:<10.6f} | {gpu_time:<10.6f} | {delta:<10.6f}")
Dim        | CPU (s)    | GPU (s)    | Delta (s) 
--------------------------------------------------
1x1        | 0.000040   | 0.000050   | -0.000010 
4x4        | 0.000023   | 0.000045   | -0.000022 
9x9        | 0.000015   | 0.000038   | -0.000023 
16x16      | 0.000014   | 0.000045   | -0.000032 
25x25      | 0.000015   | 0.000043   | -0.000028 
36x36      | 0.000015   | 0.000043   | -0.000028 
49x49      | 0.000021   | 0.000044   | -0.000024 
64x64      | 0.000074   | 0.000045   | 0.000029  
81x81      | 0.000026   | 0.000044   | -0.000018 
100x100    | 0.000029   | 0.000044   | -0.000016 
121x121    | 0.000037   | 0.000046   | -0.000009 
144x144    | 0.000040   | 0.000045   | -0.000006 
169x169    | 0.000085   | 0.000047   | 0.000038  
196x196    | 0.000121   | 0.000070   | 0.000050  
225x225    | 0.000131   | 0.000049   | 0.000082  
256x256    | 0.000139   | 0.000052   | 0.000086  
289x289    | 0.000207   | 0.000047   | 0.000160  
324x324    | 0.000224   | 0.000052   | 0.000172  
361x361    | 0.000279   | 0.000052   | 0.000227  
400x400    | 0.000315   | 0.000056   | 0.000259  

Across several trials I'm pretty consistently seeing on Colab with an A100 that the GPU pulls ahead reliably with a 169x169 matrix.

In [ ]:
import torch

# Get the number of available GPUs
gpu_count = torch.cuda.device_count()
print(f"Number of GPUs available: {gpu_count}")

# Optional: Print the name of each GPU if available
for i in range(gpu_count):
    print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
Number of GPUs available: 1
GPU 0: NVIDIA A100-SXM4-40GB

I only have one GPU available in my colab plan, and only one GPU in my physical puter, so this is as far as it goes for me.