Deep Learning · Practical Foundations
Tensors, Frameworks and GPUs
Deep-learning code turns examples and model parameters into tensors, applies a recorded sequence of operations, and often runs those operations on a GPU. This lesson makes tensor shapes, axes, data types, broadcasting, matrix multiplication, device movement and framework responsibilities visible before they become confusing error messages.
What a Tensor Actually Is
A tensor is an organized collection of values used by a deep-learning framework. Besides the values themselves, the framework tracks its shape (axis lengths), data type or dtype (how each value is stored), and device (where it lives, such as CPU or GPU memory).
“Rank” here means the number of axes, not matrix rank. A scalar has no axes, a vector has one, a matrix has two, and an image batch commonly has four. Names such as batch, channel, height and width are meanings supplied by the programmer and data pipeline; the tensor itself mainly records their ordered sizes.
A tensor grows by adding named axes
Scalar
7
one number
loss = 7
Vector
[2, 5, 8]
one axis
3 features
Matrix
[[1,2],[3,4]]
rows × columns
2 examples × 2 features
3-D tensor
3 × 4 × 4
channels × height × width
one small RGB image
Batch tensor
8 × 3 × 4 × 4
examples × channels × height × width
8 small RGB images
| Object | Rank | Example shape | Possible meaning |
|---|---|---|---|
| Scalar | 0 | [] | one loss value: 0.24 |
| Vector | 1 | [4] | four features |
| Matrix | 2 | [8,4] | eight examples × four features |
| 3-D tensor | 3 | [10,20,64] | batch × tokens × embedding features |
| 4-D tensor | 4 | [32,3,64,64] | batch of colour images |
One colour pixel stores three channel values
Red
R = 240
Green
G = 120
Blue
B = 30
pixel vector
[240,120,30]
An image batch is one tensor with four named axes
[32, 3, 64, 64]
shape, in NCHW order
N = 32
batch
32 photographs
C = 3
channels
red, green, blue
H = 64
height
64 pixel rows
W = 64
width
64 pixel columns
Axes Explain Almost Every Shape Operation
Indexing selects values. Reshape groups the same number of values into different axis lengths. Transpose swaps two axes; permute can reorder several. Unsqueeze inserts a length-1 axis, often to create a batch or channel position, while squeeze removes a length-1 axis.
Tiny values: shape [2,3]
A = [[1,2,3],
[4,5,6]]
There are 2 rows and 3 columns, so 2×3=6 stored values.
Same values, different arrangements
reshape(3,2) → [[1,2],[3,4],[5,6]]
transpose(0,1) → [[1,4],[2,5],[3,6]]
unsqueeze(0) → shape [1,2,3]
Reshape changes grouping; transpose changes which axis comes first; unsqueeze adds a one-example batch axis.
Follow one image batch
x.shape = [32,3,64,64]
x[0].shape = [3,64,64]
select first image; batch axis disappears
x[:,0].shape = [32,64,64]
select red channel from every image
x.permute(0,2,3,1)
shape = [32,64,64,3]
NCHW → NHWC; values stay attached to their pixel
x.flatten(1).shape
= [32,12288]
3×64×64=12,288 features per image
These operations may return a view that shares memory or may require copying, depending on layout and framework rules. The beginner's first responsibility is semantic: after every change, write what each axis means and confirm the element count when reshaping.
Elementwise Operations and Matrix Multiplication Are Not the Same
Elementwise multiplication pairs values at matching positions. Matrix multiplication combines rows with columns using dot products. Confusing * with @ can produce an error—or worse, a valid but unintended result.
Elementwise
[1,2] * [3,4]
= [3,8]
same positions multiply
Dot product
[1,2] · [3,4]
= 1×3 + 2×4
= 11
products are summed
For matrix multiplication [B,F] @ [F,O] → [B,O]. B is batch size, F is input features and O is output features. The shared F dimensions are consumed by the dot products.
Broadcasting Reuses Smaller Tensors Without Manual Copies
Broadcasting allows compatible shapes to participate in an elementwise operation. Compare axes from the right: lengths must match, one must be 1, or an axis may be absent. The smaller tensor behaves as if expanded, usually without physically copying every value.
Add one feature bias to two examples
X = [[1,2,3], b = [10,20,30]
[4,5,6]]
X + b = [[11,22,33],
[14,25,36]]
Why it works: X has shape [2,3] and b has shape [3]. The trailing dimension 3 matches, so b is reused for both rows. Beware: [4,1] + [4] produces [4,4], which may run successfully while violating your intent.
What a Deep-Learning Framework Does for You
A framework such as PyTorch or TensorFlow is more than an array library. It supplies tensor operations implemented for different devices, neural-network layers, automatic differentiation, optimizers, data pipelines, serialization and deployment/export tools. Keras provides a higher-level model-building interface integrated with its supported backend ecosystem.
| Responsibility | Framework helps with | You still decide/check |
|---|---|---|
| Tensor computation | fast kernels, broadcasting and device support | shapes, dtypes and semantic axes |
| Model definition | reusable layers and parameter registration | architecture and output meaning |
| Gradient calculation | records operations and applies chain rule | correct loss, graph connectivity and gradient scale |
| Optimization | standard update algorithms and schedulers | learning rate, parameter groups and validation |
| Data input | batching, transforms and parallel loading | split integrity, labels and preprocessing |
| Saving/export | state and runtime conversion tools | versioned contract and equivalence tests |
Why GPUs Can Accelerate Deep Learning
A CPU is excellent for varied sequential work and system tasks. A GPU contains many execution units designed to perform large numbers of similar numerical operations in parallel. Matrix multiplications and convolutions contain abundant parallel work, so sufficiently large neural-network workloads can benefit.
The GPU has separate memory. Moving a model to the GPU does not automatically move an input batch, and mixing devices raises an error. Small workloads may be slower after transfer and launch overhead. Always benchmark the full input pipeline on the actual hardware.
The operation can only run where all required tensors live
🧠
CPU memory
batch from data loader
→
explicit transfer
⚡
GPU memory
input batch
x.to(device)
model weights
model.to(device)
operations
matmul / conv
output stays on the GPU until copied or consumed there
Memory Is Often the First GPU Limit
Training stores parameters, gradients, optimizer state and intermediate activations needed for backpropagation. A raw tensor's approximate storage is number of values × bytes per value.
Estimate one FP32 image batch
For shape [32,3,224,224], there are 32×3×224×224=4,816,896 values. FP32 uses 4 bytes per value.
4,816,896 × 4 = 19,267,584 bytes
≈ 18.4 MiB (divide by 1,048,576)
Interpretation: this is only the input tensor. Activations across layers, gradients and optimizer state can require far more. Halving batch size may reduce activation memory but does not halve fixed model/optimizer storage.
Data Types Trade Precision, Range, Memory and Speed
| dtype | Typical role | Benefit | Caution |
|---|---|---|---|
| float32 | default model computation | wide practical compatibility | more memory than 16-bit formats |
| float16 | mixed-precision acceleration on supported hardware | smaller/faster operations | limited range; gradients may underflow without scaling |
| bfloat16 | mixed precision on supported accelerators | float32-like exponent range | fewer fraction bits; hardware support varies |
| int64 / long | class indices and token IDs | exact integer indexing | not a normal neural-network weight dtype |
| bool | masks | clear binary semantics | cannot represent scores |
Automatic mixed precision lets a framework choose lower precision for suitable operations while keeping sensitive reductions or updates in safer precision. It is a controlled execution policy, not simply converting every tensor to half precision.
A Device-Safe PyTorch Example
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Two examples, each with three input features.
x = torch.tensor([[1., 2., 3.],
[4., 5., 6.]], device=device) # [2, 3]
w = torch.tensor([[0.1, 0.4],
[0.2, 0.5],
[0.3, 0.6]], device=device) # [3, 2]
b = torch.tensor([1.0, -1.0], device=device) # [2]
scores = x @ w + b # [2,3] @ [3,2] -> [2,2]; b broadcasts
print("device:", scores.device)
print("shape:", scores.shape)
print(scores)
assert scores.shape == (2, 2)
assert torch.isfinite(scores).all()Expected scores are [[2.4, 2.2], [4.2, 6.7]]. Print shape, dtype and device at boundaries before debugging the model's mathematics.
Shape and Device Errors Become Easier to Diagnose
| Symptom | Likely reason | First inspection |
|---|---|---|
| matmul shape error | feature dimension and weight input dimension differ | print the two shapes and write [B,F]@[F,O] |
| expected 4-D input | batch or channel axis missing | print shape after the data loader and transform |
| tensors on different devices | input/target/model were moved inconsistently | print .device for each tensor and first parameter |
| wrong target type for classification | class indices are floating point or one-hot for the chosen loss | check target shape/dtype against the loss contract |
| silent [B,B] output | a [B,1] value broadcast with a [B] value | make singleton axes intentional; assert result shape |
| GPU slower than CPU | workload too small or copies/input pipeline dominate | benchmark after warm-up and profile transfers |
| CUDA out of memory | batch/activation/model state exceeds device memory | measure peak memory; reduce batch/shape or use checkpointing/mixed precision |
A Practical Tensor Checklist
- Name every axis in words before writing a complex shape.
- Check shape, dtype, device and finite values at data/model/loss boundaries.
- Use
@for matrix multiplication and understand when broadcasting occurs. - Move the model, inputs and targets to the same device; avoid repeated transfers.
- Estimate memory from element count, then remember training needs activations and optimizer state too.
- Use mixed precision through the framework's supported mechanism and verify numerical quality.
- Benchmark real batches on the target hardware; a GPU is an accelerator, not a promise.