Bitpath

Lesson 1 · Unit 03

Modules

Layers that own their weights, and models built from layers

13 exercisesabout 3 min

What you practise

  • nn.Module, nn.Linear and its parameter shapes, forward, activations, nn.Sequential, counting parameters

Try a question from this lesson

Pick one

A layer turns 3 input numbers into 2 outputs as W @ x + b. How many numbers does it have to learn? What does this print?

Python
import torch.nn as nn

layer = nn.Linear(3, 2)
ps = layer.parameters()
print(sum(p.numel() for p in ps))
Hint

W needs one row per output and one column per input. Then there is one bias per output.

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

nn.Linear keeps W and b for you

nn.Linear(n_in, n_out) creates a weight of shape (n_out, n_in) and a bias of shape (n_out,), randomly initialised and already tracking gradients.

Calling the layer on a batch of shape (N, n_in) computes x @ W.T + b for every row and returns shape (N, n_out).

Python
import torch
import torch.nn as nn

layer = nn.Linear(3, 2)
print(layer.weight.shape)  # [2, 3]
print(layer.bias.shape)    # [2]
x = torch.ones(5, 3)       # 5 samples
print(layer(x).shape)      # [5, 2]

11 more exercises in the app

  • 3× type the answer
  • 4× multiple choice
  • 2× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy