Skip to main content

1. What is PyTorch?

PyTorch is an open-source machine-learning and deep-learning framework. It provides tools for creating, training, evaluating, and deploying neural networks. PyTorch is especially popular because it provides:
  • Easy-to-use tensor operations
  • Automatic differentiation
  • GPU acceleration
  • Neural-network building blocks
  • Flexible training loops
  • Support for CNNs, RNNs, Transformers, and generative models
  • Strong research and production ecosystem

Main PyTorch components

Installation

Check the installation:

Why learn PyTorch?

If you want to work in:
  • Deep Learning
  • Computer Vision
  • NLP
  • Generative AI
  • LLMs
  • Research
  • AI engineering
then PyTorch is one of the most important frameworks to understand.

2. Importing PyTorch

The basic import is:
For neural networks:
For optimizers:
For datasets and batching:
For computer vision:

What does nn mean?

torch.nn contains the building blocks used to construct neural networks. For example:

3. What is a Tensor?

A tensor is the fundamental data structure in PyTorch. You can think of tensors as generalized arrays.

Scalar

A scalar contains one value. Its shape is:

Vector

Shape:

Matrix

Shape:
That means:

Why are tensors important?

Almost everything in a neural network is represented using tensors:
Understanding tensor shape, dtype, and device is one of the most important PyTorch skills.

4. Creating Tensors

torch.zeros()

Creates a tensor filled with zeros.
This creates:
Useful when initializing values.

torch.ones()

Creates a tensor containing only ones.

torch.rand()

Creates random numbers between 0 and 1.

torch.randn()

Generates random values approximately following a standard normal distribution.
This is frequently used for testing neural networks and creating synthetic data.

torch.randint()

Creates random integers.
This generates values from 0 through 9.

torch.arange()

Creates a sequence.
Output:

5. Tensor Data Types

Every tensor has a data type.
Common data types include:
For example:

Why does dtype matter?

Neural networks normally perform calculations using floating-point numbers. For example:
Now:
For classification labels, however, torch.int64 is commonly required by CrossEntropyLoss. So dtype depends on what the tensor represents.

6. Tensor Shape

Shape tells us the dimensions of a tensor.
Output:
This means:

Number of elements

For a [2, 3, 4] tensor:
So numel() returns 24.

7. Tensor Indexing

PyTorch indexing works similarly to NumPy.
First row:
Output:
Specific element:
Output:

Slicing

The : means “all rows”. So this means:
Result:

8. Tensor Arithmetic

Given:
Addition:
Subtraction:
Element-wise multiplication:
Division:
Power:
Important distinction:
means element-wise multiplication. It does NOT mean matrix multiplication.

9. Matrix Multiplication

Consider:
Element-wise multiplication:
gives:
Matrix multiplication:
or:
gives:

Important interview question

What is the difference between:
and:
Answer:

10. Useful Tensor Functions

PyTorch provides many mathematical operations.
Other useful operations:

argmax()

argmax() returns the index of the largest value.
Result:
This is frequently used for classification predictions.

11. Reshaping Tensors

Neural networks often require data in a particular shape. Suppose:
Current shape:
We can reshape it:
Now:
The number of elements must remain the same:

view()

Another way:
view() has stricter memory-layout requirements than reshape(), so reshape() is often the more convenient choice.

flatten()

This converts:
into:
Flattening is particularly important when connecting CNN features to fully connected layers.

12. unsqueeze() and squeeze()

These operations add and remove dimensions. Suppose:
Shape:
Add a dimension:
Now:
This is useful when a model expects a batch dimension. For example:
Remove a dimension:

13. Concatenation and Stacking

torch.cat()

Concatenates tensors along an existing dimension.
Result:

torch.stack()

Creates a new dimension.
Result shape:

Difference


14. NumPy and PyTorch

PyTorch works closely with NumPy. NumPy → PyTorch:
PyTorch → NumPy:
When possible, these objects can share the same underlying memory. Therefore, changing one can affect the other.

15. CPU and GPU

Deep-learning training can be much faster on GPUs. Check whether CUDA is available:
Select a device:
Move a tensor:
Move the model:
During training, both inputs and model parameters must generally be on compatible devices:

Important rule

You cannot normally do:
and expect the operation to work. Both need to be on compatible devices.

16. Autograd

One of PyTorch’s most important features is automatic differentiation. Suppose:
Mathematically:
If:
then:
PyTorch can calculate this automatically.
Output:

What happened?

This mechanism is the foundation of neural-network training.

17. Gradient Descent

Suppose our model is:
The model has parameters:
During training:
Example:
The gradient tells us how changing w would affect the loss. The optimizer uses this information to update w.

18. Why zero_grad()?

PyTorch gradients accumulate by default. For example:
The second backward pass adds to the existing gradient. Therefore, during normal training we use:
The standard sequence is:
Meaning:

19. nn.Module

Neural networks normally inherit from:
Example:
Create the model:

Two important methods

__init__() defines the layers.
forward() defines how data flows through the model.
When you write:
PyTorch internally calls the model’s forward logic.

20. nn.Linear

A linear layer performs:
Example:
Output:
Why?
So:

21. Activation Functions

A neural network containing only linear operations is still effectively a linear transformation. Activation functions introduce non-linearity.

ReLU

Mathematically:
Therefore:
ReLU is one of the most commonly used hidden-layer activations.

Sigmoid

Output values lie between:
It is commonly useful for binary probabilities, although modern PyTorch training often uses BCEWithLogitsLoss directly on logits rather than explicitly applying sigmoid before the loss.

Tanh

Output range:

Softmax

Softmax converts logits into a probability distribution across classes.
The probabilities approximately sum to:
However, when using:
you normally pass the raw logits directly rather than applying Softmax first.

22. Building a Neural Network

The architecture is:
The final 2 might represent two output classes.

23. nn.Sequential

nn.Sequential allows you to define layers in order. Instead of:
you can write:
Then:
It is excellent for simple feed-forward architectures. For complicated architectures with branches or multiple inputs, explicit forward() logic is usually preferable.

24. Loss Functions

A loss function measures how different the model prediction is from the target. Conceptually:
The optimizer then uses the gradient of this loss to improve the model.

MSE Loss

Mean Squared Error is commonly used for regression.
Conceptually:

Cross Entropy

Used very commonly for multi-class classification.
Important:
Do not normally do:
before passing them to CrossEntropyLoss.

BCEWithLogitsLoss

For binary classification:
This combines sigmoid behavior with binary cross entropy in a numerically stable way. Therefore it is generally preferred over:
as a training setup.

25. Optimizers

The optimizer changes the model parameters using gradients. Common optimizers:

SGD

Adam

AdamW

What is learning rate?

Learning rate controls how large each parameter update is. Very large:
Very small:
The learning rate is one of the most important hyperparameters.

26. Complete Training Loop

The training loop is arguably the most important PyTorch pattern to understand.
Understand every line:

1. model.train()

Tells PyTorch that the model is in training mode. This matters for layers such as:
  • Dropout
  • BatchNorm

2. Move data

Moves data to CPU or GPU.

3. Forward pass

The model generates predictions.

4. Calculate loss

Measures prediction error.

5. Clear old gradients

6. Backpropagation

Calculates gradients.

7. Update parameters

Updates model weights. The entire process is:

27. Dataset

A Dataset defines how your data is accessed.
There are three important parts.

__init__()

Stores or prepares the data.

__len__()

Returns the number of samples.

__getitem__()

Returns one sample. For example:

28. DataLoader

A Dataset gives individual samples. A DataLoader creates batches.
Then:

Why use DataLoader?

Instead of processing:
we process:
This makes training more efficient. Important parameters include:

29. Training, Validation and Test Sets

A common structure is:

Training set

Used to update model parameters.

Validation set

Used during development to make decisions such as:
  • Which model is better?
  • Which hyperparameters should we use?
  • When should training stop?

Test set

Used for final evaluation. Example:
For real projects, validation should usually be kept separate from the final test set.

30. Evaluation

During evaluation:
Then disable gradient calculation:
Why? During inference we don’t need gradients. This saves:
  • Memory
  • Computation
  • Time

31. Classification Accuracy

Example:
Suppose:
Then:

32. model.train() vs model.eval()

This distinction is extremely important. Training:
Evaluation:
Why does this matter? Because some layers behave differently during training and evaluation. Most importantly:
For example, Dropout randomly removes activations during training but should not randomly remove them during evaluation.

33. Dropout

Dropout is a regularization technique. It randomly disables some activations during training.
Approximately 50% of eligible activations are dropped during training. Example:

Why use Dropout?

It can reduce overfitting. Without regularization:
This suggests the model may be memorizing training data.

34. Batch Normalization

Batch normalization normalizes activations using batch statistics during training. Example:
It can help stabilize optimization and sometimes speed up training. During evaluation, BatchNorm uses stored running statistics, which is another reason model.eval() matters.

35. Weight Initialization

Neural-network layers receive default parameter initialization from PyTorch. You can customize it. Xavier initialization:
Kaiming initialization:
Good initialization can help optimization, especially in deeper networks.

36. CNN — Convolutional Neural Network

CNNs are designed particularly for spatial data such as images. Typical architecture:
A CNN learns features progressively. Early layers may learn:
Middle layers may learn:
Deeper layers may learn:

37. Conv2d

Example:
For an RGB image:
The 32 output channels mean the layer learns 32 filters. Input:
Meaning:

38. Pooling

Max pooling reduces spatial dimensions.
Spatial dimensions change:
Pooling reduces spatial resolution and can make representations more compact.

