Skip to main content
LearnMLAcademy
Advanced10 min read

Tensors, Frameworks & GPUs

Manage multidimensional tensors and accelerate training on CUDA GPU hardware, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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

“Dimension” or “axis” means one direction in the array. “Rank” means how many axes exist. “Shape” lists the length of each axis.
ObjectRankExample shapePossible meaning
Scalar0[]one loss value: 0.24
Vector1[4]four features
Matrix2[8,4]eight examples × four features
3-D tensor3[10,20,64]batch × tokens × embedding features
4-D tensor4[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]

The numbers are manually chosen 8-bit teaching values from 0 to 255. They describe colour intensity; they are not class labels or learned weights.

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

32 × 3 × 64 × 64 = 393,216 stored values
A dimension's position changes its meaning. Some libraries or data pipelines use NHWC instead; confirm the convention expected by every layer.

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.

ResponsibilityFramework helps withYou still decide/check
Tensor computationfast kernels, broadcasting and device supportshapes, dtypes and semantic axes
Model definitionreusable layers and parameter registrationarchitecture and output meaning
Gradient calculationrecords operations and applies chain rulecorrect loss, graph connectivity and gradient scale
Optimizationstandard update algorithms and schedulerslearning rate, parameter groups and validation
Data inputbatching, transforms and parallel loadingsplit integrity, labels and preprocessing
Saving/exportstate and runtime conversion toolsversioned 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

Repeated CPU↔GPU copies can erase acceleration. Move batches in reasonably large chunks and keep connected operations on the same device.

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

dtypeTypical roleBenefitCaution
float32default model computationwide practical compatibilitymore memory than 16-bit formats
float16mixed-precision acceleration on supported hardwaresmaller/faster operationslimited range; gradients may underflow without scaling
bfloat16mixed precision on supported acceleratorsfloat32-like exponent rangefewer fraction bits; hardware support varies
int64 / longclass indices and token IDsexact integer indexingnot a normal neural-network weight dtype
boolmasksclear binary semanticscannot 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

tensor_device_basics.py
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

SymptomLikely reasonFirst inspection
matmul shape errorfeature dimension and weight input dimension differprint the two shapes and write [B,F]@[F,O]
expected 4-D inputbatch or channel axis missingprint shape after the data loader and transform
tensors on different devicesinput/target/model were moved inconsistentlyprint .device for each tensor and first parameter
wrong target type for classificationclass indices are floating point or one-hot for the chosen losscheck target shape/dtype against the loss contract
silent [B,B] outputa [B,1] value broadcast with a [B] valuemake singleton axes intentional; assert result shape
GPU slower than CPUworkload too small or copies/input pipeline dominatebenchmark after warm-up and profile transfers
CUDA out of memorybatch/activation/model state exceeds device memorymeasure 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.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Tensors, Frameworks & GPUs"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5interpretation
A tensor changes from shape [8,4] to [8,1] through a linear layer. What must the weight map?
Question 2 of 5conceptual
What does broadcasting do?
Question 3 of 5debugging/diagnostic
Why must model parameters and inputs usually be on the same device?
Question 4 of 5numerical/formula
How many float32 bytes are needed for 1,000 elements before training overhead?
Question 5 of 5practical selection
Why might a tiny model run slower on a GPU?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1A tensor changes from shape [8,4] to [8,1] through a linear layer. What must the weight map?▼

Correct Answer: 4 input features to 1 output

The batch dimension stays 8; the layer transforms each example's four features into one output.

2What does broadcasting do?▼

Correct Answer: Combines compatible shapes without manually copying the smaller tensor

Broadcasting expands compatible singleton or absent dimensions conceptually so element-wise operations can run.

3Why must model parameters and inputs usually be on the same device?▼

Correct Answer: Cross-device operations otherwise fail or require explicit transfer

Framework operations require participating tensors on compatible devices; repeated transfers also waste time.

4How many float32 bytes are needed for 1,000 elements before training overhead?▼

Correct Answer: 4,000

Float32 uses four bytes per element, so 1,000 values require 4,000 bytes.

5Why might a tiny model run slower on a GPU?▼

Correct Answer: Launch and transfer overhead can exceed the small computation

Accelerators help when enough parallel work amortizes data-transfer and kernel-launch overhead.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next