← All writing

PyTorch

PyTorch notes on datasets, data loaders, modules and training, with explanations of convolution shapes, tensor indexing and broadcasting.

PyTorch

Load Data

Dataset and DataLoader

In PyTorch, a Dataset is an abstract class (torch.utils.data.Dataset) that represents a collection of data. Its primary job is to provide a consistent interface for accessing individual data samples and their corresponding labels, decoupling the data storage from the model training code.

In Python, an abstract class is a blueprint for other classes. It allows you to define a set of methods that must be created within any child classes (subclasses) that inherit from it. (Like Java)

In PyTorch, torch.utils.data.DataLoader is an iterable that wraps a Dataset to provide high-performance data feeding. It handles the heavy lifting of batching, shuffling, and multi-processing so your training loop stays clean and fast.

The 4 Key Responsibilities of a DataLoader

A DataLoader transforms your Dataset into a "stream" of data ready for a Neural Network:

  1. Batching: Instead of passing one item at a time (which is slow), it groups NN items into a single tensor (a "batch").
  2. Shuffling: It reorders the data at every "epoch" (full pass through the data). This is crucial for preventing the model from learning the order of the data rather than the actual patterns.
  3. Parallel Loading: It uses num_workers to load data in the background using multiple CPU cores. While the GPU is training on Batch A, the CPU is already preparing Batch B.
  4. Automatic Collating: it takes the list of samples returned by your Dataset's __getitem__ and "collates" (glues) them into a single batch tensor.

Examle

python
import torch
from torch.utils.data import Dataset, DataLoader

def main():
    #  A raw dataset and each sample is a vector.
    data = [[2, 3, 5], [7, 11, 13], [17, 19, 23], [29, 31, 37]]
    label = [0, 1, 1, 0]

    # First, we should define a custom dataset by inheriting from 
    # Dataset(an abstract class).

    class customDataset(Dataset):
        # Implement the necessary abstract methods.
        def __init__(self, data, label):
            # Convert the lists to Tensors once at the start
            # otherwise it will be wrong!
            self.data = torch.tensor(data)
            self.label = torch.tensor(label)

        def __len__(self):
            return len(self.data)

        def __getitem__(self, idx):
            return self.data[idx], self.label[idx]
        
    # Second, we can create an instance of the custom dataset.
    dataset = customDataset(data, label)

    # Third, we can create a DataLoader to iterate over the dataset.
    dataLoader = DataLoader(
        dataset=dataset,         # The dataset to load from
        batch_size=2,           # How many samples per batch
        shuffle=True,            # Mix the data every epoch
        num_workers=4,           # Use 4 CPU cores to load data in parallel
        pin_memory=True          # Speeds up data transfer to GPU
    )
    
    # Finally, we can iterate over the DataLoader to get batches of data.
    for batch_idx, (data, label) in enumerate(dataLoader):
        print(f"Batch {batch_idx}:")
        print("Data:", data)
        print("Label:", label)

    # Batch 0:
    # Data: tensor([[29, 31, 37],[17, 19, 23]])
    # Label: tensor([0, 1])
    # Batch 1:
    # Data: tensor([[ 2,  3,  5],[ 7, 11, 13]])
    # Label: tensor([0, 1])

if __name__ == "__main__":
    main()

TensorDataset

we can use TensorDataset to directly create a Dataset class.

python
TensorDataset(X, y)

Train

Module

In PyTorch, a Model (or "Module") is a class that encapsulates the architecture of your neural network. It defines how data transforms from an input (like pixels) to an output (like a classification).

All models in PyTorch must inherit from the abstract base class torch.nn.Module.

python
    # Define a custom neural network by inheriting from nn.Module
    class customNeuralNet(nn.Module):
        def __init__(self, input_size, hidden_size, num_classes):
            # Required: Initialize the parent nn.Module
            super(customNeuralNet, self).__init__()  
            
            # Define the components (the "machinery")
            self.layer1 = nn.Linear(input_size, hidden_size) 
            self.layer2 = nn.Linear(hidden_size, num_classes)
            self.relu = nn.ReLU() # An activation function to introduce non-linearity

        def forward(self, x):
            # Define the data flow (the "assembly line")
            out = self.layer1(x)
            out = self.relu(out)
            out = self.layer2(out)
            return out

Training

python
    # Create an instance of the neural network
    model = customNeuralNet(input_size=featureNum, hidden_size=5, num_classes=2)

    # Define a loss function and an optimizer
    criterion = nn.CrossEntropyLoss()  # Suitable for multi-class classification
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

    num_epochs = 30 # How many times to see the whole dataset

    for epoch in range(num_epochs):
        epoch_loss = 0.0
        for batch_idx, (inputs, targets) in enumerate(train_loader):

            # 1. Zero the gradients 
            # (Important: Clear the "memory" of previous errors)
            optimizer.zero_grad()

            # 2. Forward Pass: Get predictions
            outputs = model(inputs)

            # 3. Compute Loss: How wrong was the model?
            loss = criterion(outputs, targets)

            # 4. Backward Pass: Calculate the gradients
            loss.backward()

            # 5. Optimizer Step: Update the model weights
            optimizer.step()

            epoch_loss += loss.item()

        # Print progress every 10 epochs
        if (epoch + 1) % 10 == 0:
            print(f"Epoch [{epoch+1}/{num_epochs}], Avg Loss: {epoch_loss/len(train_loader):.4f}")

    model.eval() # Set model to evaluation mode
    correct = 0
    total = 0

    with torch.no_grad(): # Turn off gradient calculation
        for inputs, targets in test_loader:
            # shape of inputs: torch.Size([32, 10]), shape of targets: torch.Size([32])
            print(f"shape of inputs: {inputs.shape}, shape of targets: {targets.shape}")
            # Get predictions
            outputs = model(inputs)
            
            print(f"outputs: {outputs}")
            # CrossEntropyLoss outputs 'logits' (raw scores). 
            # We take the index of the highest score as our predicted class.
            _, predicted = torch.max(outputs.data, dim=1)
            
            total += targets.size(0)
            correct += (predicted == targets).sum().item()

    print(f'Accuracy on the 200 test samples: {100 * correct / total:.2f}%')

nn.Conv2d

Refer to Conv2d: Finally Understand What Happens in the Forward Pass | by Axel Thevenot 🐣 | TDS Archive | Medium

python
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)

One input channel and one output channel

Input shape : (1, 9, 9) β€” Output Shape : (1, 7, 7) β€” K : (3, 3) β€” P : (0, 0) β€” S : (1, 1) β€” D : (1, 1) β€” G : 1

External image Β· miro.medium.com

One input channel and multiple output channels

Input Shape: (1, 7, 7) β€” Output Shape : (4, 5, 5) β€” K : (3, 3) β€” P : (0, 0) β€” S : (1, 1) β€” D : (1, 1) β€” G : 1

output channles are 4, so there are 4 kernels.

External image Β· miro.medium.com

Multiple input channels and one output channel

There are 2 input channels and thus two kernels.

image-20260116163457648

Multiple input channels and multiple output channels

NOTE: The number of kernel is equal to input channels times outout channels!

External image Β· miro.medium.com

nn.Conv1d

nn.Conv1d is used when your data only has one spatial or temporal dimension to slide across.

While Conv2d slides a box across a picture (Height and Width), Conv1d slides a line across a sequence (like Time). It is the go-to layer for time-series data, audio signals, and natural language text.

Here is the most important rule to remember for nn.Conv1d: it strictly expects an input shape of [Batch, Channels, Length].

nn.Conv1d is similar as nn.Conv2d

python
import torch
import torch.nn as nn

# 16 samples, 1 sensor (channel), 100 time steps
data = torch.randn(16, 1, 100) 

# in_channels=1 (our single sensor)
# out_channels=8 (we want to learn 8 different temporal patterns)
# kernel_size=3 (look at 3 time steps at once)
conv1d = nn.Conv1d(in_channels=1, out_channels=8, kernel_size=3)

output = conv1d(data)

# Length becomes 98 because we didn't use padding (100 - 3 + 1)
print(output.shape) 
# Output: torch.Size([16, 8, 98])

Advanced indexing

Tensor Index

1D

python
import torch

# Simple 1D data
data = torch.tensor([100, 200, 300, 400])

