A PyTorch MNIST Digit Classifier: Parameters and Memory Math
PyTorch
Machine Learning
Python
Jupyter
A torchvision v2 image classifier and its memory footprint
Author
Dennis Chua
Published
November 23, 2026
Neural networks often feel like abstract black boxes until we inspect the actual arrays of numbers sitting in memory. In this walk through, we will strip away the mystery with a self-contained PyTorch exercise: loading a single handwritten digit, wiring up a minimal classifier, and auditing every learnable number inside it.
Along the way, we will see how the exact same parameter-counting loop that measures a 407 KB toy network explains why modern 8-billion-parameter LLMs require tens of gigabytes of VRAM.
From Pixels to Tensors (torchvision.transforms.v2)
Before we define a model, we need real data to anchor our mental model. We will pull a single sample from the classic MNIST dataset of handwritten digits using PyTorch’s modern torchvision.transforms.v2 pipeline.
MNIST: A database of handwritten digits. MNIST has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available from NIST. See this MNIST reader code.
import torchimport torch.nn as nnfrom torchvision import datasetsfrom torchvision.transforms import v2transform = v2.Compose([ v2.ToImage(), # PIL image converted to image tensor v2.ToDtype(torch.float32, scale=True) # Cast to float32, scale pixels to range 0.0 -> 1.0])# Fetch MNIST once and apply the transform-to-tensor method to each imagetrain_data = datasets.MNIST(root="data", train=True, download=True, transform=transform)# Inspect one image and its labelimage, label = train_data[0]print("Image tensor shape:", image.shape)print("Label:", label)
The transform pipeline:v2.ToImage() converts the raw PIL image into a uint8 image tensor, and v2.ToDtype(torch.float32, scale=True) casts the pixel values to 32-bit floats while scaling them from [0, 255] down to [0.0, 1.0].
The tensor shape:torch.Size([1, 28, 28]) follows PyTorch’s standard [Channels, Height, Width] layout: 1 grayscale channel, 28 pixels tall, and 28 pixels wide.
Let’s convert that tensor back to a PIL image and render it so we can see what we are working with.
import matplotlib.pyplot as pltto_pil = v2.ToPILImage()pil_image = to_pil(image)plt.imshow(pil_image, cmap="gray")plt.axis("off")plt.show()
First training sample from MNIST (label: 5).
We have our concrete artifact: a single handwritten 5, represented in memory as a \(1 \times 28 \times 28\) grid of float32 numbers.
Defining and Verifying the Architecture
Next, let’s build a minimal multi-layer perceptron (DigitClassifier) by subclassing nn.Module.
class DigitClassifier(nn.Module):def__init__(self):super().__init__()self.flatten = nn.Flatten()self.layer1 = nn.Linear(784, 128)self.activation = nn.ReLU()self.layer2 = nn.Linear(128, 10)def forward(self, x): x =self.flatten(x) x =self.layer1(x) x =self.activation(x) x =self.layer2(x)return xmodel = DigitClassifier()print(model)
Calling print(model) is the fastest sanity check in PyTorch. Each line echoes the exact attribute name we assigned in __init__ alongside its layer configuration:
flatten: The Linear layers in our neural net can not process 2D data. We first must unroll the 2D \(28 \times 28\) grid into a flat 1D vector of \(784\) pixel features (while leaving the batch dimension intact). Essentially .flatten reshapes the tensor as [1, 28, 28] \(\rightarrow\) [1, 728].
layer1: A fully connected (Linear) layer that projects those \(784\) inputs into \(128\) hidden features.
activation: A ReLU activation function (max(0, x)) that introduces non-linearity without changing the tensor’s shape.
layer2: A final Linear layer that maps the \(128\) hidden features down to \(10\) output scores—one for each digit class (0 through 9).
Default torch.nn.Flatten parameters: Our .flatten is called with default parameters (start_dim=1, end_dim=-1). These instruct PyTorch to retain dimension zero (batch size) while collapsing the remaining dimensions per sample.
The numbers a neural network actually learns during training all stay in its parameters, specifically the weights and biases of its layers. We can inspect every parameter in our model using model.named_parameters() and count the individual scalar values inside each tensor with .numel() (“number of elements”).
total =0for name, param in model.named_parameters(): count = param.numel() total += countprint(f"{name:16} shape {tuple(param.shape)} -> {count} values")print(f"\nTotal learnable parameters: {total}")
Running this loop highlights three important details about how PyTorch structures models in memory:
Tensors vs. Elements: Each param is a single torch.nn.Parameter tensor; for example, layer1.weight is one 2D tensor of shape (128, 784). Calling .numel() multiplies its dimensions (\(128 \times 784 = 100,352\)) to count the individual scalar torch.float32 numbers stored inside that buffer.
Stateless Layers Disappear: Notice that flatten and activation (ReLU) do not appear in the output. They are pure mathematical operations with no learnable weights or biases of their own.
Weight Matrix Orientation: PyTorch stores nn.Linear weight matrices with shape (out_features, in_features). That is why layer1.weight has shape (128, 784), indicating that each of the 128 output neurons stores its own contiguous row of 784 weights.
Here is the complete memory breakdown for our untrained classifier in default torch.float32 precision (4 bytes per scalar value):
Parameter
Tensor Shape
Element Count
Size in float32
layer1.weight
(128, 784)
100,352
~401.4 KB
layer1.bias
(128,)
128
0.5 KB
layer2.weight
(10, 128)
1,280
~5.1 KB
layer2.bias
(10,)
10
40 B
Total
—
101,770
~407.1 KB
Every single number that backpropagation will adjust during training fits comfortably in roughly 407 KB of RAM.
Scaling the Intuition: From 407 KB to Qwen3-8B
This simple counting exercise scales directly to modern foundation models. When we read that a dense LLM like Qwen3-8B has 8 billion parameters, that number refers to the exact same param.numel() total we just computed. The loop sums every weight matrix, bias vector, embedding lookup table, and normalization scale across all of its Transformer layers.
Qwen3-8B is a dense casual language model from Alibaba’s Qwen3 series.
The memory math is identical:
Full precision (float32, 4 bytes/value):\(8 \times 10^9 \times 4\text{ bytes} = \mathbf{32\text{ GB}}\) just to hold the static weights in memory.
Half precision (float16 / bfloat16, 2 bytes/value): Cuts the footprint in half to ~16 GB.
8-bit quantization (int8, 1 byte/value): Shrinks the weights to ~8 GB.
4-bit quantization (int4, ~0.5 bytes/value): Brings the static weights down to ~4–5 GB, making it possible to run an 8B model on a consumer GPU with room left over for the context window (KV cache).
Notice what stays constant across every precision tier. The number of parameters (8 billion) never changes, only the byte width of each individual scalar value shrinks.