39. Complete CNN

If the input is:
after two 2×2 pooling operations:
So the feature map becomes:
That explains:

40. Image Dataset with Torchvision

PyTorch provides datasets through torchvision. Example using MNIST:
Create a DataLoader:

41. Image Transformations

Transforms preprocess and augment images. Convert image to tensor:
Resize:
Normalize:
Data augmentation:

Why augmentation?

Instead of showing the model exactly the same images repeatedly, we create slightly modified versions. Examples:
This can improve generalization.

42. Transfer Learning

Training a large image model from scratch requires a lot of data and computation. Transfer learning starts with a model that has already learned useful visual features. Example:
Replace the final layer:
If your dataset has 10 classes, the final layer needs 10 outputs.

Freezing the pretrained layers

Then enable training for the classifier:
This is called feature extraction. Later, you can optionally unfreeze some pretrained layers and fine-tune them.

43. RNN

RNN stands for Recurrent Neural Network. RNNs process sequential information. Examples:
Example:
Shape:
Here:

44. LSTM

LSTM means Long Short-Term Memory. It was designed to better preserve useful information over longer sequences than a basic RNN.
LSTM maintains:
These allow information to persist through the sequence.

45. GRU

GRU means Gated Recurrent Unit. It is another recurrent architecture.
Compared with LSTM, GRU has a simpler gating structure and does not maintain a separate cell state.

46. Transformer

Transformers became fundamental to modern NLP and generative AI. A Transformer uses attention to determine which parts of a sequence are important to each other. Example:
Conceptually:
Transformers are the foundation of many modern language models.

47. Attention

Attention answers a basic question:
“Which other pieces of information should this token pay attention to?”
The mathematical form is:
Where:
PyTorch implementation:
When:
this is self-attention.

48. Embeddings

Neural networks cannot directly understand words such as:
They are represented as token IDs. For example:
An embedding converts these IDs into dense vectors.
Shape:
Meaning:

49. Simple NLP Model

The flow is:
This is a simple educational model, not a modern LLM architecture.

50. Model Parameters

Every neural network contains parameters such as weights and biases. View them:
Count all parameters:
Count only trainable parameters:
This is particularly useful when comparing model sizes.

51. Saving a Model

The recommended approach is usually to save the model’s state_dict.
Later:

What is state_dict()?

It is essentially a dictionary containing the model’s learned parameters and buffers.

52. Saving a Checkpoint

If training takes hours or days, save checkpoints.
Load:
A checkpoint allows you to continue training instead of starting from zero.

53. Learning Rate Scheduler

A learning-rate scheduler changes the learning rate during training. Example:
Then:
Conceptually:
Other schedulers include:

54. Early Stopping

Sometimes validation performance stops improving. Instead of continuing forever, we can stop training. Concept:
Example:
The important idea is to save the best model, not necessarily the model from the final epoch.

55. Mixed Precision

Modern GPUs can perform some operations efficiently using lower-precision numerical formats. Mixed precision can provide:
  • Faster training
  • Lower GPU memory usage
  • Better hardware utilization
Example:
This is especially useful for large neural networks and GPU training.

56. Gradient Clipping

Sometimes gradients become extremely large. This is called exploding gradients. Gradient clipping limits their magnitude.
It is particularly useful in some recurrent-network training scenarios.

57. Freezing Parameters

Sometimes you don’t want to train every layer.
Now those parameters will not receive normal gradient-based updates. To train a specific layer:
This is heavily used in transfer learning and fine-tuning.

58. torch.no_grad()

For inference:
no_grad() tells autograd that gradients are not needed. Benefits:
Remember:
and:
serve different purposes. eval() changes model behavior. no_grad() disables gradient tracking. You commonly use both during inference.

59. detach()

Suppose:
Output:
detach() creates a tensor that is disconnected from the current computation graph. For example:
This is useful when you want to take model outputs outside PyTorch’s gradient computation.

60. Random Seeds

For reproducibility:
For CUDA:
However, a seed does not automatically guarantee perfect reproducibility in every environment. Results can also depend on:
  • GPU hardware
  • CUDA version
  • Backend algorithms
  • Parallelism
  • Other libraries

61. Classification Example

Training:
The model receives:
and predicts one of:

62. Regression Example

Regression predicts continuous values. Suppose:
We can create synthetic training data:
Model:
Loss:
Optimizer:
Training:
The model should learn parameters close to:

63. Binary Classification

For binary classification, the model can produce one logit per sample.
Loss:
Training:
Convert logits to probabilities:
Convert probabilities to binary predictions:
Important distinction:

64. Multi-Class Classification

Suppose the classes are:
Then the output layer needs three outputs:
The model returns logits:
Choose the class with the highest logit:
Loss:
Targets should normally be class indices:
rather than one-hot vectors.