# 1D index tensor (Notice we ask for index '3' twice)
idx = torch.tensor([0, 3, 3])

result = data[idx]
print(result)
# Output: tensor([100, 400, 400])

N-Dimensional Tensor

If the shape of array tensor is [fisrt_dim, ...(arrary)] and the shape of index tensor is [...(index)]

Then the the shape of result will be [...(index),...(arrary)].

python
import torch

array = torch.ones((10,3,4))
index = torch.tensor([[2, 3],
                      [4, 5],
                      [6, 7]])

result = array[index]
# Shape of arrary torch.Size([10, 3, 4]), 
# shape of index torch.Size([3, 2]), 
# shape of result torch.Size([3, 2, 3, 4])
print(f"Shape of arrary {array.shape}, shape of index {index.shape}, shape of result {result.shape}")

Mask

Broadcast

1. The Two Golden Rules of Broadcasting

When you try to add, multiply, or compare two tensors, PyTorch aligns their shapes starting from the right side (trailing dimensions) and moving left.

Two dimensions are considered "compatible" if:

  1. They are exactly equal.
  2. One of them is 1. (PyTorch will stretch the 1 to match the other number, i.e. copy itself to match.).

If a tensor has fewer dimensions than the other, PyTorch automatically pads its left side with 1s.

Dim 4: 32 and 1 β†’\rightarrow Match! (The 1 stretches to 32)

Dim 3: 1 and 1 β†’\rightarrow Match!

Dim 2: 16 and 16 β†’\rightarrow Match! (They are equal)

Dim 1: 64 and (missing) β†’\rightarrow Match! (PyTorch pretends the missing dim is 1, then stretches it to 64, i.e., copy 64 times)

python
features = torch.randn(64, 16, 1, 32)
weights = torch.randn(16, 1, 1) # Must format it like this!

# This works perfectly without crashing
scaled_features = features * weights 
print(scaled_features.shape)
# Output: torch.Size([64, 16, 1, 32])

Optimizer

All built-in optimizers (like optim.SGD, optim.Adam, or optim.RMSprop) inherit from this base class torch.optim.Optimizer.

The Two Main Components of an Optimizer

When you create an optimizer, it relies on two internal dictionaries to keep track of training:

  • param_groups: A list of dictionaries. It holds the actual model parameters (weights/biases) and the hyperparameters associated with them (like lr for learning rate, or weight_decay). This is what allows you to use different learning rates for different layers.
  • state: A dictionary that remembers the "history" of each parameter. For example, in Adam or SGD with Momentum, the optimizer needs to remember the gradient from the previous step to calculate the current step. The state dictionary stores this memory.

super().__init__()

python
class AdamW(torch.optim.Optimizer):
    def __init__(self, params, lr, beta, eps, lam):

        default = dict(lr = lr, beta = beta, eps = eps, lam = lam)

        # PyTorch takes your raw params and your defaults dictionary 
        # and fuses them into a structured list called self.param_groups.
        super().__init__(params, default)

self.param_groups

self.param_groups is the organizational heart of a PyTorch optimizer. Despite the name, it is actually a list of dictionaries.

If you were to print(optimizer.param_groups) inside your training loop, here is a simplified look at exactly what PyTorch outputs:

Python

python
[
    {
        'params': [
            Parameter containing: tensor([[[...]]], requires_grad=True), # conv1.weight
            Parameter containing: tensor([0.1, ...], requires_grad=True), # bn1.weight
            Parameter containing: tensor([-0.5, ...], requires_grad=True) # bn1.bias
            # ... all other weights in your model
        ],
        'lr': 0.01,
        'momentum': 0.0,
        'weight_decay': 0.0,
        'dampening': 0,
        'nesterov': False
    }
]

Here is a breakdown of what you are looking at:


1. The List [ ... ]

By default, the list only contains one single dictionary (Index 0). This is because when you initialize your optimizer with optim.SGD(model.parameters(), lr=0.01), you are telling PyTorch to put every single layer into one big group and apply the exact same rules to all of them.

2. The 'params' Key

This is the most important part of the dictionary. It holds a list of the actual memory addresses of your model's weights and biases.

  • When your custom step() function loops through group['params'], it is directly modifying the tensors inside this specific list.
  • Because Python passes objects by reference, changing the tensor inside this optimizer dictionary automatically changes the tensor inside your nn.Module.

3. The Hyperparameter Keys

The rest of the dictionary contains the rules for how to update the tensors in the 'params' list.

  • 'lr': The learning rate for this specific group.
  • 'weight_decay', 'momentum', etc.: These are populated by the defaults dictionary you passed into the super().__init__(params, defaults) function.

Why is it a List of Groups? (The Superpower)

You might wonder why PyTorch bothers making it a list of dictionaries instead of just one single dictionary.

It is designed this way so you can create Multiple Parameter Groups. This allows you to apply different learning rates or weight decays to different parts of your network.

For example, if you are using a pre-trained model, you usually want to train the final classification layer very fast, but barely touch the earlier convolutional layers so they don't forget what they learned.

If you set up multiple groups, your param_groups looks like this:

Python

python
[
    # Group 0: Feature Extractor (Slow Learning Rate)
    {
        'params': [conv1.weight, conv2.weight, ...],
        'lr': 0.0001  
    },
    # Group 1: Classifier (Fast Learning Rate)
    {
        'params': [fc.weight, fc.bias],
        'lr': 0.01    
    }
]

When your step() function runs, it will process Group 0 with the tiny learning rate, and then process Group 1 with the large learning rate.

example

python
class AdamW(torch.optim.Optimizer):
    def __init__(self, params, lr, beta, eps, lam):

        default = dict(lr = lr, beta = beta, eps = eps, lam = lam)

        # PyTorch takes your raw params and your defaults dictionary 
        # and fuses them into a structured list called self.param_groups.
        super().__init__(params, default)

    @torch.no_grad() # CRITICAL: We don't want PyTorch to track these updates!
    def step(self, closure = None):
        # The API specifies that the user might pass in a callable closure to 
        # re-compute the loss before the optimizer step. We won't need this for the 
        # optimizers we’ll use, but we add it to comply with the API.
        loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        # Loops through your layer groups. 
        # If you passed all model.parameters() at once, there is only one group
        for group in self.param_groups:
            # This 
            alpha = group["lr"]
            beta1= group["beta"][0], beta2 = group["beta"][1]
            eps = group["eps"]
            lam = group["lam"]

            # Iterate over the specific parameters (weights/biases) in this group
            # e.g., conv1.weight, bn1.weight, bn1.bias and so on.
            for p in group['params']:
                # If this parameter doesn't have a gradient, skip it
                if p.grad is None:
                    continue
                # Get state associated with p.
                # Used to store and initialize these moment vectors.
                state = self.state[p]
                # Get iteration number from the state, or initial value.
                t = state.get("t", 1)
                m = state.get("m", torch.zeros_like(p))
                v = state.get("v", torch.zeros_like(p))

                # Get the actual gradient data
                g = p.grad.data
                m = beta1 * m + (1 - beta1) * g
                v = beta2 * v + (1 - beta2) * (g ** 2)
                alpha_t = alpha * math.sqrt(1 - math.pow(beta2, t)) / (1 - math.pow(beta1, t))
                p.data -= alpha_t * m / (torch.sqrt(v) + eps)
                p.data -= alpha * lam * p.data
                state["t"] = t + 1
                state["m"] = m
                state["v"] = v
            
        return loss

wandb

Wandb stands for Weights & Biases. It is a wildly popular, free-to-use developer tool used by Machine Learning engineers to track, visualize, and save their experiments

How to use it

Tiny example:

python
import wandb

# 1. Start a new run, give it a name, and save your settings
wandb.init(
    project="my-awesome-project",
    config={
        "learning_rate": 0.01,
        "epochs": 100,
        "architecture": "CNN"
    }
)

# ... inside your standard PyTorch training loop ...
for epoch in range(epochs):
    for samples, targets in train_bar:
        outputs = model(samples)
        loss = criterion(outputs, targets)
        
        loss.backward()
        optimizer.step()
        
        # 2. Log the metrics to the cloud!
        wandb.log({"Train Loss": loss.item(), "Epoch": epoch})

# 3. Tell wandb you are done
wandb.finish()

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.