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
Why learn PyTorch?
If you want to work in:- Deep Learning
- Computer Vision
- NLP
- Generative AI
- LLMs
- Research
- AI engineering
2. Importing PyTorch
The basic import is: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
Vector
Matrix
Why are tensors important?
Almost everything in a neural network is represented using tensors:4. Creating Tensors
torch.zeros()
Creates a tensor filled with zeros.
torch.ones()
torch.rand()
Creates random numbers between 0 and 1.
torch.randn()
Generates random values approximately following a standard normal distribution.
torch.randint()
Creates random integers.
torch.arange()
Creates a sequence.
5. Tensor Data Types
Every tensor has a data type.Why does dtype matter?
Neural networks normally perform calculations using floating-point numbers. For example: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.Number of elements
[2, 3, 4] tensor:
numel() returns 24.
7. Tensor Indexing
PyTorch indexing works similarly to NumPy.Slicing
: means “all rows”.
So this means:
8. Tensor Arithmetic
Given:9. Matrix Multiplication
Consider:Important interview question
What is the difference between:10. Useful Tensor Functions
PyTorch provides many mathematical operations.argmax()
argmax() returns the index of the largest value.
11. Reshaping Tensors
Neural networks often require data in a particular shape. Suppose:view()
Another way:
view() has stricter memory-layout requirements than reshape(), so reshape() is often the more convenient choice.
flatten()
12. unsqueeze() and squeeze()
These operations add and remove dimensions.
Suppose:
13. Concatenation and Stacking
torch.cat()
Concatenates tensors along an existing dimension.
torch.stack()
Creates a new dimension.
Difference
14. NumPy and PyTorch
PyTorch works closely with NumPy. NumPy → PyTorch:15. CPU and GPU
Deep-learning training can be much faster on GPUs. Check whether CUDA is available:Important rule
You cannot normally do:16. Autograd
One of PyTorch’s most important features is automatic differentiation. Suppose:What happened?
17. Gradient Descent
Suppose our model is:w would affect the loss.
The optimizer uses this information to update w.
18. Why zero_grad()?
PyTorch gradients accumulate by default.
For example:
19. nn.Module
Neural networks normally inherit from:
Two important methods
__init__() defines the layers.
forward() defines how data flows through the model.
20. nn.Linear
A linear layer performs:
21. Activation Functions
A neural network containing only linear operations is still effectively a linear transformation. Activation functions introduce non-linearity.ReLU
Sigmoid
BCEWithLogitsLoss directly on logits rather than explicitly applying sigmoid before the loss.
Tanh
Softmax
Softmax converts logits into a probability distribution across classes.22. Building a Neural Network
2 might represent two output classes.
23. nn.Sequential
nn.Sequential allows you to define layers in order.
Instead of:
forward() logic is usually preferable.
24. Loss Functions
A loss function measures how different the model prediction is from the target. Conceptually:MSE Loss
Mean Squared Error is commonly used for regression.Cross Entropy
Used very commonly for multi-class classification.CrossEntropyLoss.
BCEWithLogitsLoss
For binary classification: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:26. Complete Training Loop
The training loop is arguably the most important PyTorch pattern to understand.1. model.train()
- Dropout
- BatchNorm
2. Move data
3. Forward pass
4. Calculate loss
5. Clear old gradients
6. Backpropagation
7. Update parameters
27. Dataset
A Dataset defines how your data is accessed.__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.Why use DataLoader?
Instead of processing: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:30. Evaluation
During evaluation:- Memory
- Computation
- Time
31. Classification Accuracy
Example:32. model.train() vs model.eval()
This distinction is extremely important.
Training:
33. Dropout
Dropout is a regularization technique. It randomly disables some activations during training.Why use Dropout?
It can reduce overfitting. Without regularization:34. Batch Normalization
Batch normalization normalizes activations using batch statistics during training. Example:model.eval() matters.
35. Weight Initialization
Neural-network layers receive default parameter initialization from PyTorch. You can customize it. Xavier initialization:36. CNN — Convolutional Neural Network
CNNs are designed particularly for spatial data such as images. Typical architecture:37. Conv2d
Example:
38. Pooling
Max pooling reduces spatial dimensions.39. Complete CNN
2×2 pooling operations:
40. Image Dataset with Torchvision
PyTorch provides datasets throughtorchvision.
Example using MNIST:
41. Image Transformations
Transforms preprocess and augment images. Convert image to tensor:Why augmentation?
Instead of showing the model exactly the same images repeatedly, we create slightly modified versions. Examples: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:Freezing the pretrained layers
43. RNN
RNN stands for Recurrent Neural Network. RNNs process sequential information. Examples:44. LSTM
LSTM means Long Short-Term Memory. It was designed to better preserve useful information over longer sequences than a basic RNN.45. GRU
GRU means Gated Recurrent Unit. It is another recurrent architecture.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:47. Attention
Attention answers a basic question:“Which other pieces of information should this token pay attention to?”The mathematical form is:
48. Embeddings
Neural networks cannot directly understand words such as:49. Simple NLP Model
50. Model Parameters
Every neural network contains parameters such as weights and biases. View them:51. Saving a Model
The recommended approach is usually to save the model’sstate_dict.
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.53. Learning Rate Scheduler
A learning-rate scheduler changes the learning rate during training. Example:54. Early Stopping
Sometimes validation performance stops improving. Instead of continuing forever, we can stop training. Concept: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
56. Gradient Clipping
Sometimes gradients become extremely large. This is called exploding gradients. Gradient clipping limits their magnitude.57. Freezing Parameters
Sometimes you don’t want to train every layer.58. torch.no_grad()
For inference:
no_grad() tells autograd that gradients are not needed.
Benefits:
eval() changes model behavior.
no_grad() disables gradient tracking.
You commonly use both during inference.
59. detach()
Suppose:
detach() creates a tensor that is disconnected from the current computation graph.
For example:
60. Random Seeds
For reproducibility:- GPU hardware
- CUDA version
- Backend algorithms
- Parallelism
- Other libraries
61. Classification Example
62. Regression Example
Regression predicts continuous values. Suppose:63. Binary Classification
For binary classification, the model can produce one logit per sample.64. Multi-Class Classification
Suppose the classes are:65. Autoencoder
An autoencoder learns to reconstruct its input. Architecture:66. GAN Basics
GAN means Generative Adversarial Network. It contains two networks:67. Custom Loss Function
You can create your own loss.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:
69. Hooks
Hooks allow you to inspect intermediate values. Example:- Debugging
- Inspecting activations
- Visualizing intermediate layers
- Model analysis
70. Profiling
When a model is slow, profiling helps identify bottlenecks. Example:71. Important Tensor Shapes
Understanding tensor shapes is critical.Tabular data
Usually:Images
Usually:Sequences
Often:Interview tip
When debugging a PyTorch model, always print:72. Common PyTorch Errors
Shape mismatch
Example:in_features.
CPU/GPU mismatch
Incorrect:X is still on CPU.
Correct:
Incorrect target dtype
ForCrossEntropyLoss, targets should generally be integer class indices with dtype:
73. Debugging Checklist
When your PyTorch model fails, check:74. Overfitting
Overfitting means the model performs very well on training data but poorly on unseen data. Example:75. Underfitting
Underfitting means the model cannot even perform well on the training data. Example:76. Learning Rate
The learning rate determines the size of parameter updates. Conceptually:77. Batch Size
Suppose:78. Epoch
An epoch means:One complete pass through the training dataset.Example:
79. Iteration
An iteration usually refers to one batch/optimizer update. For example:80. state_dict
PyTorch stores model parameters in a state_dict.
81. Inference
Inference means using a trained model to make predictions. Standard pattern:82. Clean PyTorch Project Structure
A real project may be organized like this:83. Complete PyTorch Workflow
A typical machine-learning project follows:84. Complete Training Template
Here is a practical template:85. What You Should Memorize for Interviews
Don’t try to memorize every PyTorch function. Understand these concepts deeply.Level 1 — Tensors
Know:What is a tensor and why are tensor shapes important?