65. Autoencoder

An autoencoder learns to reconstruct its input. Architecture:
Example:
Loss:
The model attempts to make:

66. GAN Basics

GAN means Generative Adversarial Network. It contains two networks:
The Generator tries to create convincing fake samples. The Discriminator tries to distinguish real samples from generated samples. Generator:
Discriminator:
GAN training is more complicated than ordinary supervised training because two networks are optimized against each other.

67. Custom Loss Function

You can create your own loss.
Use it:
This is useful when the problem requires a specialized objective.

68. Custom Layer

PyTorch also allows custom neural-network layers.

Why nn.Parameter?

nn.Parameter tells PyTorch:
“This tensor is a learnable model parameter.”
Therefore it appears in:
and can be updated by the optimizer.

69. Hooks

Hooks allow you to inspect intermediate values. Example:
Run the model:
The hook executes automatically. Remove it:
Hooks are useful for:
  • Debugging
  • Inspecting activations
  • Visualizing intermediate layers
  • Model analysis

70. Profiling

When a model is slow, profiling helps identify bottlenecks. Example:
Profiling can help answer:

71. Important Tensor Shapes

Understanding tensor shapes is critical.

Tabular data

Usually:
Example:
Meaning:

Images

Usually:
Example:
Meaning:

Sequences

Often:
Example:
Meaning:

Interview tip

When debugging a PyTorch model, always print:
Shape errors are among the most common problems in deep learning.

72. Common PyTorch Errors

Shape mismatch

Example:
Check:
Make sure the input feature dimension matches the layer’s expected in_features.

CPU/GPU mismatch

Incorrect:
if X is still on CPU. Correct:

Incorrect target dtype

For CrossEntropyLoss, targets should generally be integer class indices with dtype:
You can use:

73. Debugging Checklist

When your PyTorch model fails, check:
Check for invalid values:
Check gradients:
This can help identify:

74. Overfitting

Overfitting means the model performs very well on training data but poorly on unseen data. Example:
Possible solutions:
Example:

75. Underfitting

Underfitting means the model cannot even perform well on the training data. Example:
Possible solutions:

76. Learning Rate

The learning rate determines the size of parameter updates. Conceptually:
Too high:
Too low:
Typical starting points can be:
These are only starting points. The appropriate value depends on the model, data, optimizer, and training setup.

77. Batch Size

Suppose:
Then:
Large batch sizes can provide:
but require:
Small batch sizes require less memory but can result in noisier gradients and potentially slower hardware utilization.

78. Epoch

An epoch means:
One complete pass through the training dataset.
Example:
This means the model processes the training dataset ten times.

79. Iteration

An iteration usually refers to one batch/optimizer update. For example:
gives:
For:
you get approximately:

80. state_dict

PyTorch stores model parameters in a state_dict.
You can inspect a particular parameter:
Save:
Load:

81. Inference

Inference means using a trained model to make predictions. Standard pattern:
Remember:

82. Clean PyTorch Project Structure

A real project may be organized like this:
This makes the project easier to maintain than putting everything into one huge Python file.

83. Complete PyTorch Workflow

A typical machine-learning project follows:
The most important thing is to understand what happens at every stage.

84. Complete Training Template

Here is a practical template:
The most important sequence is:

85. What You Should Memorize for Interviews

Don’t try to memorize every PyTorch function. Understand these concepts deeply.

Level 1 — Tensors

Know:
You should be able to explain:
What is a tensor and why are tensor shapes important?

Level 2 — Autograd

Know:
Understand:

Level 3 — Neural Networks

Know:
You should understand what happens inside:

Level 4 — Training

Know:
This is the core of PyTorch training.

Level 5 — Data

Know:
Understand why batching is needed.

Level 6 — Computer Vision

Know:
Understand image tensor shape:

Level 7 — Advanced Deep Learning

Know the concepts:

86. PyTorch Cheat Sheet


87. Recommended Learning Order

Don’t try to learn everything simultaneously. Follow this progression:

88. The Core PyTorch Mental Model

If you remember only one thing, remember this:
The model is essentially learning:
After thousands or millions of updates, the model ideally learns parameters that produce useful predictions.

89. The Most Important PyTorch Concepts

For practical work and interviews, prioritize these concepts:

1. Tensor

Understand:

2. Autograd

Understand:

3. nn.Module

Understand how neural networks are constructed.

4. Forward pass

5. Loss

6. Backpropagation

7. Optimizer

8. Dataset/DataLoader

Understand how data reaches the model.

9. Training vs evaluation

10. GPU

11. CNN

Understand image processing.

12. Attention/Transformer

Understand the architecture behind many modern NLP and generative-AI systems.

90. Final PyTorch Pattern to Memorize

The most important PyTorch code pattern is:
Understand what each line means:
Then evaluation:
So the complete mental model is: