Model Training, Saving, and Loading in PyTorch

अब हम PyTorch में Model Training, फिर उसे Save और Load करने की पूरी प्रक्रिया विस्तार से सीखते हैं —
जो किसी भी Deep Learning project का core हिस्सा है।


🔷 1. 🔁 Model Training in PyTorch

🧱 Training Steps Overview:

  1. Model बनाना (nn.Module)
  2. Loss function चुनना (nn.CrossEntropyLoss, etc.)
  3. Optimizer सेट करना (torch.optim)
  4. Forward pass करना
  5. Loss calculate करना
  6. Backward pass (loss.backward())
  7. Optimizer step (optimizer.step())

🧪 Full Example (Classifier):

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# Sample data
X = torch.tensor([[0.,0.],[0.,1.],[1.,0.],[1.,1.]])
y = torch.tensor([[0.],[1.],[1.],[0.]])

dataset = TensorDataset(X, y)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True)

# Step 1: Model
class XORNet(nn.Module):
def __init__(self):
super(XORNet, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)

def forward(self, x):
x = torch.relu(self.fc1(x))
return torch.sigmoid(self.fc2(x))

model = XORNet()

# Step 2: Loss and Optimizer
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=0.1)

# Step 3: Training loop
for epoch in range(500):
for xb, yb in dataloader:
y_pred = model(xb)
loss = criterion(y_pred, yb)

optimizer.zero_grad()
loss.backward()
optimizer.step()

if epoch % 100 == 0:
print(f"Epoch {epoch}, Loss: {loss.item():.4f}")

🔷 2. 💾 Saving a PyTorch Model

PyTorch में 2 तरीके हैं model save करने के:

✅ Option 1: State Dict Only (Recommended)

torch.save(model.state_dict(), "xor_model.pth")

यह केवल model के weights save करता है, architecture नहीं।


✅ Option 2: Complete Model (Not Recommended)

torch.save(model, "xor_model_full.pth")

यह पूरा model + structure save करता है, पर version compatibility issues आ सकते हैं।


🔷 3. 📂 Loading a Model

🔁 Load from State Dict (Best Practice):

model = XORNet()  # पहले architecture बनाओ
model.load_state_dict(torch.load("xor_model.pth"))
model.eval() # evaluation mode में डालना ज़रूरी

🔍 .eval() inference के समय BatchNorm / Dropout को deactivate करता है।


🧠 Bonus: GPU Compatibility (Saving/Loading)

✅ Save on GPU, Load on CPU:

# Save (from GPU)
torch.save(model.state_dict(), "model_gpu.pth")

# Load on CPU
device = torch.device("cpu")
model.load_state_dict(torch.load("model_gpu.pth", map_location=device))

🧪 Example: Inference After Loading

model.eval()
with torch.no_grad():
test = torch.tensor([[1., 1.]])
output = model(test)
print("Predicted:", output.item())

📦 Advanced Tip: Save Optimizer State Too

torch.save({
'model_state': model.state_dict(),
'optimizer_state': optimizer.state_dict(),
}, "checkpoint.pth")

Load Later:

checkpoint = torch.load("checkpoint.pth")
model.load_state_dict(checkpoint['model_state'])
optimizer.load_state_dict(checkpoint['optimizer_state'])

🧠 Evaluation Tips

  • हमेशा model.eval() use करें inference के लिए
  • torch.no_grad() में prediction करें (memory efficiency के लिए)
  • Large models के लिए model checkpoints का उपयोग करें

📝 Practice Questions:

  1. PyTorch में model train करने के मुख्य steps क्या हैं?
  2. State dict और full model saving में क्या अंतर है?
  3. Optimizer state क्यों save करना चाहिए?
  4. .eval() और .train() modes में क्या फर्क है?
  5. Inference में torch.no_grad() का उपयोग क्यों करें?

🧠 Summary Table

TaskMethod
🔧 TrainForward → Loss → Backward → Optimizer
💾 Save Weightstorch.save(model.state_dict(), path)
📂 Load Weightsmodel.load_state_dict(torch.load(path))
📌 Inferencemodel.eval() + with torch.no_grad()
🔁 Save with OptimizerUse checkpoint = {'model': ..., 'opt': ...}

Introduction of PyTorch – Complete Beginner Guide with Examples

Introduction of PyTorch

अगर आप Machine Learning, Deep Learning, Computer Vision, Natural Language Processing या Artificial Intelligence सीखना शुरू कर रहे हैं, तो आपने PyTorch का नाम जरूर सुना होगा।

PyTorch एक powerful framework है जिसकी help से हम tensors पर mathematical operations कर सकते हैं, neural networks बना सकते हैं, models को train कर सकते हैं और CPU या GPU पर computations perform कर सकते हैं। Official PyTorch documentation इसे CPU और GPU दोनों के लिए optimized tensor library के रूप में describe करती है।

Simple language में कहें तो:

PyTorch Python की help से Deep Learning models बनाने और train करने का एक framework है।

Suppose हमें images देखकर यह पता करना है कि image में cat है या dog। इसके लिए हमें image data load करना होगा, उसे numbers में convert करना होगा, neural network बनाना होगा, model को examples दिखाकर train करना होगा और फिर new image पर prediction करनी होगी।

PyTorch इन सभी steps को handle करने के लिए useful tools provide करता है।

इस chapter में हम PyTorch को बिल्कुल basic level से समझेंगे। हमारा focus केवल code याद करने पर नहीं होगा। हम यह भी समझेंगे कि Tensor क्या है, GPU क्यों use होता है, gradient क्या करता है, model कैसे learn करता है और training loop के अंदर वास्तव में क्या होता है।


What is PyTorch?

PyTorch एक Python-based open-source framework है जिसका main use tensor computation और deep neural networks बनाने में होता है। इसके important components में tensor library, automatic differentiation system, neural-network modules, optimizers और data-loading utilities शामिल हैं।

PyTorch में Deep Learning model बनाने का basic flow इस तरह समझ सकते हैं:

Data → Tensor → Model → Prediction → Loss → Gradient → Weight Update → Better Prediction

यही पूरा Deep Learning का basic cycle है।

मान लीजिए हमारे पास students का data है:

Study HoursAttendanceResult
255%Fail
465%Pass
680%Pass
890%Pass

हम चाहते हैं कि computer पुराने data को देखकर new student के result का prediction करे।

PyTorch की help से हम इस data को tensors में convert करेंगे, model बनाएंगे, prediction करेंगे, prediction की error calculate करेंगे और model के parameters update करेंगे।

बार-बार यही process होने पर model धीरे-धीरे data से pattern learn करता है।


Why Do We Need PyTorch?

Theoretically neural network को केवल Python और mathematics की help से भी बनाया जा सकता है।

Suppose हमारे पास एक simple neuron है: y=wx+b

यहां x input है, w weight है, b bias है और y output है।

एक छोटे model के लिए calculations manually लिखना possible है। लेकिन modern neural networks में लाखों या कभी-कभी बहुत बड़ी संख्या में parameters हो सकते हैं। ऐसे models में matrices, gradients, optimization, batching और hardware acceleration manually manage करना practical नहीं होता।

PyTorch इस complexity को आसान बनाता है।

उदाहरण के लिए matrix multiplication:

import torch

A = torch.tensor([[1, 2],
                  [3, 4]])

B = torch.tensor([[5, 6],
                  [7, 8]])

C = torch.matmul(A, B)

print(C)

PyTorch required tensor operation perform कर देता है और यही type की operations neural networks के अंदर बहुत बड़ी scale पर होती हैं।


Main Features of PyTorch

PyTorch का core tensor computation पर आधारित है और इसके साथ torch.autograd, torch.nn, torch.optim, Dataset और DataLoader जैसे components मिलते हैं। torch.autograd gradient calculation automate करता है, torch.nn.Module neural-network models का base class है और torch.optim model parameters update करने वाले optimizers provide करता है।

Beginner के लिए PyTorch को इन major parts में समझना सबसे useful है:

PyTorch ComponentMain Work
torch.TensorData को numerical form में store करना
torch.autogradGradients automatically calculate करना
torch.nnNeural network layers और models बनाना
torch.optimModel weights update करना
DatasetIndividual data samples manage करना
DataLoaderData को batches में model तक पहुंचाना
torch.save()Model/tensors save करना
torch.load()Saved information load करना

Official documentation के अनुसार DataLoader dataset पर Python iterable provide करता है और batching, loading order तथा single या multi-process data loading जैसी capabilities support करता है।


Installing PyTorch

सबसे पहले Python system में installed होना चाहिए।

Basic pip environment में PyTorch install करने के लिए commonly यह command use की जाती है:

pip install torch torchvision torchaudio

लेकिन GPU/CUDA support hardware और environment के अनुसार अलग हो सकता है, इसलिए GPU-based installation के लिए official PyTorch installation selector के अनुसार command choose करना better है।

Installation check करने के लिए:

import torch

print(torch.__version__)

अगर version print हो जाता है, तो PyTorch successfully import हो रहा है।


Your First PyTorch Program

सबसे simple program:

import torch

x = torch.tensor([10, 20, 30, 40])

print(x)

Output लगभग इस प्रकार होगा:

tensor([10, 20, 30, 40])

यहां:

import torch

PyTorch library import करता है।

और:

torch.tensor(...)

Python values को PyTorch Tensor में convert करता है।

अब सबसे important question आता है:

Tensor आखिर है क्या?


What is a Tensor in PyTorch?

Tensor PyTorch का सबसे basic और important concept है।

Easy language में:

Tensor numbers को organized form में store करने वाला multidimensional data structure है।

अगर आपने Mathematics में scalar, vector और matrix पढ़ा है तो Tensor को समझना बहुत आसान है।

DimensionExampleसामान्य नाम
0D5Scalar
1D[1,2,3]Vector
2D[[1,2],[3,4]]Matrix
3D+Multiple matricesHigher-dimensional Tensor

उदाहरण:

import torch

a = torch.tensor(5)

b = torch.tensor([1, 2, 3])

c = torch.tensor([
    [1, 2],
    [3, 4]
])

print(a)
print(b)
print(c)

Why Are Tensors Important?

Computer directly image को वैसे नहीं देखता जैसे human देखता है।

Suppose एक RGB image की size है:

224 × 224

हर pixel में Red, Green और Blue information होती है।

Deep Learning में ऐसी image को numerical tensor के रूप में represent किया जा सकता है, जैसे:

3 × 224 × 224

जहां 3 RGB channels को show कर सकता है।

इसी तरह text, audio और tabular data को भी suitable numerical representation में convert करके tensors के माध्यम से process किया जा सकता है।

इसलिए Deep Learning का बड़ा हिस्सा अंत में tensor operations पर आ जाता है।


Creating Tensors

PyTorch में tensors कई तरीकों से create किए जा सकते हैं।

Tensor from values

import torch

x = torch.tensor([1, 2, 3, 4])

print(x)

Tensor filled with zeros

x = torch.zeros(3, 3)

print(x)

Output:

tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

Tensor filled with ones

x = torch.ones(2, 3)

print(x)

Random Tensor

x = torch.rand(2, 3)

print(x)

Random tensors Deep Learning में बहुत useful हैं। उदाहरण के लिए neural network parameters को शुरुआत में random values से initialize किया जा सकता है।


Tensor Shape

Tensor का shape हमें बताता है कि tensor में कितनी dimensions हैं और हर dimension की size क्या है।

import torch

x = torch.tensor([
    [1, 2, 3],
    [4, 5, 6]
])

print(x.shape)

Output:

torch.Size([2, 3])

इसका मतलब tensor में:

2 Rows
3 Columns

हैं।

Deep Learning में shape समझना बहुत important है क्योंकि बहुत common errors tensor shape mismatch के कारण आते हैं।


Tensor Data Type

Tensor के अंदर अलग-अलग types का data हो सकता है।

import torch

x = torch.tensor([1.5, 2.5, 3.5])

print(x.dtype)

Possible output:

torch.float32

Machine Learning models में floating-point tensors बहुत commonly use होते हैं।

हम manually datatype भी define कर सकते हैं:

x = torch.tensor([1, 2, 3], dtype=torch.float32)

print(x)

Basic Tensor Operations

PyTorch में tensor पर normal mathematical operations आसानी से perform किए जा सकते हैं।

import torch

a = torch.tensor([10, 20, 30])
b = torch.tensor([1, 2, 3])

print(a + b)
print(a - b)
print(a * b)
print(a / b)

यहां * element-wise multiplication करता है।

Matrix multiplication के लिए:

A = torch.tensor([[1., 2.],
                  [3., 4.]])

B = torch.tensor([[5., 6.],
                  [7., 8.]])

C = torch.matmul(A, B)

print(C)

Neural networks के अंदर इसी type की matrix operations बार-बार होती हैं।


CPU and GPU in PyTorch

Deep Learning models में बहुत large mathematical calculations होती हैं। GPU many numerical operations को parallel तरीके से execute करने में useful हो सकता है, और PyTorch tensors GPU hardware पर computation के लिए move किए जा सकते हैं. PyTorch का tensor system GPU acceleration support करता है।

Available CUDA GPU check करने के लिए commonly:

import torch

print(torch.cuda.is_available())

हम device select कर सकते हैं:

device = torch.device(
    "cuda" if torch.cuda.is_available() else "cpu"
)

print(device)

Tensor को selected device पर भेज सकते हैं:

x = torch.tensor([1., 2., 3.])

x = x.to(device)

print(x)

अगर CUDA GPU available है तो tensor GPU पर जा सकता है, otherwise CPU पर रहेगा।

Model को भी similarly device पर भेजा जाता है:

model = model.to(device)

Important point यह है कि operation में use होने वाले model और tensors compatible device पर होने चाहिए।


What is Autograd?

अब PyTorch का एक बहुत important concept आता है:

torch.autograd

Neural network को train करने के लिए हमें यह जानना होता है कि model की error को कम करने के लिए weights को किस direction में change करना चाहिए।

इसके लिए gradients calculate किए जाते हैं।

PyTorch में torch.autograd automatic differentiation engine है जो computational graph से gradients calculate कर सकता है। Official PyTorch tutorial के अनुसार backpropagation के दौरान gradients के आधार पर model parameters adjust किए जाते हैं।

Simple example:

import torch

x = torch.tensor(2.0, requires_grad=True)

y = x ** 2

y.backward()

print(x.grad)

यहां:

y = x²

तो derivative:

dy/dx = 2x

और x = 2 पर gradient:

4

मिलेगा।

PyTorch ने यह derivative manually लिखवाए बिना calculate कर दिया।

यही feature बड़े neural networks को train करने में extremely useful है।


What Does requires_grad=True Mean?

जब हम लिखते हैं:

x = torch.tensor(2.0, requires_grad=True)

तो हम PyTorch को बताते हैं कि इस tensor पर होने वाले operations का gradient track करना है।

Official documentation के अनुसार requires_grad_() autograd को tensor operations record करना शुरू करने के लिए use किया जा सकता है।

Deep Learning में model weights के gradients needed होते हैं ताकि optimizer उन्हें update कर सके।


What is a Neural Network?

Neural Network एक mathematical model है जो input data से patterns learn करने की कोशिश करता है।

Simple neuron को ऐसे imagine करें:

Input
  ↓
Weight
  ↓
Weighted Calculation
  ↓
Bias
  ↓
Activation
  ↓
Output

Basic equation: y=wx+b

जहां:

x = Input
w = Weight
b = Bias
y = Output

जब multiple neurons और layers combine होते हैं, neural network बनता है।


torch.nn in PyTorch

PyTorch में neural networks बनाने के लिए torch.nn package दिया गया है। torch.nn.Module सभी neural-network modules का base class है और custom models generally इसी से subclass किए जाते हैं।

Example:

import torch
import torch.nn as nn

class SimpleModel(nn.Module):

    def __init__(self):
        super().__init__()

        self.layer = nn.Linear(2, 1)

    def forward(self, x):
        return self.layer(x)

Model create करें:

model = SimpleModel()

print(model)

Understanding nn.Linear

Suppose:

nn.Linear(2, 1)

इसका meaning है:

2 Input Features
       ↓
Linear Layer
       ↓
1 Output

अगर हमारे student example में inputs हैं:

Study Hours
Attendance

तो 2 input features होंगे।

Output:

Predicted Score

एक value हो सकती है।

Linear layer internally weights और bias use करती है।


What is the Forward Method?

हर PyTorch model में commonly:

def forward(self, x):

define किया जाता है।

यह बताता है कि input model के अंदर किस path से जाएगा।

Example:

def forward(self, x):

    x = self.layer1(x)

    x = self.relu(x)

    x = self.layer2(x)

    return x

Flow:

Input
 ↓
Layer 1
 ↓
ReLU
 ↓
Layer 2
 ↓
Output

इस process को forward pass कहा जाता है।


Dataset and DataLoader

Real Deep Learning project में data बहुत बड़ा हो सकता है।

मान लीजिए हमारे पास:

100,000 images

हैं।

सभी images को एक साथ memory में load करना हमेशा practical नहीं होता।

PyTorch इस problem को handle करने के लिए Dataset और DataLoader abstractions provide करता है। Official tutorial के अनुसार Dataset individual samples access/processing करता है, जबकि DataLoader samples को collect करके batches में training loop तक पहुंचाता है।

Simple concept:

Complete Dataset
      ↓
DataLoader
      ↓
Batch 1
Batch 2
Batch 3
...
      ↓
Model

Example:

from torch.utils.data import TensorDataset, DataLoader
import torch

X = torch.tensor([
    [1., 2.],
    [2., 3.],
    [3., 4.],
    [4., 5.]
])

y = torch.tensor([
    [1.],
    [2.],
    [3.],
    [4.]
])

dataset = TensorDataset(X, y)

loader = DataLoader(
    dataset,
    batch_size=2,
    shuffle=True
)

अब training के समय:

for inputs, targets in loader:

    print(inputs)
    print(targets)

Data batches में मिलेगा।


What is Batch Size?

Suppose dataset में:

1000 samples

हैं।

अगर:

batch_size = 100

तो roughly 10 batches बनेंगे।

एक batch:

100 samples

model को एक साथ देगा।

Batching training को manageable बनाती है और hardware resources effectively use करने में help कर सकती है।


What is Loss Function?

Model पहली बार correct prediction नहीं करता।

Suppose:

Actual Value = 10
Prediction   = 6

तो prediction गलत है।

लेकिन computer को कैसे पता चलेगा कि prediction कितना गलत है?

यह काम Loss Function करती है।

Loss एक numerical value देती है जो model prediction और target के difference को represent करती है।

Regression में example:

criterion = nn.MSELoss()

Classification में problem के अनुसार दूसरे loss functions use किए जाते हैं।

Concept:

Prediction
    +
Actual Target
    ↓
Loss Function
    ↓
Error

Training का main objective generally इसी loss को reduce करना होता है।


What is an Optimizer?

Gradient calculate हो जाने के बाद model weights automatically खुद नहीं बदलते।

Weights update करने के लिए optimizer use किया जाता है।

PyTorch का torch.optim package optimizers provide करता है जो model parameters का state रखकर उन्हें calculated optimization rule के अनुसार update करते हैं।

Example:

optimizer = torch.optim.Adam(
    model.parameters(),
    lr=0.001
)

यहां:

Adam = Optimizer
lr = Learning Rate

Learning rate decide करती है कि एक update में parameters कितने change होंगे।


Complete Training Process in PyTorch

अब PyTorch का सबसे important concept समझते हैं।

Training loop generally इस flow को follow करता है:

Data
 ↓
Model
 ↓
Prediction
 ↓
Loss
 ↓
Backward Pass
 ↓
Gradient
 ↓
Optimizer
 ↓
Weight Update
 ↓
Next Batch

Official PyTorch training tutorial भी Dataset/DataLoader, loss function, optimizer और training loop को model training के मुख्य building blocks के रूप में explain करता है।

Basic code:

for epoch in range(100):

    for inputs, targets in loader:

        optimizer.zero_grad()

        predictions = model(inputs)

        loss = criterion(predictions, targets)

        loss.backward()

        optimizer.step()

अब इसे line-by-line समझते हैं।


Step 1: optimizer.zero_grad()

optimizer.zero_grad()

Previous gradient values clear करता है ताकि current training step के gradients clean तरीके से calculate किए जा सकें।


Step 2: Forward Pass

predictions = model(inputs)

Input model में जाता है और prediction मिलता है।

Example:

Input = 5 hours study
Model Prediction = 70 Marks

Step 3: Calculate Loss

loss = criterion(predictions, targets)

Prediction को actual value से compare किया जाता है।

Example:

Prediction = 70
Actual     = 80

Loss function difference को numerical form में represent करती है।


Step 4: Backward Pass

loss.backward()

यह gradients calculate करता है।

Conceptually model पूछ रहा है:

कौन-से weights prediction की error के लिए responsible हैं और उन्हें किस direction में change करना चाहिए?

Autograd इस gradient calculation को automatically handle करता है।


Step 5: Update Weights

optimizer.step()

Optimizer calculated gradients के basis पर model parameters update करता है।

फिर अगला batch आता है और यही process repeat होता है।


What is an Epoch?

Suppose training dataset में:

10,000 images

हैं।

जब model सभी 10,000 training images को एक बार process कर लेता है, इसे generally:

1 Epoch

कहा जाता है।

अगर:

epochs = 20

तो model complete training dataset को 20 passes तक process करेगा।

लेकिन ज्यादा epochs का मतलब हमेशा better model नहीं होता। कुछ point के बाद model training data पर overfit भी कर सकता है।


Simple Complete PyTorch Example

अब एक छोटा model देखते हैं:

import torch
import torch.nn as nn
import torch.optim as optim

X = torch.tensor([
    [1.0],
    [2.0],
    [3.0],
    [4.0]
])

y = torch.tensor([
    [2.0],
    [4.0],
    [6.0],
    [8.0]
])

model = nn.Linear(1, 1)

criterion = nn.MSELoss()

optimizer = optim.SGD(
    model.parameters(),
    lr=0.01
)

for epoch in range(1000):

    prediction = model(X)

    loss = criterion(prediction, y)

    optimizer.zero_grad()

    loss.backward()

    optimizer.step()

print(model(torch.tensor([[5.0]])))

यहां training data roughly relation follow कर रहा है:

y = 2x

Examples:

1 → 2
2 → 4
3 → 6
4 → 8

Model training के बाद 5 के लिए value approximately 10 के आसपास learn करने की कोशिश करेगा।

यह बहुत छोटा example है, लेकिन Deep Learning की basic learning philosophy इसी से शुरू होती है।


PyTorch Model Training को आसान तरीके से समझें

मान लीजिए कोई student पहली बार maths question solve करता है।

Teacher कहता है:

Your Answer = 50
Correct Answer = 80

Student अपनी mistake देखता है और अगली बार method improve करता है।

Deep Learning model के साथ similar conceptual cycle होता है:

Student LearningNeural Network
QuestionInput
Student AnswerPrediction
Correct AnswerTarget
MistakeLoss
Mistake AnalysisGradient
LearningWeight Update
Repeated PracticeEpochs

इस analogy से training process बहुत आसानी से समझ आता है।


Training Mode and Evaluation Mode

Model training और testing के समय कुछ layers अलग behaviour कर सकती हैं।

Training के समय:

model.train()

Evaluation के समय:

model.eval()

Inference में gradient calculation की जरूरत न हो तो commonly:

with torch.no_grad():

    prediction = model(x)

use किया जाता है।


Saving a PyTorch Model

Model train करने में काफी time लग सकता है। इसलिए trained model को save किया जाता है।

PyTorch torch.save() serialization provide करता है और .pt extension commonly tensors/model-related files के लिए use की जाती है।

Example:

torch.save(
    model.state_dict(),
    "model.pth"
)

यह model parameters save करता है।


Loading a Model

Model load करने के लिए:

model = SimpleModel()

model.load_state_dict(
    torch.load("model.pth")
)

model.eval()

PyTorch की loading utilities saved tensors और model state restore करने के लिए use की जाती हैं; device mapping भी load के समय control की जा सकती है।

इसका फायदा यह है कि model को बार-बार train करने की जरूरत नहीं होती।


PyTorch and NumPy

NumPy और PyTorch दोनों multidimensional numerical arrays के साथ काम कर सकते हैं।

Beginner level पर difference इस तरह समझ सकते हैं:

FeatureNumPyPyTorch
Numerical ArraysYesYes
Tensor OperationsArray-basedTensor-based
Automatic GradientMain feature नहींYes
Neural Network ToolsBuilt-in DL framework नहींYes
GPU-oriented DL workflowLimited/general external setupPyTorch का core use case
Deep LearningAdditional libraries चाहिएBuilt-in ecosystem

PyTorch project खुद tensor computation को NumPy-like functionality और strong GPU acceleration के साथ describe करता है।

अगर आपने NumPy पहले सीखा है, तो PyTorch tensors समझना relatively आसान हो सकता है।


Where is PyTorch Used?

PyTorch का ecosystem computer vision, NLP और other deep-learning applications के लिए libraries और tools provide करता है। Official project site distributed training और broader ecosystem support को भी highlight करती है।

Practical projects में PyTorch का use image classification, object detection, image captioning, segmentation, text classification, language models, medical image analysis, regression, generative models और research prototypes जैसे tasks में किया जा सकता है।

उदाहरण के लिए image classification system का flow:

Image
 ↓
Preprocessing
 ↓
Tensor
 ↓
CNN / Vision Model
 ↓
Features
 ↓
Classifier
 ↓
Cat / Dog

Text application का basic flow:

Sentence
 ↓
Tokenization
 ↓
Numerical Representation
 ↓
Neural Network
 ↓
Prediction

PyTorch for Computer Vision

Computer Vision में images को tensors की form में process किया जाता है।

Suppose हमारे पास RGB image है।

Conceptually:

Image
 ↓
Resize
 ↓
Convert to Tensor
 ↓
Normalization
 ↓
CNN / ViT
 ↓
Prediction

PyTorch ecosystem में image-oriented workflows के लिए torchvision जैसे tools commonly use किए जाते हैं।

Deep Learning based computer vision में PyTorch इसलिए useful है क्योंकि tensor operations, neural-network modules, gradients और GPU computations एक integrated workflow में मिल जाते हैं।


PyTorch for Deep Learning Research

Research में कई बार हमें existing architecture को modify करना पड़ता है।

Suppose standard neural network में researcher नया attention block add करना चाहता है।

PyTorch में custom classes create करके model architecture define किया जा सकता है:

class MyModel(nn.Module):

    def __init__(self):
        super().__init__()

        # custom layers

    def forward(self, x):

        # custom processing

        return x

nn.Module modules को nested structure में organize करने की ability देता है, इसलिए complex models multiple reusable components में build किए जा सकते हैं।

यही flexibility research-oriented model development में काफी useful होती है।


Important PyTorch Terms for Beginners

इन terms को clear रखना PyTorch सीखने में बहुत help करेगा:

TermEasy Meaning
TensorNumerical data container
ShapeTensor का size/structure
DeviceCPU या GPU
ModelPattern learn करने वाला system
LayerModel का एक processing block
ParameterModel द्वारा learn होने वाली value
WeightInput की importance control करने वाला parameter
BiasAdditional learnable value
Forward PassInput से output prediction बनाना
LossPrediction की error
GradientParameter change की direction/amount की information
BackpropagationGradient calculation process
OptimizerParameters update करने वाला algorithm
Learning RateUpdate step की size
BatchData का छोटा group
EpochComplete training dataset पर एक full pass
DatasetTraining/testing data collection
DataLoaderDataset को batches में supply करना
InferenceTrained model से prediction करना

Beginner Learning Path for PyTorch

PyTorch सीखते समय directly complex CNN, Transformer या LLM से start करना confusion create कर सकता है।

Better learning order इस प्रकार रखें:

Python Basics
      ↓
NumPy Basics
      ↓
Basic Mathematics
      ↓
PyTorch Tensor
      ↓
Tensor Operations
      ↓
CPU / GPU
      ↓
Autograd
      ↓
nn.Module
      ↓
Loss Function
      ↓
Optimizer
      ↓
Dataset & DataLoader
      ↓
Training Loop
      ↓
Simple Neural Network
      ↓
CNN
      ↓
Advanced Models

यह sequence follow करने पर आपको केवल PyTorch code नहीं बल्कि उसके पीछे का logic भी समझ आएगा।


Common Mistakes Beginners Make in PyTorch

PyTorch सीखते समय कुछ errors बहुत common हैं।

Shape Mismatch

Expected Shape ≠ Input Shape

Neural network layer को सही input dimensions देना जरूरी है।

CPU-GPU Device Mismatch

Model GPU पर और input CPU पर होने पर operation fail हो सकता है।

इसलिए:

model = model.to(device)
x = x.to(device)

जैसी consistency रखना useful है।

Wrong Data Type

कुछ operations specific datatype expect कर सकते हैं। Classification targets और model inputs के datatype requirements अलग हो सकते हैं।

Forgetting zero_grad()

Training loop में gradient management समझना जरूरी है।

Using Wrong Loss Function

Regression और classification problems के लिए loss function अलग हो सकती है।

Training Without Validation

सिर्फ training loss देखकर model की quality decide नहीं करनी चाहिए। Unseen validation/test data पर performance भी check करनी चाहिए।


Advantages of Learning PyTorch

PyTorch सीखने का सबसे बड़ा फायदा यह है कि यह आपको Deep Learning के major concepts practically समझने देता है।

जब आप manually training loop लिखते हैं, तो आपको clearly दिखाई देता है:

Input कहां गया?
Prediction कैसे आया?
Loss कैसे calculate हुआ?
Gradient कब बना?
Optimizer ने weights कब बदले?

इससे Deep Learning black box जैसा नहीं लगता।

PyTorch में low-level tensor operations से लेकर high-level neural-network components तक एक ही ecosystem में available हैं। Official documentation torch.Tensor, autograd, neural-network modules, optimizers और data utilities को core building blocks के रूप में expose करती है।


A Simple Real-Life Example

Suppose हम एक system बनाना चाहते हैं जो house price predict करे।

Inputs:

Area
Number of Rooms
Age of House
Location Score

Target:

House Price

PyTorch workflow:

House Data
    ↓
Convert to Tensor
    ↓
Dataset
    ↓
DataLoader
    ↓
Neural Network
    ↓
Predicted Price
    ↓
Compare with Actual Price
    ↓
Calculate Loss
    ↓
Backpropagation
    ↓
Optimizer Updates Weights
    ↓
Repeat Training

Training के बाद:

New House Details
       ↓
Trained Model
       ↓
Predicted Price

यही basic pattern image classification, disease prediction, text classification और कई दूसरे Machine Learning applications में अलग-अलग models के साथ दिखाई देता है।


Frequently Asked Questions About PyTorch

What is PyTorch in simple words?

PyTorch एक Deep Learning framework है जो tensors, neural networks, automatic gradients और model training के लिए tools provide करता है।

Is PyTorch only for Deep Learning?

PyTorch का major use Deep Learning में होता है, लेकिन इसकी tensor library general numerical computations के लिए भी useful है।

What is Tensor in PyTorch?

Tensor numerical data को multidimensional form में represent करता है। Deep Learning operations largely tensors पर perform होते हैं।

Can PyTorch use GPU?

हाँ। PyTorch tensor computation GPU hardware पर run कर सकता है जब compatible hardware/software environment available हो।

What is Autograd?

Autograd PyTorch का automatic differentiation system है जो computational graph के आधार पर gradients calculate करता है।

What is nn.Module?

torch.nn.Module PyTorch neural-network modules का base class है। Custom models generally इसे subclass करके बनाए जाते हैं।

What is DataLoader?

DataLoader dataset से samples लेकर उन्हें batches के रूप में training loop तक पहुंचाता है और batching तथा data-loading options provide करता है।

What is an optimizer?

Optimizer gradients के basis पर model parameters update करने के लिए use किया जाता है। PyTorch में optimizers torch.optim package के through available हैं।

Is Python required for PyTorch?

Beginner-level PyTorch learning और सामान्य PyTorch workflows के लिए Python knowledge बहुत important है, क्योंकि PyTorch का widely used interface Python-based है।

Should I learn NumPy before PyTorch?

Compulsory नहीं है, लेकिन NumPy का basic knowledge arrays, dimensions, indexing और matrix operations समझने में काफी help करता है।


Conclusion

PyTorch को समझने का सबसे आसान तरीका केवल commands याद करना नहीं है। उसके पूरे learning process को समझना ज्यादा important है।

सबसे पहले data को Tensor में represent किया जाता है। Tensor model में जाता है और model prediction produce करता है। Prediction को actual target से compare करके Loss calculate होती है। इसके बाद autograd gradients calculate करता है और Optimizer model parameters update करता है। यह process कई batches और epochs तक repeat होती है। PyTorch के official training materials भी Dataset/DataLoader, model, loss, autograd और optimizer को इसी training workflow के core parts के रूप में explain करते हैं।

पूरे PyTorch को एक line में याद रखना हो तो:

PyTorch = Tensors + Neural Network + Automatic Gradient + Optimization + Data Handling

और Deep Learning training को:

Data → Model → Prediction → Loss → Gradient → Weight Update → Repeat

अगर यह basic cycle अच्छी तरह समझ आ गई, तो आगे ANN, CNN, RNN, LSTM, Transformer, Computer Vision और advanced Deep Learning models समझना काफी आसान हो जाता है।

TensorFlow and Keras Basics

अब जब आपने Deep Learning के theory और models (जैसे CNN, RNN, BERT) अच्छे से समझ लिए हैं —
तो अगला practical step है:
⚙️ TensorFlow और Keras के साथ Deep Learning models बनाना सीखना।


🔷 1. TensorFlow क्या है?

TensorFlow एक open-source deep learning framework है जिसे Google ने बनाया है।
यह numerical computation और large-scale machine learning models के लिए design किया गया है।

🧠 TensorFlow का नाम “Tensor” (data structure) + “Flow” (computation graph) से आया है।


✅ Key Features:

FeatureDetail
📊 Automatic DifferentiationGradient calculation
🧮 GPU/TPU Supportतेज़ computation
🧠 High-level + Low-level APIsFlexibility
🔧 DeploymentAndroid, Web, Edge devices
🤝 EcosystemTF Hub, TF Lite, TF.js, TF-Serving

🔷 2. Keras क्या है?

Keras एक high-level deep learning API है, जो TensorFlow के ऊपर चलता है।
यह models को लिखना, train करना और debug करना बहुत आसान बना देता है।

🎯 “Keras = Simplicity + Productivity + Modularity”


✅ Keras क्यों चुनें?

BenefitReason
🚀 Easy to LearnPythonic syntax
🧩 ModularLayers, Optimizers, Loss अलग-अलग
🧠 PowerfulAdvanced models possible
🔧 Fast prototypingजल्दी result देखने के लिए
🔌 TF BackendTensorFlow की ताकत use करता है

🔷 3. Tensor, Model, and Layer Basics

🔹 Tensor:

Multidimensional array (जैसे NumPy array, लेकिन GPU-compatible)

import tensorflow as tf
x = tf.constant([[1, 2], [3, 4]])
print(x.shape) # (2, 2)

🔹 Layer:

Neural network का एक building block (Dense, Conv2D, LSTM)

from tensorflow.keras.layers import Dense
dense = Dense(units=64, activation='relu')

🔹 Model:

Input से Output तक का पूरा network architecture

from tensorflow.keras.models import Sequential

model = Sequential([
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])

🔷 4. Keras में Model बनाना (Step-by-Step)

✅ Step 1: Import

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

✅ Step 2: Model Define

model = Sequential([
Dense(64, activation='relu', input_shape=(100,)),
Dense(10, activation='softmax')
])

✅ Step 3: Compile

model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)

✅ Step 4: Train

model.fit(x_train, y_train, epochs=10, batch_size=32)

✅ Step 5: Evaluate

model.evaluate(x_test, y_test)

🧪 Example: Simple Binary Classifier

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential([
Dense(16, activation='relu', input_shape=(2,)),
Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=20)

🔧 Useful Layers in Keras

LayerUse
DenseFully connected layer
Conv2DImage convolution layer
LSTM / GRUSequence modeling
DropoutRegularization
FlattenInput flattening
EmbeddingWord embedding for NLP

🧠 Visualization: Model Summary

model.summary()

📝 Practice Questions:

  1. TensorFlow और Keras में क्या अंतर है?
  2. Sequential model क्या होता है?
  3. Model को compile करने में किन चीज़ों की ज़रूरत होती है?
  4. Dense layer क्या है?
  5. एक simple 3-layer model का कोड लिखिए।

🧠 Summary Table

ConceptDescription
TensorFlowGoogle का ML framework
KerasEasy high-level API
TensorMultidimensional data
LayerModel का हिस्सा (Dense, Conv)
ModelComplete NN architecture

Transformers and BERT

अब हम NLP के सबसे क्रांतिकारी अविष्कारों की ओर बढ़ते हैं —
🚀 Transformers और BERT — जिन्होंने NLP की दुनिया को पूरी तरह बदल दिया है।


🔶 1. Transformers: Introduction

Transformer architecture 2017 में Google ने पेश किया, पेपर:

📄 “Attention is All You Need” — Vaswani et al.

इसने Recurrent Networks (RNN, LSTM) की dependency को हटा दिया और NLP को पूरी तरह से revolutionize कर दिया।


📐 Transformer की Key Idea: Self-Attention

हर word sentence के बाकी सभी words के context को साथ में समझता है, न कि केवल पिछले शब्दों को।


🔧 Architecture Overview

Transformer दो मुख्य हिस्सों में बंटा होता है:

[Encoder] →→→→→→→→→ [Decoder]
PartRole
EncoderInput text को समझना (e.g., sentence meaning)
DecoderOutput generate करना (e.g., translation, caption)

Note: BERT सिर्फ Encoder यूज़ करता है, GPT सिर्फ Decoder।


🔁 Self-Attention Mechanism

हर शब्द input में बाकी सभी शब्दों से relate करता है:

Sentence: "The cat sat on the mat"
"cat" → attends to "the", "sat", "mat" etc. via attention scores

🔢 Attention Equation:

जहाँ:

  • Q: Query
  • K: Key
  • V: Value
  • dk: Key vector dimension

⚙️ Transformer के Components:

ComponentExplanation
🔹 Multi-Head AttentionParallel attention layers for better learning
🔹 Positional EncodingSequence order की जानकारी add करता है
🔹 Feedforward NetworkLinear + non-linear layers
🔹 Layer NormalizationStable training
🔹 Residual ConnectionsGradient flow बनाए रखता है

🧠 2. BERT: Bidirectional Encoder Representations from Transformers

📄 “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” – Devlin et al., 2018


🎯 मुख्य उद्देश्य:

  • Language Understanding — Chatbots, Q&A, classification

🔧 कैसे काम करता है?

  • BERT केवल Transformer Encoder architecture पर आधारित है।
  • यह दोनों तरफ के context को एक साथ पढ़ता है — इसलिए Bidirectional है।

📊 Pretraining Tasks:

  1. Masked Language Modeling (MLM)
    • Sentence में कुछ शब्दों को mask किया जाता है, और model को predict करना होता है।
    textCopyEditInput: "The [MASK] is shining" Output: "sun"
  2. Next Sentence Prediction (NSP)
    • दो sentences दिए जाते हैं — model को यह predict करना होता है कि दूसरा sentence पहले के बाद आता है या नहीं।

📦 Pretrained BERT Models:

VariantDescription
bert-base-uncasedLowercase English, 12 layers
bert-large-uncased24 layers, large model
DistilBERTLightweight, faster
Multilingual BERT100+ languages

🔧 BERT Applications:

TaskExample
✅ Sentiment Analysis“I love this product!” → Positive
🧠 Question Answering“Where is Taj Mahal?” → “Agra”
✍️ Named Entity Recognition“Barack Obama is from USA” → Person, Country
💬 ChatbotsIntent understanding
📃 Text ClassificationNews, spam, legal docs

🧰 Example: HuggingFace Transformers

from transformers import BertTokenizer, BertModel

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")

inputs = tokenizer("I love deep learning", return_tensors="pt")
outputs = model(**inputs)

🧠 Transformer vs BERT

AspectTransformerBERT
TypeGeneral architecturePretrained NLP model
StructureEncoder + DecoderOnly Encoder
DirectionDependsBidirectional
ApplicationTranslation, captioningUnderstanding, classification

📈 Transformers & BERT Impact

AreaImpact
📚 ResearchNLP को neural-level accuracy
🗣️ ChatbotsSmarter conversations
🧾 Legal/MedicalAutomated document understanding
🧠 AI ModelsFoundation for GPT, T5, RoBERTa, etc.

📝 Practice Questions:

  1. Transformer architecture में self-attention का क्या role है?
  2. BERT bidirectional क्यों है?
  3. Masked Language Modeling का मतलब क्या है?
  4. BERT किन NLP tasks के लिए use होता है?
  5. HuggingFace से BERT कैसे load करते हैं?

🧠 Summary Table

TermDescription
TransformerSequence model using attention mechanism
BERTBidirectional encoder for NLP tasks
MLMMask words and predict
NSPPredict sentence relationship
ApplicationsQ&A, classification, chatbot, NER

Sequence Models for Text (RNN, LSTM)

NLP की एक महत्वपूर्ण category — Sequence Models — की ओर बढ़ते हैं।
Text data inherently sequential होता है (हर word का order matter करता है), और इसी कारण हमें ऐसे models की ज़रूरत होती है जो sequence को याद रख सकें


🔶 1. Sequence Data क्या होता है?

Text = शब्दों का क्रम (sequence of words):
जैसे: "मैं स्कूल जा रहा हूँ।"
यहाँ “जा रहा” और “जा रही” में फर्क होता है — क्रम मायने रखता है।

🧠 Sequence models का कार्य है – इस क्रम और संदर्भ को समझना।


🔁 2. Recurrent Neural Network (RNN)

📌 उद्देश्य:

  • ऐसे model बनाना जो पिछले शब्दों का context याद रखकर अगला शब्द समझें या predict करें।

🔧 Working (Step-by-step):

हर समय step पर input आता है (word) और hidden state update होता है:

x₁ → x₂ → x₃ ...
↓ ↓ ↓
h₁ → h₂ → h₃ → Output

यह hidden state ht पिछली जानकारी को अगली word processing में उपयोग करता है।


⚠️ RNN की सीमाएं (Limitations)

समस्याविवरण
❌ Vanishing Gradientलंबे sentences में पिछले context की जानकारी खो जाती है
❌ Fixed memoryपुराने शब्दों को ठीक से नहीं याद रख पाता
❌ Slow trainingSequential nature के कारण parallelization कठिन

🔄 3. LSTM (Long Short-Term Memory)

LSTM, RNN का एक बेहतर version है — जिसे इस समस्या को हल करने के लिए 1997 में Hochreiter & Schmidhuber ने प्रस्तावित किया।


📌 Core Idea:

LSTM में एक special memory cell होता है जो decide करता है कि कौन-सी जानकारी याद रखनी है, कौन-सी भूलनी है, और कौन-सी update करनी है।


🧠 Key Components of LSTM:

GateRole
🔒 Forget Gateक्या भूलना है
🔓 Input Gateक्या जोड़ना है
📤 Output Gateअगले step में क्या भेजना है

📊 LSTM Architecture (Flow)

Input xₜ → [Forget Gate, Input Gate, Output Gate] → Cell State → Output hₜ

LSTM sequence को ज़्यादा देर तक याद रखने में सक्षम होता है।


🔢 Equations (Simplified):


🧪 Practical Example:

📌 Use Case: Text Generation

  • Input: “The sun”
  • Output: “The sun is shining brightly today…”

LSTM last words को याद रखकर अगला word predict करता है।


🧰 Python Code Example (PyTorch)

import torch.nn as nn

class LSTMModel(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, vocab_size)

def forward(self, x):
x = self.embedding(x)
out, _ = self.lstm(x)
out = self.fc(out)
return out

🤖 RNN vs LSTM Comparison

FeatureRNNLSTM
MemoryShortLong
GatesNoYes (forget, input, output)
Vanishing GradientCommonHandled
Use CaseSimple patternsComplex sequences

📈 Applications of Sequence Models

TaskUse
🔤 Language ModelingNext word prediction
✍️ Text GenerationPoetry, story generation
📧 Spam DetectionSequential classification
🎧 Speech RecognitionAudio-to-text
🧠 Sentiment AnalysisReview understanding
💬 ChatbotsHuman-like conversation

📝 Practice Questions:

  1. Sequence model की जरूरत NLP में क्यों पड़ती है?
  2. RNN का drawback क्या है?
  3. LSTM कैसे context याद रखता है?
  4. LSTM में तीन मुख्य gates कौन से हैं?
  5. एक छोटा सा PyTorch LSTM model का code लिखिए।

🧠 Summary Table

TermMeaning
RNNSequence modeling network
LSTMLong-memory capable RNN
GatesDecide memory control
ApplicationText, audio, time-series
LimitationRNN: short memory; LSTM: handles long-term context