Neural Networks & Deep Learning – Complete Notes

Artificial Neural Networks, CNN, RNN, TensorFlow और PyTorch – Detailed notes in English and हिंदी

1. Introduction to Neural Networks

English

  1. Problem: Traditional machine-learning algorithms (linear regression, decision trees, SVMs) work well on structured data, but they struggle with high-dimensional unstructured data: images, audio, text, video. Hand-engineering features for these problems is nearly impossible — how would you describe a cat to a decision tree? A new family of algorithms was needed that could learn features automatically from raw data, layer by layer, and scale to millions of examples.
  2. Definition: An Artificial Neural Network (ANN) is a computing system inspired by biological neurons, made of layers of interconnected units (neurons). Each connection has a weight; each neuron computes a weighted sum of its inputs, adds a bias, and passes the result through a non-linear activation function. Deep Learning is the branch of machine learning that uses ANNs with many hidden layers to learn hierarchical representations of data.
  3. Example: Image classification with a small network:
    import tensorflow as tf
    from tensorflow.keras import layers, models
    
    model = models.Sequential([
        layers.Flatten(input_shape=(28, 28)),      # input: 784 pixels
        layers.Dense(128, activation='relu'),       # hidden layer 1
        layers.Dense(64,  activation='relu'),       # hidden layer 2
        layers.Dense(10,  activation='softmax')     # output: 10 classes
    ])
    
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    # model.fit(x_train, y_train, epochs=5)
  4. Types:
    Type Idea Typical Use
    Feedforward (MLP/DNN) Data flows forward through dense layers Tabular data, small images
    CNN Local filters + weight sharing Images, video, signals
    RNN / LSTM / GRU Sequential memory Text, time series, speech
    Transformer Self-attention over sequences NLP, vision, multimodal
    Autoencoder Bottleneck compression + reconstruction Dim reduction, anomaly detection
    GAN Generator vs discriminator Image synthesis, super-res
    Reinforcement NN Learn policies from reward Games, robotics
  5. Advantages:
    • Automatic feature learning from raw data.
    • Universal approximators — can approximate any continuous function with enough units.
    • Scales to millions of parameters and examples with GPUs/TPUs.
    • Transferable — pretrained models reuse learning across tasks.
    • State-of-the-art in vision, speech, NLP, medicine, and games.
    • Flexible architectures — same building blocks combine many ways.
  6. Disadvantages:
    • Data-hungry — needs large labelled datasets.
    • Compute-hungry — GPUs and long training times.
    • Black box — hard to interpret decisions.
    • Overfitting risk on small data.
    • Hyperparameter-sensitive — many knobs to tune.
    • Energy cost — training large models consumes significant power.
  7. Characteristics:
    • Layered architecture: Input → hidden layers → output.
    • Weights & biases: Learnable parameters.
    • Activation functions: Non-linearity (ReLU, sigmoid, tanh, softmax).
    • Loss function: Guides learning (MSE, cross-entropy).
    • Optimization: Gradient descent variants.
    • Backpropagation: Efficient gradient computation.
  8. Diagram: Simple feedforward network
         INPUT       HIDDEN 1     HIDDEN 2      OUTPUT
          x1 ─────▶  h1 ──┐  ┌── h1' ──┐
          x2 ─────▶  h2 ──┼──▶ h2' ──┼──▶  y1
          x3 ─────▶  h3 ──┼──▶ h3' ──┼──▶  y2
                         │          │
                        Bias       Bias
    
        Every line = a weight. Each hidden neuron:
          z = Σ (wᵢ · xᵢ) + b
          a = activation(z)
  9. Conclusion: Neural networks changed machine learning by replacing hand-crafted features with learned ones. Deep networks build hierarchies — edges → shapes → objects — that match the structure of real-world data. They are the foundation of modern AI: image recognition, machine translation, speech assistants, and language models. Understanding the basic unit (a weighted sum plus non-linearity) and the training loop (forward pass, loss, backprop, update) unlocks every architecture that follows.
  10. Exercise:
    1. Explain with a diagram how a neuron computes its output.
    2. List three tasks where neural networks outperform classical ML.
    3. Write TensorFlow/Keras code for a 2-hidden-layer network on MNIST.
    4. Why is a non-linear activation necessary?
    5. Compare CNNs, RNNs and Transformers in one table.

हिंदी (सरल)

  1. समस्या: Traditional machine-learning algorithms (linear regression, decision trees, SVMs) structured data पर ठीक चलते हैं, पर high-dimensional unstructured data — images, audio, text, video — पर struggle करते हैं। इन problems के लिए features हाथ से engineer करना लगभग असंभव है — किसी decision tree को cat कैसे describe करें? एक नई family चाहिए थी जो raw data से features अपने आप सीखे, layer by layer, और millions of examples तक scale करे।
  2. परिभाषा: Artificial Neural Network (ANN) biological neurons से inspired computing system है, जिसमें interconnected units (neurons) की layers होती हैं। हर connection का एक weight होता है; हर neuron अपने inputs का weighted sum निकालता है, bias जोड़ता है, और result को non-linear activation function से pass करता है। Deep Learning machine learning की वह शाखा है जो कई hidden layers वाले ANNs से data का hierarchical representation सीखती है।
  3. उदाहरण: छोटे network से image classification:
    import tensorflow as tf
    from tensorflow.keras import layers, models
    
    model = models.Sequential([
        layers.Flatten(input_shape=(28, 28)),      # input: 784 pixels
        layers.Dense(128, activation='relu'),       # hidden layer 1
        layers.Dense(64,  activation='relu'),       # hidden layer 2
        layers.Dense(10,  activation='softmax')     # output: 10 classes
    ])
    
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    # model.fit(x_train, y_train, epochs=5)
  4. प्रकार:
    Type Idea Typical Use
    Feedforward (MLP/DNN) Data dense layers से आगे बहता है Tabular data, छोटी images
    CNN Local filters + weight sharing Images, video, signals
    RNN / LSTM / GRU Sequential memory Text, time series, speech
    Transformer Sequences पर self-attention NLP, vision, multimodal
    Autoencoder Bottleneck compression + reconstruction Dim reduction, anomaly detection
    GAN Generator vs discriminator Image synthesis, super-res
    Reinforcement NN Reward से policies सीखें Games, robotics
  5. लाभ:
    • Automatic feature learning raw data से।
    • Universal approximators — पर्याप्त units के साथ कोई भी continuous function approximate।
    • Scale — GPUs/TPUs से millions of parameters और examples।
    • Transferable — pretrained models दूसरे tasks पर reuse।
    • State-of-the-art — vision, speech, NLP, medicine, games।
    • Flexible architectures — वही building blocks कई तरह।
  6. नुकसान:
    • Data-hungry — बड़े labelled datasets चाहिए।
    • Compute-hungry — GPUs और लंबा training।
    • Black box — decisions interpret करना कठिन।
    • Overfitting risk छोटे data पर।
    • Hyperparameter-sensitive — कई knobs।
    • Energy cost — बड़े models training में significant power।
  7. विशेषताएँ:
    • Layered architecture: Input → hidden → output।
    • Weights & biases: Learnable parameters।
    • Activation functions: Non-linearity (ReLU, sigmoid, tanh, softmax)।
    • Loss function: Learning guide (MSE, cross-entropy)।
    • Optimization: Gradient descent variants।
    • Backpropagation: Efficient gradient computation।
  8. आरेख: Simple feedforward network
         INPUT       HIDDEN 1     HIDDEN 2      OUTPUT
          x1 ─────▶  h1 ──┐  ┌── h1' ──┐
          x2 ─────▶  h2 ──┼──▶ h2' ──┼──▶  y1
          x3 ─────▶  h3 ──┼──▶ h3' ──┼──▶  y2
                         │          │
                        Bias       Bias
    
        हर line = एक weight। हर hidden neuron:
          z = Σ (wᵢ · xᵢ) + b
          a = activation(z)
  9. निष्कर्ष: Neural networks ने machine learning को बदल दिया — hand-crafted features की जगह learned features। Deep networks hierarchies बनाते हैं — edges → shapes → objects — जो real-world data की structure से मेल खाती हैं। ये modern AI की नींव हैं: image recognition, machine translation, speech assistants और language models। Basic unit (weighted sum + non-linearity) और training loop (forward pass, loss, backprop, update) समझना हर आगे की architecture unlock करता है।
  10. अभ्यास:
    1. Diagram के साथ समझाइए कि neuron अपना output कैसे compute करता है।
    2. तीन tasks list कीजिए जहाँ neural networks classical ML से बेहतर हैं।
    3. MNIST पर 2 hidden layers वाला TensorFlow/Keras network लिखिए।
    4. Non-linear activation ज़रूरी क्यों है?
    5. CNNs, RNNs और Transformers एक table में compare कीजिए।

2. Perceptron & Activation Functions

English

  1. Problem: A single perceptron can only draw a straight line as a decision boundary. It cannot learn XOR, spiral data, or any non-linearly separable pattern. To model complex relationships, we need networks of neurons where each neuron applies a non-linear transformation. Without non-linearity, stacking layers collapses into a single linear transformation — a deep network becomes no better than a linear classifier.
  2. Definition: A perceptron is the simplest neural unit: it computes y = activation(Σ wᵢ·xᵢ + b). The activation function introduces non-linearity, enabling networks to approximate any continuous function. Common activations: sigmoid, tanh, ReLU, Leaky ReLU, ELU, GELU, Swish, softmax.
  3. Example: Perceptron in pure Python and PyTorch:
    # Pure Python perceptron
    import numpy as np
    def perceptron(x, w, b):
        z = np.dot(w, x) + b
        return 1 if z >= 0 else 0
    
    # PyTorch single neuron
    import torch, torch.nn as nn
    neuron = nn.Linear(in_features=3, out_features=1)
    x = torch.tensor([[1.0, 2.0, 3.0]])
    y = torch.relu(neuron(x))
    print(y)
  4. Types:

    A. Common activation functions:

    Function Formula Range Notes
    Sigmoid 1 / (1 + e⁻ᶻ) (0, 1) Vanishing gradient; good for binary output.
    Tanh (eᶻ − e⁻ᶻ) / (eᶻ + e⁻ᶻ) (−1, 1) Zero-centred; still saturates.
    ReLU max(0, z) [0, ∞) Default for hidden layers; fast; dying ReLU risk.
    Leaky ReLU max(αz, z), α ≈ 0.01 (−∞, ∞) Fixes dying ReLU.
    ELU z if z > 0 else α(eᶻ − 1) (−α, ∞) Smoother, negative values.
    GELU z · Φ(z) (−0.17, ∞) Used in Transformers (BERT, GPT).
    Swish z · sigmoid(βz) (−0.28, ∞) Smooth; used in EfficientNet.
    Softmax eᶻⁱ / Σ eᶻʲ (0, 1), sums to 1 Multi-class output.

    B. Perceptron types: Single-layer perceptron (linear), Multi-Layer Perceptron (MLP, non-linear), and variants with different activations. The "linear perceptron" without activation can only classify linearly separable data.

  5. Advantages:
    • Simplicity: A perceptron is trivial to implement and understand.
    • ReLU family: Fast to compute, sparse, works well in deep networks.
    • Softmax: Gives calibrated probabilities for classification.
    • Non-linearity enables universal approximation.
    • Activations are differentiable for backpropagation.
    • Choice affects learning dynamics — right activation speeds up convergence.
  6. Disadvantages:
    • Sigmoid / tanh: Saturate → vanishing gradients.
    • ReLU: "Dying ReLU" — neurons stuck at zero.
    • Softmax: Not ideal for multi-label (use sigmoid per class).
    • Single perceptron cannot learn XOR — needs hidden layers.
    • Choice is empirical — no universal rule for which activation to use.
    • Over-smooth activations (GELU, Swish) can slow training on tiny datasets.
  7. Characteristics:
    • Non-linearity: The key reason deep networks work.
    • Differentiability: Needed for gradient-based training.
    • Vanishing gradient: Sigmoid/tanh problem, mitigated by ReLU family.
    • Zero-centred: Tanh better than sigmoid for optimization.
    • Output layer: Softmax for multi-class, sigmoid for binary, linear for regression.
    • Hidden layer default: ReLU or GELU.
  8. Diagram: Activation functions
        Sigmoid          Tanh              ReLU
        ───────          ────              ────
         1 ┤─╮            1 ┤  ╭─          ┤      /
           │  ╰─            │ /             │    /
         0 ┤───╮          0 ┤╯             │  /
           │    ╰─          │               │ /
        -1 ┤                 -1 ┤             └───────
            z                 z                z
    
        Dying ReLU problem:
    
          ReLU(z) = max(0, z)
          If z < 0 for all inputs → gradient = 0
          Neuron "dies" and never recovers.
    
        Fix: Leaky ReLU, ELU, GELU, Swish.
  9. Conclusion: The perceptron is the atom of every neural network. Its power comes from two ideas: weighted sums to combine inputs, and non-linear activations to bend the decision boundary. Without the non-linearity, depth is meaningless. Choosing the right activation is a design decision: ReLU for hidden layers, sigmoid for binary output, softmax for multi-class. Modern architectures increasingly prefer smooth activations (GELU, Swish) that improve training stability on large models.
  10. Exercise:
    1. Implement a perceptron from scratch in Python (without libraries).
    2. Plot sigmoid, tanh, ReLU and Leaky ReLU for z ∈ [−5, 5].
    3. Show with a small example that XOR is not linearly separable.
    4. Explain the dying ReLU problem and how Leaky ReLU fixes it.
    5. Which activation would you use at the output of a 10-class classifier?

हिंदी (सरल)

  1. समस्या: एक single perceptron सिर्फ straight line decision boundary बना सकता है। यह XOR, spiral data, या कोई भी non-linearly separable pattern नहीं सीख सकता। Complex relationships model करने के लिए neurons के networks चाहिए जहाँ हर neuron non-linear transformation लगाए। Non-linearity के बिना, layers stack करना एक single linear transformation में collapse हो जाता है — deep network linear classifier से बेहतर नहीं।
  2. परिभाषा: Perceptron सबसे सरल neural unit है: यह y = activation(Σ wᵢ·xᵢ + b) compute करता है। Activation function non-linearity लाता है, जिससे networks कोई भी continuous function approximate कर पाते हैं। Common activations: sigmoid, tanh, ReLU, Leaky ReLU, ELU, GELU, Swish, softmax।
  3. उदाहरण: Pure Python और PyTorch में perceptron:
    # Pure Python perceptron
    import numpy as np
    def perceptron(x, w, b):
        z = np.dot(w, x) + b
        return 1 if z >= 0 else 0
    
    # PyTorch single neuron
    import torch, torch.nn as nn
    neuron = nn.Linear(in_features=3, out_features=1)
    x = torch.tensor([[1.0, 2.0, 3.0]])
    y = torch.relu(neuron(x))
    print(y)
  4. प्रकार:

    A. Common activation functions:

    Function Formula Range Notes
    Sigmoid 1 / (1 + e⁻ᶻ) (0, 1) Vanishing gradient; binary output के लिए।
    Tanh (eᶻ − e⁻ᶻ) / (eᶻ + e⁻ᶻ) (−1, 1) Zero-centred; saturate।
    ReLU max(0, z) [0, ∞) Hidden layers का default; तेज़; dying ReLU।
    Leaky ReLU max(αz, z), α ≈ 0.01 (−∞, ∞) Dying ReLU fix।
    ELU z if z > 0 else α(eᶻ − 1) (−α, ∞) Smoother, negative values।
    GELU z · Φ(z) (−0.17, ∞) Transformers (BERT, GPT) में।
    Swish z · sigmoid(βz) (−0.28, ∞) Smooth; EfficientNet में।
    Softmax eᶻⁱ / Σ eᶻʲ (0, 1), sum = 1 Multi-class output।

    B. Perceptron types: Single-layer perceptron (linear), Multi-Layer Perceptron (MLP, non-linear), और अलग activations वाले variants। बिना activation वाला "linear perceptron" सिर्फ linearly separable data classify कर सकता है।

  5. लाभ:
    • Simplicity: Perceptron implement और समझना आसान।
    • ReLU family: तेज़, sparse, deep networks में अच्छा।
    • Softmax: Classification के लिए calibrated probabilities।
    • Non-linearity universal approximation enable।
    • Activations differentiable backpropagation के लिए।
    • Choice से learning dynamics — सही activation convergence तेज़।
  6. नुकसान:
    • Sigmoid / tanh: Saturate → vanishing gradients।
    • ReLU: "Dying ReLU" — neurons शून्य पर अटक जाएँ।
    • Softmax: Multi-label के लिए ideal नहीं (per class sigmoid)।
    • Single perceptron XOR नहीं सीख सकता — hidden layers चाहिए।
    • Choice empirical — कोई universal rule नहीं।
    • Over-smooth activations (GELU, Swish) छोटे datasets पर slow।
  7. विशेषताएँ:
    • Non-linearity: Deep networks के काम करने की मुख्य वजह।
    • Differentiability: Gradient-based training के लिए।
    • Vanishing gradient: Sigmoid/tanh समस्या, ReLU से fix।
    • Zero-centred: Tanh, sigmoid से optimization में बेहतर।
    • Output layer: Multi-class → softmax, binary → sigmoid, regression → linear।
    • Hidden layer default: ReLU या GELU।
  8. आरेख: Activation functions
        Sigmoid          Tanh              ReLU
        ───────          ────              ────
         1 ┤─╮            1 ┤  ╭─          ┤      /
           │  ╰─            │ /             │    /
         0 ┤───╮          0 ┤╯             │  /
           │    ╰─          │               │ /
        -1 ┤                 -1 ┤             └───────
            z                 z                z
    
        Dying ReLU problem:
    
          ReLU(z) = max(0, z)
          अगर सभी inputs के लिए z < 0 → gradient = 0
          Neuron "मर" जाता है और recover नहीं करता।
    
        Fix: Leaky ReLU, ELU, GELU, Swish।
  9. निष्कर्ष: Perceptron हर neural network का atom है। इसकी ताकत दो ideas से आती है: inputs combine करने के लिए weighted sums, और decision boundary मोड़ने के लिए non-linear activations। Non-linearity के बिना depth का कोई मतलब नहीं। सही activation चुनना design decision है: hidden layers के लिए ReLU, binary output के लिए sigmoid, multi-class के लिए softmax। Modern architectures smooth activations (GELU, Swish) prefer कर रही हैं जो बड़े models पर training stability बढ़ाती हैं।
  10. अभ्यास:
    1. Pure Python में बिना libraries perceptron implement कीजिए।
    2. z ∈ [−5, 5] के लिए sigmoid, tanh, ReLU और Leaky ReLU plot कीजिए।
    3. छोटे उदाहरण से दिखाइए कि XOR linearly separable नहीं है।
    4. Dying ReLU problem और Leaky ReLU कैसे fix करता है समझाइए।
    5. 10-class classifier के output पर कौन सा activation use करेंगे?

3. Feedforward Networks & Backpropagation

English

  1. Problem: Once we stack layers, we need a way to update thousands or millions of weights to reduce error. Guessing or brute force is impossible. We need an efficient algorithm that computes the gradient of the loss with respect to every weight, so we can take a small step in the direction that reduces the loss. Naive gradient computation would be O(parameters²) — too slow. Backpropagation reduces this to roughly O(parameters).
  2. Definition: A feedforward network (also MLP or DNN) passes data through layers from input to output, with no cycles. Backpropagation is the algorithm that trains such networks: it performs a forward pass to compute the output and loss, then propagates the error backwards using the chain rule of calculus to compute gradients for every weight and bias, and finally updates weights with an optimizer (SGD, Adam, etc.).
  3. Example: Forward and backward pass:
    # Forward pass
    z1 = X @ W1 + b1
    a1 = relu(z1)
    z2 = a1 @ W2 + b2
    y_hat = softmax(z2)
    
    # Loss
    loss = -mean( y_onehot * log(y_hat) )
    
    # Backward pass (chain rule — PyTorch does this for you)
    loss.backward()
    
    # Update
    optimizer.step()
    optimizer.zero_grad()
  4. Types:

    A. Network types:

    Type Description
    Single-layer perceptron Input → output, linear
    Multi-Layer Perceptron (MLP) Input → several hidden → output
    Deep Neural Network (DNN) Many hidden layers; used loosely
    Fully-connected network Every neuron connects to every neuron in next layer

    B. Backpropagation variants: Full-batch, stochastic (SGD), mini-batch, and variants with momentum, Nesterov, RMSProp, Adam, AdamW.

    C. Loss functions: MSE (regression), Binary cross-entropy (binary classification), Categorical cross-entropy (multi-class), Focal loss (class imbalance).

  5. Advantages:
    • Efficient: Backprop computes all gradients in roughly one forward + one backward pass.
    • General: Works with any differentiable architecture.
    • Automatic in modern frameworks — PyTorch/TensorFlow compute gradients via autograd.
    • Scalable: GPUs make training large networks practical.
    • Foundation for CNNs, RNNs, Transformers — same algorithm.
  6. Disadvantages:
    • Vanishing/exploding gradients in very deep networks.
    • Requires differentiability — no discrete ops directly.
    • Memory for stored activations during training.
    • Local minima / saddle points can slow SGD.
    • Hyperparameter sensitivity — LR, batch size, weight init matter.
    • Numerical instability — need stable cross-entropy, ReLU, BN.
  7. Characteristics:
    • Chain rule: Gradients flow backwards through layers.
    • Weight initialization: Xavier, He — crucial for depth.
    • Mini-batch training: Balance between SGD and full-batch.
    • Epoch: One full pass over the training set.
    • Learning rate: Too high → diverge; too low → slow.
    • Autograd: Framework computes gradients via computational graph.
  8. Diagram: Forward and backward pass
        Forward:  X → [W1] → z1 → ReLU → [W2] → z2 → softmax → ŷ
                                                                  │
                                                                  ▼
                                                                Loss
                                                                  │
                                                                  ▼
        Backward:            ◀──  ∂L/∂W2  ◀──  ∂L/∂a1  ◀──  ∂L/∂z1
                                  (chain rule)
                                    │
                                    ▼
                             W2 ← W2 − η·∂L/∂W2
                             W1 ← W1 − η·∂L/∂W1
    
        Each training step:
    
          1. Forward pass  → predictions
          2. Compute loss
          3. Backward pass → gradients
          4. Optimizer step (update weights)
          5. zero_grad() → reset for next step
  9. Conclusion: Feedforward networks plus backpropagation are the engine of deep learning. Backprop's beauty is its use of the chain rule: gradients flow backwards layer by layer, and modern frameworks do this automatically via autograd. When training fails (loss plateaus, explodes, or diverges), the problem is usually in weight initialization, learning rate, normalization, or activation choice. Understanding the forward/backward loop is essential before moving to CNNs, RNNs, and Transformers — they all use the same training machinery.
  10. Exercise:
    1. Write a 3-layer MLP in PyTorch for the Iris dataset.
    2. Compute gradients manually for a 2-layer network on paper.
    3. Explain why weight initialization matters for deep networks.
    4. Compare SGD, mini-batch, and full-batch training.
    5. Show how to log loss per epoch in Keras.

हिंदी (सरल)

  1. समस्या: Layers stack करने के बाद हमें हजारों-लाखों weights update करने का तरीका चाहिए ताकि error घटे। Guess या brute force असंभव। एक efficient algorithm चाहिए जो हर weight के सापेक्ष loss का gradient compute करे, ताकि हम loss घटाने वाली दिशा में छोटा step लें। Naive gradient computation O(parameters²) — बहुत धीमा। Backpropagation इसे लगभग O(parameters) कर देता है।
  2. परिभाषा: Feedforward network (MLP या DNN भी) data को layers से input → output तक pass करता है, कोई cycles नहीं। Backpropagation वह algorithm है जो इन्हें train करता है: forward pass से output और loss compute, फिर calculus के chain rule से error पीछे propagate करके हर weight और bias का gradient निकालता है, और अंत में optimizer (SGD, Adam आदि) से weights update करता है।
  3. उदाहरण: Forward और backward pass:
    # Forward pass
    z1 = X @ W1 + b1
    a1 = relu(z1)
    z2 = a1 @ W2 + b2
    y_hat = softmax(z2)
    
    # Loss
    loss = -mean( y_onehot * log(y_hat) )
    
    # Backward pass (chain rule — PyTorch कर देता है)
    loss.backward()
    
    # Update
    optimizer.step()
    optimizer.zero_grad()
  4. प्रकार:

    A. Network types:

    Type विवरण
    Single-layer perceptron Input → output, linear
    Multi-Layer Perceptron (MLP) Input → कई hidden → output
    Deep Neural Network (DNN) कई hidden layers; loosely used
    Fully-connected network हर neuron अगली layer के हर neuron से जुड़ा

    B. Backpropagation variants: Full-batch, stochastic (SGD), mini-batch, और momentum, Nesterov, RMSProp, Adam, AdamW वाले variants।

    C. Loss functions: MSE (regression), Binary cross-entropy (binary classification), Categorical cross-entropy (multi-class), Focal loss (class imbalance)।

  5. लाभ:
    • Efficient: Backprop लगभग one forward + one backward pass में सभी gradients।
    • General: कोई भी differentiable architecture के साथ।
    • Automatic modern frameworks में — PyTorch/TensorFlow autograd से।।
    • Scalable: GPUs से बड़े networks practical।
    • Foundation CNNs, RNNs, Transformers — वही algorithm।
  6. नुकसान:
    • Vanishing/exploding gradients बहुत deep networks में।
    • Differentiability चाहिए — discrete ops directly नहीं।
    • Memory training के दौरान stored activations।
    • Local minima / saddle points SGD धीमा कर सकते हैं।
    • Hyperparameter sensitivity — LR, batch size, weight init।
    • Numerical instability — stable cross-entropy, ReLU, BN चाहिए।
  7. विशेषताएँ:
    • Chain rule: Gradients layers से पीछे flow।
    • Weight initialization: Xavier, He — depth के लिए critical।
    • Mini-batch training: SGD और full-batch के बीच balance।
    • Epoch: Training set पर एक पूरा pass।
    • Learning rate: बहुत high → diverge; बहुत low → slow।
    • Autograd: Framework computational graph से gradients।
  8. आरेख: Forward और backward pass
        Forward:  X → [W1] → z1 → ReLU → [W2] → z2 → softmax → ŷ
                                                                  │
                                                                  ▼
                                                                Loss
                                                                  │
                                                                  ▼
        Backward:            ◀──  ∂L/∂W2  ◀──  ∂L/∂a1  ◀──  ∂L/∂z1
                                  (chain rule)
                                    │
                                    ▼
                             W2 ← W2 − η·∂L/∂W2
                             W1 ← W1 − η·∂L/∂W1
    
        हर training step:
    
          1. Forward pass  → predictions
          2. Loss compute
          3. Backward pass → gradients
          4. Optimizer step (weights update)
          5. zero_grad() → next step के लिए reset
  9. निष्कर्ष: Feedforward networks और backpropagation deep learning का इंजन हैं। Backprop की सुंदरता chain rule में है: gradients layers से पीछे flow करते हैं, और modern frameworks autograd से यह अपने आप करते हैं। जब training fail हो (loss plateau, explode, diverge), समस्या अक्सर weight initialization, learning rate, normalization, या activation choice में होती है। Forward/backward loop समझना CNNs, RNNs और Transformers पर जाने से पहले ज़रूरी है — सब वही training machinery use करते हैं।
  10. अभ्यास:
    1. Iris dataset पर 3-layer MLP PyTorch में लिखिए।
    2. 2-layer network के gradients कागज़ पर manually compute कीजिए।
    3. Deep networks में weight initialization क्यों मायने रखता है समझाइए।
    4. SGD, mini-batch और full-batch training compare कीजिए।
    5. Keras में per-epoch loss log करना दिखाइए।

4. Gradient Descent & Optimization

English

  1. Problem: Given a loss function over millions of parameters, we need to find the parameter values that minimise it. Closed-form solutions exist only for simple models (linear regression with MSE). For deep networks, the loss surface is non-convex with saddle points, plateaus, and sharp valleys. Naive gradient descent can be slow, unstable, or stuck. Optimizers were developed to make training fast and reliable.
  2. Definition: Gradient descent is an iterative optimization algorithm that updates parameters in the direction opposite to the gradient of the loss: θ ← θ − η · ∇L(θ). The learning rate η controls step size. Variants change how the gradient is estimated (batch size) and how updates are computed (momentum, adaptive LR).
  3. Example: Optimizers in PyTorch and Keras:
    # PyTorch
    import torch.optim as optim
    
    optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
    # or: optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
    # or: optim.AdamW(model.parameters(), lr=1e-3)
    
    for epoch in range(10):
        optimizer.zero_grad()
        out  = model(x)
        loss = criterion(out, y)
        loss.backward()
        optimizer.step()
    
    # Keras
    model.compile(
        optimizer=tf.keras.optimizers.Adam(1e-3),
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )
    
    # Learning rate schedule
    scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)
  4. Types:

    A. Gradient descent variants:

    Variant Batch size Notes
    Batch GD Full dataset Stable, slow, high memory
    Stochastic GD 1 sample Noisy, fast, escapes local minima
    Mini-batch GD 32–512 Default in practice

    B. Optimizers:

    Optimizer Idea
    SGD θ ← θ − η·∇L
    Momentum Accumulate velocity to smooth updates
    Nesterov Look-ahead momentum
    AdaGrad Per-parameter LR, good for sparse
    RMSProp Exponential average of squared grads
    Adam Momentum + RMSProp; most popular
    AdamW Adam with decoupled weight decay
    LAMB Layer-wise adaptive LR for very large batches

    C. LR schedules: Step decay, exponential, cosine annealing, warmup + cosine, one-cycle, ReduceLROnPlateau.

  5. Advantages:
    • Simple and general: Works with any differentiable model.
    • Mini-batch: Efficient use of GPUs.
    • Adam family: Fast convergence, minimal tuning.
    • Schedules: Improve final accuracy.
    • Adaptive methods handle sparse features and different scales.
    • Momentum escapes shallow local minima.
  6. Disadvantages:
    • Learning rate sensitive: Bad η ruins training.
    • Saddle points can trap SGD without momentum.
    • Adam generalization sometimes slightly worse than fine-tuned SGD.
    • Memory for optimizer state (Adam 2× parameters).
    • Hyperparameters: β1, β2, ε, weight decay require tuning.
    • Gradient noise from small batches can destabilize training.
  7. Characteristics:
    • Iterative: Many small steps, not one big jump.
    • Stochastic: Gradient from mini-batch approximates true gradient.
    • Non-convex: Local minima, saddle points, plateaus.
    • Adaptive methods: Per-parameter learning rates.
    • Weight decay: L2 regularization equivalent for SGD.
    • Gradient clipping: Prevents exploding gradients in RNNs.
  8. Diagram: Optimization landscape and LR effect
        Loss surface (2D slice):
    
                  ▲  Loss
                  │    ╭──╮     local min
                  │   ╱    ╲
                  │  ╱      ╲
                  │ ╱        ╲     saddle
                  │╱          ╲      ────────
                  │            ╲___╱
                  │              ╲     global min
                  └────────────────────────────────▶ θ
    
        Learning rate effect:
    
          Too high:   ╱╲╱╲╱╲   bounces, diverges
          Too low:    ────────  slow crawl
          Just right: ───────╲  smooth descent
    
        Momentum:
    
          v ← β·v − η·∇L
          θ ← θ + v
          Accumulates direction → faster, smoother
  9. Conclusion: Optimization is where deep learning gets practical. SGD with momentum and Adam are the two workhorses. The learning rate — and its schedule — matters more than almost any other hyperparameter. Modern practice: Adam/AdamW for quick prototyping, SGD with momentum + cosine schedule for best final accuracy on vision tasks, gradient clipping for RNNs and Transformers, and warmup for large models. Understanding the optimizer is essential for diagnosing training problems.
  10. Exercise:
    1. Train the same network with SGD and Adam; compare loss curves.
    2. Experiment with LR 1e-1, 1e-3, 1e-5 and record final accuracy.
    3. Add a cosine LR schedule and show its effect.
    4. Explain momentum with a physical analogy.
    5. Show gradient clipping in PyTorch with clip_grad_norm_.

हिंदी (सरल)

  1. समस्या: लाखों parameters वाले loss function में वे parameter values ढूँढने हैं जो इसे minimise करें। Closed-form solutions सिर्फ सरल models (linear regression with MSE) के लिए हैं। Deep networks में loss surface non-convex है — saddle points, plateaus, sharp valleys। Naive gradient descent slow, unstable, या stuck हो सकता है। Optimizers training को fast और reliable बनाने के लिए विकसित हुए।
  2. परिभाषा: Gradient descent iterative optimization algorithm है जो parameters को loss के gradient की opposite direction में update करता है: θ ← θ − η · ∇L(θ). Learning rate η step size तय करता है। Variants बदलते हैं कि gradient कैसे estimate होता है (batch size) और updates कैसे compute होती हैं (momentum, adaptive LR).
  3. उदाहरण: PyTorch और Keras में optimizers:
    # PyTorch
    import torch.optim as optim
    
    optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
    # या: optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
    # या: optim.AdamW(model.parameters(), lr=1e-3)
    
    for epoch in range(10):
        optimizer.zero_grad()
        out  = model(x)
        loss = criterion(out, y)
        loss.backward()
        optimizer.step()
    
    # Keras
    model.compile(
        optimizer=tf.keras.optimizers.Adam(1e-3),
        loss='categorical_crossentropy',
        metrics=['accuracy']
    )
    
    # Learning rate schedule
    scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)
  4. प्रकार:

    A. Gradient descent variants:

    Variant Batch size Notes
    Batch GD पूरा dataset Stable, slow, high memory
    Stochastic GD 1 sample Noisy, fast, local minima से escape
    Mini-batch GD 32–512 Practice में default

    B. Optimizers:

    Optimizer Idea
    SGD θ ← θ − η·∇L
    Momentum Velocity accumulate → smooth updates
    Nesterov Look-ahead momentum
    AdaGrad Per-parameter LR, sparse data के लिए
    RMSProp Squared grads का exponential average
    Adam Momentum + RMSProp; सबसे popular
    AdamW Adam + decoupled weight decay
    LAMB बहुत बड़े batches के लिए layer-wise LR

    C. LR schedules: Step decay, exponential, cosine annealing, warmup + cosine, one-cycle, ReduceLROnPlateau।

  5. लाभ:
    • Simple और general: कोई भी differentiable model।
    • Mini-batch: GPUs का efficient use।
    • Adam family: तेज़ convergence, कम tuning।
    • Schedules: Final accuracy better।
    • Adaptive methods sparse features और अलग scales handle।
    • Momentum shallow local minima से escape।
  6. नुकसान:
    • Learning rate sensitive: खराब η training ruin।
    • Saddle points बिना momentum SGD को trap।
    • Adam generalization कभी fine-tuned SGD से थोड़ा खराब।
    • Memory optimizer state (Adam 2× parameters)।
    • Hyperparameters: β1, β2, ε, weight decay tuning।
    • Gradient noise छोटे batches से training destabilize।
  7. विशेषताएँ:
    • Iterative: कई छोटे steps, एक बड़ी छलांग नहीं।
    • Stochastic: Mini-batch का gradient true gradient approximate।
    • Non-convex: Local minima, saddle points, plateaus।
    • Adaptive methods: Per-parameter learning rates।
    • Weight decay: SGD के लिए L2 regularization equivalent।
    • Gradient clipping: RNNs में exploding gradients रोकता है।
  8. आरेख: Optimization landscape और LR effect
        Loss surface (2D slice):
    
                  ▲  Loss
                  │    ╭──╮     local min
                  │   ╱    ╲
                  │  ╱      ╲
                  │ ╱        ╲     saddle
                  │╱          ╲      ────────
                  │            ╲___╱
                  │              ╲     global min
                  └────────────────────────────────▶ θ
    
        Learning rate effect:
    
          बहुत high:  ╱╲╱╲╱╲   bounce, diverge
          बहुत low:   ────────  slow crawl
          बिल्कुल सही: ───────╲  smooth descent
    
        Momentum:
    
          v ← β·v − η·∇L
          θ ← θ + v
          Direction accumulate → faster, smoother
  9. निष्कर्ष: Optimization वह जगह है जहाँ deep learning practical बनती है। SGD with momentum और Adam दो workhorses हैं। Learning rate — और उसका schedule — लगभग किसी भी hyperparameter से ज़्यादा मायने रखता है। Modern practice: quick prototyping के लिए Adam/AdamW, vision tasks पर best final accuracy के लिए SGD with momentum + cosine schedule, RNNs और Transformers के लिए gradient clipping, और बड़े models के लिए warmup। Optimizer समझना training problems diagnose करने के लिए essential है।
  10. अभ्यास:
    1. वही network SGD और Adam से train करके loss curves compare कीजिए।
    2. LR 1e-1, 1e-3, 1e-5 से experiment करके final accuracy record कीजिए।
    3. Cosine LR schedule जोड़कर असर दिखाइए।
    4. Momentum को physical analogy से समझाइए।
    5. PyTorch में clip_grad_norm_ से gradient clipping दिखाइए।

5. Regularization, Dropout & Batch Normalization

English

  1. Problem: Deep networks have millions of parameters and can memorise the training set — achieving near-zero training error while performing poorly on new data. This is overfitting. Internal covariate shift (changing distributions across layers during training) also slows learning and makes it fragile. Regularization techniques and normalization layers solve both problems.
  2. Definition: Regularization is any technique that improves generalization (test performance) rather than training performance. Dropout randomly zeroes a fraction of activations during training, forcing the network to be robust. Batch Normalization (BN) normalizes activations per mini-batch, stabilising and accelerating training. Layer Normalization is the sequential analogue used in Transformers.
  3. Example: Dropout and BatchNorm in Keras and PyTorch:
    # Keras
    from tensorflow.keras import layers
    model = tf.keras.Sequential([
        layers.Dense(256),
        layers.BatchNormalization(),
        layers.Activation('relu'),
        layers.Dropout(0.3),
        layers.Dense(128, activation='relu'),
        layers.Dropout(0.3),
        layers.Dense(10, activation='softmax')
    ])
    
    # PyTorch
    class Net(nn.Module):
        def __init__(self):
            super().__init__()
            self.fc1  = nn.Linear(784, 256)
            self.bn1  = nn.BatchNorm1d(256)
            self.drop = nn.Dropout(0.3)
            self.fc2  = nn.Linear(256, 10)
    
        def forward(self, x):
            x = self.drop(F.relu(self.bn1(self.fc1(x))))
            return self.fc2(x)
  4. Types:

    A. Regularization techniques:

    Technique Idea
    L2 (weight decay) Penalise large weights (λ·Σw²)
    L1 Penalise |w|; encourages sparsity
    Dropout Randomly drop activations during training
    Data augmentation More diverse training data
    Early stopping Stop when val loss starts increasing
    Label smoothing Soften one-hot targets
    Ensembling Combine multiple models
    Dropout variants Spatial Dropout, DropBlock, Stochastic Depth

    B. Normalization layers: Batch Norm, Layer Norm, Group Norm, Instance Norm, RMS Norm.

    C. Where to place:

    • Convolutional nets: Conv → BN → ReLU → Dropout.
    • Transformers: Linear → LayerNorm (pre-norm).
    • RNNs: Layer Norm is common; Batch Norm less so.
  5. Advantages:
    • Reduces overfitting: Better test accuracy.
    • Faster training: BN allows higher learning rates.
    • Stable training: Smoother loss curves.
    • Dropout: Effectively ensembles many subnetworks.
    • Augmentation expands data cheaply.
    • Early stopping prevents wasteful training.
  6. Disadvantages:
    • Dropout slows convergence and hurts small datasets less than expected.
    • BN: Unstable with small batch sizes.
    • BN has different behaviour in train vs eval (must switch mode).
    • L2 λ must be tuned — too high underfits.
    • Layer Norm needed when batch statistics unreliable.
    • Augmentation must be label-preserving; bad augmentations hurt.
  7. Characteristics:
    • Train vs eval mode: Dropout and BN behave differently.
    • Regularization strength: Higher dropout, higher λ → more regularization.
    • BN has parameters: Learnable γ, β after normalisation.
    • Running statistics: BN stores mean/var for inference.
    • Complementary: Combine BN + Dropout + Augmentation + Early stopping.
    • Task-dependent: Vision → BN + augmentation; NLP → LayerNorm + weight decay.
  8. Diagram: Dropout and BatchNorm
        Dropout (p = 0.5):
    
          Train:                Eval:
          a1 ──✗ (dropped)      a1' = a1 * (1 − p)
          a2 ──✓                a2' = a2 * (1 − p)
          a3 ──✗                a3' = a3 * (1 − p)
          a4 ──✓
          (each node dropped independently)
    
        BatchNorm:
    
          For each mini-batch:
            μ  = mean(x)
            σ² = var(x)
            x̂  = (x − μ) / √(σ² + ε)
            y  = γ·x̂ + β     (γ, β learnable)
    
        Training:
          uses batch statistics
    
        Inference:
          uses running mean/var stored during training
  9. Conclusion: Regularization and normalization are what make deep networks generalize rather than memorise. Dropout, weight decay, augmentation, and early stopping fight overfitting; BN and LayerNorm fight unstable training. The recipes differ by domain: CNNs love BN + augmentation + dropout; Transformers use LayerNorm + weight decay + no dropout in some blocks; RNNs benefit from LayerNorm + gradient clipping. When a model overfits, add regularization; when training is unstable, add normalization; when data is small, add augmentation and reduce capacity.
  10. Exercise:
    1. Compare training with and without Dropout on CIFAR-10.
    2. Add BatchNorm and observe how the learning rate can be increased.
    3. Show the difference in behaviour of Dropout in train vs eval mode.
    4. Explain why Layer Norm is preferred in Transformers over Batch Norm.
    5. List three label-preserving augmentations for images.

हिंदी (सरल)

  1. समस्या: Deep networks में लाखों parameters होते हैं और वे training set को memorise कर सकते हैं — training error लगभग शून्य, पर नए data पर खराब performance। यह overfitting है। Internal covariate shift (training के दौरान layers में बदलती distributions) भी learning धीमी और नाज़ुक बनाती है। Regularization techniques और normalization layers दोनों समस्याएँ हल करती हैं।
  2. परिभाषा: Regularization वह कोई भी technique है जो generalization (test performance) improve करती है, training performance नहीं। Dropout training के दौरान कुछ activations को random zero करता है, जिससे network robust बनता है। Batch Normalization (BN) activations को per mini-batch normalize करता है, training stable और तेज़। Layer Normalization sequential analogue है जो Transformers में use होता है।
  3. उदाहरण: Keras और PyTorch में Dropout और BatchNorm:
    # Keras
    from tensorflow.keras import layers
    model = tf.keras.Sequential([
        layers.Dense(256),
        layers.BatchNormalization(),
        layers.Activation('relu'),
        layers.Dropout(0.3),
        layers.Dense(128, activation='relu'),
        layers.Dropout(0.3),
        layers.Dense(10, activation='softmax')
    ])
    
    # PyTorch
    class Net(nn.Module):
        def __init__(self):
            super().__init__()
            self.fc1  = nn.Linear(784, 256)
            self.bn1  = nn.BatchNorm1d(256)
            self.drop = nn.Dropout(0.3)
            self.fc2  = nn.Linear(256, 10)
    
        def forward(self, x):
            x = self.drop(F.relu(self.bn1(self.fc1(x))))
            return self.fc2(x)
  4. प्रकार:

    A. Regularization techniques:

    Technique Idea
    L2 (weight decay) बड़े weights पर penalty (λ·Σw²)
    L1 |w| पर penalty; sparsity encourage
    Dropout Training में activations random drop
    Data augmentation ज़्यादा diverse training data
    Early stopping Val loss बढ़ने पर रोक दें
    Label smoothing One-hot targets soften
    Ensembling कई models combine
    Dropout variants Spatial Dropout, DropBlock, Stochastic Depth

    B. Normalization layers: Batch Norm, Layer Norm, Group Norm, Instance Norm, RMS Norm।

    C. कहाँ लगाएँ:

    • Convolutional nets: Conv → BN → ReLU → Dropout।
    • Transformers: Linear → LayerNorm (pre-norm)।
    • RNNs: Layer Norm common; Batch Norm कम।
  5. लाभ:
    • Overfitting कम: Better test accuracy।
    • तेज़ training: BN higher learning rates allow।
    • Stable training: Smoother loss curves।
    • Dropout: कई subnetworks का ensemble।
    • Augmentation data सस्ते में expand।
    • Early stopping wasteful training रोकता है।
  6. नुकसान:
    • Dropout convergence धीमा करता है।
    • BN: छोटे batch sizes पर unstable।
    • BN train vs eval में अलग behave (mode switch ज़रूरी)।
    • L2 λ tune करना पड़ता है — बहुत high → underfit।
    • Layer Norm जब batch stats unreliable।
    • Augmentation label-preserving हो; खराब augmentations नुकसान।
  7. विशेषताएँ:
    • Train vs eval mode: Dropout और BN अलग behave।
    • Regularization strength: Higher dropout, higher λ → ज़्यादा regularization।
    • BN के parameters: Normalisation के बाद learnable γ, β।
    • Running statistics: BN inference के लिए mean/var store।
    • Complementary: BN + Dropout + Augmentation + Early stopping combine।
    • Task-dependent: Vision → BN + augmentation; NLP → LayerNorm + weight decay।
  8. आरेख: Dropout और BatchNorm
        Dropout (p = 0.5):
    
          Train:                Eval:
          a1 ──✗ (dropped)      a1' = a1 * (1 − p)
          a2 ──✓                a2' = a2 * (1 − p)
          a3 ──✗                a3' = a3 * (1 − p)
          a4 ──✓
          (हर node independently drop)
    
        BatchNorm:
    
          हर mini-batch के लिए:
            μ  = mean(x)
            σ² = var(x)
            x̂  = (x − μ) / √(σ² + ε)
            y  = γ·x̂ + β     (γ, β learnable)
    
        Training:
          batch statistics use
    
        Inference:
          training में stored running mean/var use
  9. निष्कर्ष: Regularization और normalization ही deep networks को memorise के बजाय generalize कराते हैं। Dropout, weight decay, augmentation और early stopping overfitting से लड़ते हैं; BN और LayerNorm unstable training से। Recipes domain से बदलती हैं: CNNs को BN + augmentation + dropout पसंद; Transformers LayerNorm + weight decay use; RNNs LayerNorm + gradient clipping से फायदा। जब model overfit करे — regularization जोड़ें; training unstable हो — normalization जोड़ें; data छोटा हो — augmentation और capacity घटाएँ।
  10. अभ्यास:
    1. CIFAR-10 पर Dropout के साथ और बिना training compare कीजिए।
    2. BatchNorm जोड़कर देखें learning rate कैसे बढ़ सकती है।
    3. Dropout का train vs eval behaviour दिखाइए।
    4. Transformers में Batch Norm के बजाय Layer Norm क्यों prefer होता है समझाइए।
    5. Images के लिए तीन label-preserving augmentations list कीजिए।

6. Convolutional Neural Networks (CNN)

English

  1. Problem: Feeding raw pixels into a fully connected network on even a modest image is impractical. A 224×224×3 colour image has 150,528 inputs; a single dense layer with 1,000 units would have 150 million weights — huge memory and compute. Worse, fully connected layers ignore spatial structure: shifting a cat by 2 pixels changes the input completely. Images need a network that exploits locality, translation invariance, and weight sharing.
  2. Definition: A Convolutional Neural Network (CNN) is a neural architecture that uses convolutional layers to learn spatial hierarchies. Each layer applies a set of small learnable filters (kernels) that slide over the input, producing feature maps. Key operations: convolution, non-linear activation, pooling, and finally fully connected classification heads.
  3. Example: A small CNN in PyTorch:
    import torch, torch.nn as nn, torch.nn.functional as F
    
    class SmallCNN(nn.Module):
        def __init__(self, n_classes=10):
            super().__init__()
            self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
            self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
            self.pool  = nn.MaxPool2d(2)
            self.fc1   = nn.Linear(64 * 8 * 8, 128)
            self.fc2   = nn.Linear(128, n_classes)
    
        def forward(self, x):
            x = self.pool(F.relu(self.conv1(x)))   # 32×32 → 16×16
            x = self.pool(F.relu(self.conv2(x)))   # 16×16 → 8×8
            x = x.flatten(1)
            x = F.relu(self.fc1(x))
            return self.fc2(x)
    
    # model = SmallCNN()
    # print(model)
  4. Types:

    A. Core layers:

    Layer Purpose
    Convolution Learn local features; weights shared across space
    Activation (ReLU) Non-linearity
    Pooling (max/avg) Downsample; translation invariance
    Global Average Pooling Reduce spatial dims to 1×1
    Fully connected Classification / regression head
    Batch Norm Stabilise and accelerate
    Dropout Regularize classification head

    B. Convolution variants: 1×1, 3×3, 5×5, 7×7; stride; dilated (atrous); transposed (deconvolution); depthwise separable.

    C. Padding modes: 'valid' (no padding), 'same' (output = input size).

  5. Advantages:
    • Weight sharing reduces parameters dramatically.
    • Translation invariance — same feature detected anywhere.
    • Hierarchical features — edges → textures → parts → objects.
    • Local receptive fields match image statistics.
    • Well-understood and heavily optimised.
    • Transfer learning — pretrained CNNs work on many tasks.
  6. Disadvantages:
    • Fixed input size for fully connected heads.
    • Not rotation invariant by default (needs augmentation).
    • Compute-heavy for high-resolution inputs.
    • Not ideal for sequences of variable length (RNNs/Transformers better).
    • Requires large data unless using pretrained models.
    • Interpretation — visualising filters helps but is limited.
  7. Characteristics:
    • Local connectivity: Each neuron sees only a small region.
    • Parameter sharing: Same filter across all positions.
    • Receptive field grows with depth.
    • Pooling reduces resolution, increases field.
    • Padding and stride control output dimensions.
    • Channel dimension separates filters (features).
  8. Diagram: Convolution operation
        Input (5×5)              Filter (3×3)         Output (3×3)
        1 0 1 0 0                1 0 1               5 4 4
        0 1 1 1 0      *         0 1 0        =      4 4 5
        1 0 1 0 1                1 0 1               4 5 5
        0 1 1 1 0
        1 0 1 0 0
    
        Filter slides over input; at each position:
          output[i,j] = Σ input[i+m, j+n] * filter[m,n] + bias
    
        Pooling (2×2 max):
    
        1 3 | 2 4
        5 6 | 7 8       →   6  8
        ----+----
        1 2 | 3 4
        5 7 | 8 9       →   7  9
    
        Typical CNN block:
    
          Input → Conv → BN → ReLU → Pool → ... → Flatten → FC → Softmax
  9. Conclusion: CNNs are the workhorse of computer vision. Their power comes from three inductive biases: locality, translation invariance, and parameter sharing. These match the statistics of natural images and dramatically reduce the number of parameters. Modern CNNs use 3×3 filters, batch norm, residual connections, and data augmentation. Even with the rise of Vision Transformers, CNNs remain state-of-the-art for many tasks and are frequently used as feature extractors in larger systems.
  10. Exercise:
    1. Compute the output size of a conv layer for input 32×32, kernel 3×3, stride 1, padding 1.
    2. Implement a small CNN in PyTorch and train on CIFAR-10.
    3. Compare max-pooling and average-pooling on the same network.
    4. Explain how 1×1 convolutions reduce channels.
    5. Visualise the first-layer filters of a trained CNN.

हिंदी (सरल)

  1. समस्या: Even एक modest image को fully connected network में raw pixels की तरह feed करना impractical है। 224×224×3 colour image में 150,528 inputs होते हैं; 1,000 units वाली एक dense layer में 150 million weights — बहुत memory और compute। बदतर, fully connected layers spatial structure ignore करती हैं: cat को 2 pixels shift करने से input पूरी तरह बदल जाता है। Images को ऐसा network चाहिए जो locality, translation invariance और weight sharing use करे।
  2. परिभाषा: Convolutional Neural Network (CNN) वह neural architecture है जो spatial hierarchies सीखने के लिए convolutional layers use करती है। हर layer छोटे learnable filters (kernels) input पर slide करती है और feature maps बनाती है। मुख्य operations: convolution, non-linear activation, pooling, और अंत में fully connected classification heads।
  3. उदाहरण: PyTorch में छोटा CNN:
    import torch, torch.nn as nn, torch.nn.functional as F
    
    class SmallCNN(nn.Module):
        def __init__(self, n_classes=10):
            super().__init__()
            self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
            self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
            self.pool  = nn.MaxPool2d(2)
            self.fc1   = nn.Linear(64 * 8 * 8, 128)
            self.fc2   = nn.Linear(128, n_classes)
    
        def forward(self, x):
            x = self.pool(F.relu(self.conv1(x)))   # 32×32 → 16×16
            x = self.pool(F.relu(self.conv2(x)))   # 16×16 → 8×8
            x = x.flatten(1)
            x = F.relu(self.fc1(x))
            return self.fc2(x)
    
    # model = SmallCNN()
    # print(model)
  4. प्रकार:

    A. Core layers:

    Layer उद्देश्य
    Convolution Local features सीखें; weights space पर shared
    Activation (ReLU) Non-linearity
    Pooling (max/avg) Downsample; translation invariance
    Global Average Pooling Spatial dims को 1×1 तक
    Fully connected Classification / regression head
    Batch Norm Stabilise और accelerate
    Dropout Classification head regularize

    B. Convolution variants: 1×1, 3×3, 5×5, 7×7; stride; dilated (atrous); transposed (deconvolution); depthwise separable।

    C. Padding modes: 'valid' (कोई padding नहीं), 'same' (output = input size)।

  5. लाभ:
    • Weight sharing parameters dramatically घटाता है।
    • Translation invariance — same feature कहीं भी detect।
    • Hierarchical features — edges → textures → parts → objects।
    • Local receptive fields image statistics से मेल।
    • Well-understood और heavily optimised।
    • Transfer learning — pretrained CNNs कई tasks पर।
  6. नुकसान:
    • Fixed input size fully connected heads के लिए।
    • Rotation invariant नहीं by default (augmentation चाहिए)।
    • Compute-heavy high-resolution inputs पर।
    • Sequences के लिए ideal नहीं (RNNs/Transformers बेहतर)।
    • Large data चाहिए जब तक pretrained models न हों।
    • Interpretation — filters visualise करने से limited मदद।
  7. विशेषताएँ:
    • Local connectivity: हर neuron छोटा region देखता है।
    • Parameter sharing: वही filter हर position पर।
    • Receptive field depth के साथ बढ़ता है।
    • Pooling resolution घटाता, field बढ़ाता है।
    • Padding और stride output dimensions control।
    • Channel dimension filters (features) को अलग रखता है।
  8. आरेख: Convolution operation
        Input (5×5)              Filter (3×3)         Output (3×3)
        1 0 1 0 0                1 0 1               5 4 4
        0 1 1 1 0      *         0 1 0        =      4 4 5
        1 0 1 0 1                1 0 1               4 5 5
        0 1 1 1 0
        1 0 1 0 0
    
        Filter input पर slide करता है; हर position पर:
          output[i,j] = Σ input[i+m, j+n] * filter[m,n] + bias
    
        Pooling (2×2 max):
    
        1 3 | 2 4
        5 6 | 7 8       →   6  8
        ----+----
        1 2 | 3 4
        5 7 | 8 9       →   7  9
    
        Typical CNN block:
    
          Input → Conv → BN → ReLU → Pool → ... → Flatten → FC → Softmax
  9. निष्कर्ष: CNNs computer vision के workhorse हैं। ताकत तीन inductive biases से: locality, translation invariance और parameter sharing। ये natural images की statistics से मेल खाते हैं और parameters dramatically घटाते हैं। Modern CNNs 3×3 filters, batch norm, residual connections और data augmentation use करती हैं। Vision Transformers के उभरने के बावजूद, CNNs कई tasks पर state-of-the-art हैं और बड़े systems में feature extractors की तरह use होती हैं।
  10. अभ्यास:
    1. Input 32×32, kernel 3×3, stride 1, padding 1 के लिए conv layer का output size compute कीजिए।
    2. PyTorch में छोटा CNN implement करके CIFAR-10 पर train कीजिए।
    3. Max-pooling और average-pooling compare कीजिए।
    4. 1×1 convolutions channels कैसे घटाते हैं समझाइए।
    5. Trained CNN के first-layer filters visualise कीजिए।

7. CNN Architectures (LeNet to ResNet)

English

  1. Problem: Designing a CNN from scratch is hard — how many layers, how many filters, where to pool? As datasets and GPUs grew, the community discovered which patterns work. Studying the historical architectures teaches principles that still guide modern design: deeper is better (up to a point), residual connections fix degradation, and 3×3 convolutions are efficient.
  2. Definition: Landmark CNN architectures define the design patterns that dominate image classification. Each introduces a key idea: LeNet (convolutional stacking), AlexNet (deep + ReLU + dropout + GPUs), VGG (uniform 3×3 stacks), GoogLeNet/Inception (multi-scale + 1×1 bottlenecks), ResNet (residual connections), DenseNet (dense connectivity), MobileNet (depthwise separable for mobile), EfficientNet (compound scaling).
  3. Example: Using pretrained models in PyTorch:
    import torchvision.models as models
    import torch.nn as nn
    
    # Load a pretrained ResNet-50
    model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
    
    # Replace the classifier head for 10 classes
    model.fc = nn.Linear(model.fc.in_features, 10)
    
    # Now train just the head (transfer learning)
  4. Types:
    Architecture Year Key Idea Depth
    LeNet-5 1998 First successful CNN for digits 7
    AlexNet 2012 ReLU, dropout, GPU training 8
    VGG-16/19 2014 Uniform 3×3 conv stacks 16/19
    GoogLeNet/Inception 2014 Multi-scale Inception blocks, 1×1 bottlenecks 22
    ResNet-50/101/152 2015 Residual (skip) connections 50–152
    DenseNet 2016 Dense connections (concat) 121–264
    MobileNet 2017 Depthwise separable convs for mobile ~28
    EfficientNet 2019 Compound scaling (depth × width × resolution) B0–B7
    ConvNeXt 2022 Modernise ResNet with transformer tricks ~50–200
  5. Advantages:
    • Reuse: Pretrained models work on new tasks with little data.
    • Known good defaults: Saves weeks of architecture search.
    • Efficiency: Modern architectures are faster and more accurate.
    • Deployment: MobileNet/EfficientNet work on phones.
    • Interpretable evolution: Each generation solves a specific problem.
  6. Disadvantages:
    • Large models need serious compute (VGG has 138M parameters).
    • Diminishing returns: Deeper isn't always better.
    • Pretrained bias: ImageNet features may not transfer to very different domains (medical, satellite).
    • Licensing: Some pretrained weights restrict commercial use.
    • Overfitting if the head is not properly regularized.
  7. Characteristics:
    • Depth matters up to a point (degradation solved by residual).
    • 3×3 convolutions are the sweet spot (VGG principle).
    • 1×1 convolutions are channel mixers (Inception, ResNet bottlenecks).
    • Skip connections enable gradient flow in deep nets.
    • Global average pooling replaces huge FC layers.
    • Compound scaling balances depth, width, resolution.
  8. Diagram: Residual block and depth comparison
        Residual (skip) block:
    
               x
               │
          ┌────┴────┐
          │  Conv   │
          │  BN     │
          │  ReLU   │
          │  Conv   │
          │  BN     │
          └────┬────┘
               │
               ▼
            x + F(x)  → ReLU  → output
               ▲
               │  (identity shortcut)
    
        Depth vs error (conceptually):
    
          Plain net  ──  deeper after ~20 layers, error rises
          ResNet     ──  deeper helps → 50, 101, 152, ...
    
        Parameter comparison:
    
          VGG-16       138M parameters
          ResNet-50     25M parameters
          MobileNet      4M parameters
  9. Conclusion: Studying CNN architectures is studying the history of ideas: ReLU, dropout, small filters, bottlenecks, residual connections, depthwise separable convolutions, and compound scaling. Modern practice: start from a pretrained model (ResNet, EfficientNet, ConvNeXt) instead of training from scratch. Replace the head, freeze the backbone for small datasets, fine-tune the whole network when you have enough data. Even in the Transformer era, these CNNs remain the best choice for many vision tasks.
  10. Exercise:
    1. Draw ResNet's residual block and explain why it helps.
    2. Compare VGG-16 and ResNet-50 in parameters and accuracy.
    3. Load a pretrained EfficientNet and fine-tune on a small dataset.
    4. Explain the role of 1×1 convolutions in Inception and ResNet bottlenecks.
    5. Describe depthwise separable convolutions from MobileNet.

हिंदी (सरल)

  1. समस्या: CNN scratch से design करना मुश्किल है — कितनी layers, कितने filters, कहाँ pool? जैसे-जैसे datasets और GPUs बढ़े, community ने खोजा कि कौन से patterns काम करते हैं। Historical architectures पढ़ना वे principles सिखाता है जो आज भी modern design guide करते हैं: deeper better (एक हद तक), residual connections degradation fix करते हैं, और 3×3 convolutions efficient हैं।
  2. परिभाषा: Landmark CNN architectures वे design patterns define करती हैं जो image classification में dominante हैं। हर एक key idea introduce करती है: LeNet (convolutional stacking), AlexNet (deep + ReLU + dropout + GPUs), VGG (uniform 3×3 stacks), GoogLeNet/Inception (multi-scale + 1×1 bottlenecks), ResNet (residual connections), DenseNet (dense connectivity), MobileNet (depthwise separable for mobile), EfficientNet (compound scaling)।
  3. उदाहरण: PyTorch में pretrained models:
    import torchvision.models as models
    import torch.nn as nn
    
    # Pretrained ResNet-50 load
    model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
    
    # 10 classes के लिए classifier head बदलें
    model.fc = nn.Linear(model.fc.in_features, 10)
    
    # अब सिर्फ head train करें (transfer learning)
  4. प्रकार:
    Architecture Year Key Idea Depth
    LeNet-5 1998 पहला successful CNN for digits 7
    AlexNet 2012 ReLU, dropout, GPU training 8
    VGG-16/19 2014 Uniform 3×3 conv stacks 16/19
    GoogLeNet/Inception 2014 Multi-scale Inception, 1×1 bottlenecks 22
    ResNet-50/101/152 2015 Residual (skip) connections 50–152
    DenseNet 2016 Dense connections (concat) 121–264
    MobileNet 2017 Depthwise separable convs for mobile ~28
    EfficientNet 2019 Compound scaling (depth × width × resolution) B0–B7
    ConvNeXt 2022 Transformer tricks से ResNet modernise ~50–200
  5. लाभ:
    • Reuse: Pretrained models नए tasks पर थोड़े data से।
    • Known good defaults: Architecture search के हफ्ते बचत।
    • Efficiency: Modern architectures तेज़ और accurate।
    • Deployment: MobileNet/EfficientNet phones पर।
    • Interpretable evolution: हर generation एक समस्या हल करती है।
  6. नुकसान:
    • बड़े models serious compute (VGG में 138M parameters)।
    • Diminishing returns: Deeper हमेशा better नहीं।
    • Pretrained bias: ImageNet features हर domain पर transfer न हों (medical, satellite)।
    • Licensing: कुछ pretrained weights commercial use restrict।
    • Overfitting अगर head properly regularize न हो।
  7. विशेषताएँ:
    • Depth matters एक हद तक (degradation residual से fix)।
    • 3×3 convolutions sweet spot (VGG principle)।
    • 1×1 convolutions channel mixers (Inception, ResNet bottlenecks)।
    • Skip connections deep nets में gradient flow।
    • Global average pooling बड़ी FC layers की जगह।
    • Compound scaling depth, width, resolution balance।
  8. आरेख: Residual block और depth comparison
        Residual (skip) block:
    
               x
               │
          ┌────┴────┐
          │  Conv   │
          │  BN     │
          │  ReLU   │
          │  Conv   │
          │  BN     │
          └────┬────┘
               │
               ▼
            x + F(x)  → ReLU  → output
               ▲
               │  (identity shortcut)
    
        Depth vs error (conceptually):
    
          Plain net  ──  ~20 layers के बाद deeper, error बढ़
          ResNet     ──  deeper helps → 50, 101, 152, ...
    
        Parameter comparison:
    
          VGG-16       138M parameters
          ResNet-50     25M parameters
          MobileNet      4M parameters
  9. निष्कर्ष: CNN architectures पढ़ना ideas के इतिहास को पढ़ना है: ReLU, dropout, छोटे filters, bottlenecks, residual connections, depthwise separable convolutions और compound scaling। Modern practice: scratch से train करने के बजाय pretrained model (ResNet, EfficientNet, ConvNeXt) से शुरू करें। Head बदलें, छोटे datasets पर backbone freeze, पर्याप्त data पर पूरा fine-tune। Transformer युग में भी ये CNNs कई vision tasks के लिए best choice हैं।
  10. अभ्यास:
    1. ResNet का residual block draw करें और बताइए यह क्यों मदद करता है।
    2. VGG-16 और ResNet-50 parameters और accuracy में compare कीजिए।
    3. Pretrained EfficientNet load करके छोटे dataset पर fine-tune कीजिए।
    4. Inception और ResNet bottlenecks में 1×1 convolutions की भूमिका समझाइए।
    5. MobileNet की depthwise separable convolutions describe कीजिए।

8. Recurrent Neural Networks (RNN)

English

  1. Problem: CNNs and MLPs assume fixed-size inputs. But sequences — text, audio, time series — have variable length and temporal order. "dog bites man" is different from "man bites dog". We need a network that processes data step by step, remembers previous information, and shares parameters across time steps.
  2. Definition: A Recurrent Neural Network (RNN) is a network with loops: at each time step t, it takes an input xₜ and its own previous hidden state hₜ₋₁, and produces a new hidden state hₜ = f(Wx·xₜ + Wh·hₜ₋₁ + b). The same weights are reused at every step, so the network handles variable-length sequences.
  3. Example: A simple RNN in PyTorch:
    import torch.nn as nn
    
    class RNN(nn.Module):
        def __init__(self, vocab_size, embed=64, hidden=128, n_classes=2):
            super().__init__()
            self.embed = nn.Embedding(vocab_size, embed)
            self.rnn   = nn.RNN(embed, hidden, batch_first=True)
            self.fc    = nn.Linear(hidden, n_classes)
    
        def forward(self, x):
            # x: (batch, seq_len) → embeddings
            e = self.embed(x)
            out, h_n = self.rnn(e)   # h_n = last hidden state
            return self.fc(h_n.squeeze(0))
  4. Types:

    A. Sequence tasks:

    Task Input → Output Example
    One-to-one Fixed → Fixed Image classification
    One-to-many Fixed → Sequence Image captioning
    Many-to-one Sequence → Fixed Sentiment analysis
    Many-to-many (aligned) Sequence → Sequence POS tagging
    Many-to-many (encoder-decoder) Sequence → Sequence Machine translation

    B. RNN variants: Vanilla RNN, Bidirectional RNN, Deep (stacked) RNN, LSTM, GRU, and sequence-to-sequence with attention.

    C. Problems: Vanishing gradients (long-term dependencies lost), exploding gradients, sequential computation (slow), no direct long-range skip.

  5. Advantages:
    • Handles variable-length sequences.
    • Parameter sharing across time reduces parameters.
    • Temporal memory — hidden state carries context.
    • Flexible architecture — many-to-one, many-to-many, etc.
    • Foundation for LSTM, GRU, attention, transformers.
    • Works well on small sequences and simple tasks.
  6. Disadvantages:
    • Vanishing gradients: Forgets long-term dependencies.
    • Exploding gradients: Unstable training; needs clipping.
    • Sequential: Cannot parallelise across time steps.
    • Hard to train on very long sequences.
    • Slower than Transformers on modern hardware.
    • Less expressive than attention for long-range context.
  7. Characteristics:
    • Hidden state: Compressed memory of past.
    • Time-unrolled: Can be drawn as a deep chain.
    • Backprop through time (BPTT): Gradient flows across steps.
    • Truncated BPTT: Limit gradient to a window.
    • Bidirectional: Process sequence forwards and backwards.
    • Encoder-decoder: One RNN encodes, another decodes.
  8. Diagram: RNN unrolled over time
        Folded:                 Unrolled:
    
          ┌──┐             ┌──┐    ┌──┐    ┌──┐    ┌──┐
          │h │──▶ h        │h₀│──▶ │h₁│──▶ │h₂│──▶ │h₃│
          └──┘             └──┘    └──┘    └──┘    └──┘
           ▲                 ▲       ▲       ▲       ▲
           │                 │       │       │       │
           x                 x₀      x₁      x₂      x₃
    
        Same weights Wx, Wh, b at every step.
    
        Vanishing gradient:
    
          Gradient of loss wrt h₀ involves product of
          Wh at each step → repeated multiplication
          shrinks or explodes.
  9. Conclusion: RNNs were the first neural architecture built for sequences. They introduced memory through hidden state and weight sharing across time. But vanilla RNNs suffer from vanishing gradients and cannot remember long contexts. The improvements — LSTM and GRU — solve this with gating, and Transformers replace recurrence entirely with attention. Still, understanding the vanilla RNN is essential: it clarifies why later architectures were invented and how sequence modelling evolved.
  10. Exercise:
    1. Implement a many-to-one RNN for sentiment classification.
    2. Explain with a diagram how BPTT works.
    3. Show empirically that vanilla RNNs forget long-term dependencies.
    4. Compare RNN, LSTM and GRU in one table.
    5. Explain why gradient clipping is used with RNNs.

हिंदी (सरल)

  1. समस्या: CNNs और MLPs fixed-size inputs मानते हैं। पर sequences — text, audio, time series — variable length और temporal order वाली होती हैं। "dog bites man" और "man bites dog" अलग हैं। ऐसा network चाहिए जो step by step data process करे, पिछली जानकारी याद रखे, और time steps पर parameters share करे।
  2. परिभाषा: Recurrent Neural Network (RNN) loops वाला network है: हर time step t पर यह input xₜ और अपना पिछला hidden state hₜ₋₁ लेता है, और नया hidden state बनाता है hₜ = f(Wx·xₜ + Wh·hₜ₋₁ + b)। वही weights हर step पर reuse होते हैं, जिससे network variable-length sequences handle करता है।
  3. उदाहरण: PyTorch में simple RNN:
    import torch.nn as nn
    
    class RNN(nn.Module):
        def __init__(self, vocab_size, embed=64, hidden=128, n_classes=2):
            super().__init__()
            self.embed = nn.Embedding(vocab_size, embed)
            self.rnn   = nn.RNN(embed, hidden, batch_first=True)
            self.fc    = nn.Linear(hidden, n_classes)
    
        def forward(self, x):
            # x: (batch, seq_len) → embeddings
            e = self.embed(x)
            out, h_n = self.rnn(e)   # h_n = last hidden state
            return self.fc(h_n.squeeze(0))
  4. प्रकार:

    A. Sequence tasks:

    Task Input → Output Example
    One-to-one Fixed → Fixed Image classification
    One-to-many Fixed → Sequence Image captioning
    Many-to-one Sequence → Fixed Sentiment analysis
    Many-to-many (aligned) Sequence → Sequence POS tagging
    Many-to-many (encoder-decoder) Sequence → Sequence Machine translation

    B. RNN variants: Vanilla RNN, Bidirectional RNN, Deep (stacked) RNN, LSTM, GRU, और attention वाला sequence-to-sequence।

    C. Problems: Vanishing gradients (long-term dependencies खो), exploding gradients, sequential computation (slow), कोई direct long-range skip नहीं।

  5. लाभ:
    • Variable-length sequences handle।
    • Parameter sharing time पर parameters कम।
    • Temporal memory — hidden state context रखता है।
    • Flexible architecture — many-to-one, many-to-many, आदि।
    • Foundation LSTM, GRU, attention, transformers के लिए।
    • छोटे sequences और सरल tasks पर अच्छा।
  6. नुकसान:
    • Vanishing gradients: Long-term dependencies भूल जाते हैं।
    • Exploding gradients: Unstable; clipping चाहिए।
    • Sequential: Time steps पर parallelise नहीं।
    • बहुत long sequences पर train करना कठिन।
    • Transformers से slow modern hardware पर।
    • कम expressive long-range context के लिए attention से।
  7. विशेषताएँ:
    • Hidden state: Past की compressed memory।
    • Time-unrolled: Deep chain की तरह draw।
    • Backprop through time (BPTT): Gradient steps के आर-पार।
    • Truncated BPTT: Gradient को window तक सीमित।
    • Bidirectional: Sequence को forwards और backwards।
    • Encoder-decoder: एक RNN encode, दूसरा decode।
  8. आरेख: RNN time पर unrolled
        Folded:                 Unrolled:
    
          ┌──┐             ┌──┐    ┌──┐    ┌──┐    ┌──┐
          │h │──▶ h        │h₀│──▶ │h₁│──▶ │h₂│──▶ │h₃│
          └──┘             └──┘    └──┘    └──┘    └──┘
           ▲                 ▲       ▲       ▲       ▲
           │                 │       │       │       │
           x                 x₀      x₁      x₂      x₃
    
        Same weights Wx, Wh, b हर step पर।
    
        Vanishing gradient:
    
          h₀ के सापेक्ष loss का gradient में हर step
          पर Wh का product → repeated multiplication
          छोटा या बड़ा हो जाता है।
  9. निष्कर्ष: RNNs sequences के लिए बनी पहली neural architecture थीं। उन्होंने hidden state से memory और time पर weight sharing दी। पर vanilla RNNs vanishing gradients से परेशान हैं और लंबे contexts याद नहीं रख पातीं। Improvements — LSTM और GRU — gating से इसे हल करती हैं, और Transformers recurrence को पूरी तरह attention से बदल देते हैं। फिर भी vanilla RNN समझना essential है: यह साफ करता है कि आगे की architectures क्यों बनीं और sequence modelling कैसे विकसित हुई।
  10. अभ्यास:
    1. Sentiment classification के लिए many-to-one RNN implement कीजिए।
    2. Diagram के साथ BPTT कैसे काम करता है समझाइए।
    3. Empirically दिखाइए कि vanilla RNN long-term dependencies भूल जाते हैं।
    4. RNN, LSTM और GRU एक table में compare कीजिए।
    5. RNNs के साथ gradient clipping क्यों use होता है समझाइए।

9. LSTM & GRU

English

  1. Problem: Vanilla RNNs forget information after a few time steps because the gradient vanishes through repeated multiplications of the recurrent weight matrix. Tasks like machine translation, language modelling, and long-document summarisation need the network to remember context from hundreds or thousands of steps ago. A new recurrent unit was needed with explicit memory and gating.
  2. Definition: Long Short-Term Memory (LSTM) is a recurrent unit with a cell state (long-term memory) and three gates (input, forget, output) that control what to write, keep, and read. Gated Recurrent Unit (GRU) is a simpler variant with two gates (update, reset) that often performs similarly with fewer parameters.
  3. Example: LSTM/GRU in PyTorch:
    import torch.nn as nn
    
    class SentimentLSTM(nn.Module):
        def __init__(self, vocab_size, embed=128, hidden=256, n_classes=2):
            super().__init__()
            self.embed = nn.Embedding(vocab_size, embed)
            self.lstm  = nn.LSTM(embed, hidden, num_layers=2,
                                 batch_first=True, bidirectional=True,
                                 dropout=0.3)
            self.fc    = nn.Linear(hidden * 2, n_classes)
    
        def forward(self, x):
            e = self.embed(x)
            out, (h, c) = self.lstm(e)
            # take last timestep output (both directions concatenated)
            return self.fc(out[:, -1, :])
    
    # Replace LSTM with nn.GRU for GRU variant.
  4. Types:

    A. LSTM gates:

    Gate Role
    Forget gate (f) Decide what to discard from cell state
    Input gate (i) Decide what new info to write
    Output gate (o) Decide what to expose as hidden state
    Cell state (C) Long-term memory; changes slowly
    Hidden state (h) Short-term memory; output

    B. GRU gates:

    • Update gate (z): Combines forget + input from LSTM.
    • Reset gate (r): Controls how much past to forget.
    • No separate cell state: Simpler, faster.

    C. Variants: BiLSTM, BiGRU, stacked LSTM/GRU, peephole LSTM, ConvLSTM (for video), attention-augmented LSTM.

  5. Advantages:
    • Long-term memory: Cell state preserves info across many steps.
    • Gating: Learns what to remember and forget.
    • Stable gradients: Additive cell state updates combat vanishing.
    • GRU: Fewer parameters, faster training, similar performance.
    • Proven: Strong baseline in speech, NLP, and time series.
    • Handles variable length and sequential data naturally.
  6. Disadvantages:
    • Slow to train: Sequential dependency limits parallelisation.
    • LSTM is complex: More gates and parameters than GRU.
    • Transformers now dominate long-sequence tasks.
    • Memory hungry for very long sequences.
    • Not ideal for very long contexts — attention handles them better.
    • Hyperparameter sensitivity — layers, hidden size, dropout matter.
  7. Characteristics:
    • Cell state: Highway for gradient flow (LSTM).
    • Gating mechanism: Multiplicative interactions.
    • Sigmoid + tanh: Sigmoid for gates, tanh for candidate values.
    • Bidirectional: Context from both past and future.
    • GRU simplified: Two gates; merged cell and hidden.
    • Foundation for Seq2Seq: Pre-Transformer translation used LSTM + attention.
  8. Diagram: LSTM cell
        LSTM cell (simplified):
    
                    C_{t-1} ──────────────────────► C_t
                       │  │                    ▲
                       │  │  ┌────┐            │
                       │  └─▶│ f  │───┐        │
                       │     └────┘   │        │
                       │     ┌────┐   │  ┌───┐ │
                       │  ┌─▶│ i  │───┼─▶│ × │ │
                       │  │  └────┘   │  └───┘ │
                       │  │  ┌────┐   │        │
                       │  └─▶│ c̃ │───┘        │
                       │     └────┘            │
                       │                        │
                       │     ┌────┐   ┌───┐    │
                       │  ┌─▶│ o  │──▶│ × │────┘
                       │  │  └────┘   └───┘
                       │  │             │
                       │  │             ▼
                       │  │            h_t
                       │  │
                       x_t, h_{t-1} ────┘
    
        GRU cell (simplified):
    
          z = σ(Wz·[h_{t-1}, x_t])       update
          r = σ(Wr·[h_{t-1}, x_t])       reset
          h̃ = tanh(W·[r * h_{t-1}, x_t])
          h_t = (1 − z)*h_{t-1} + z*h̃
  9. Conclusion: LSTMs and GRUs were the workhorses of sequence modelling before Transformers. Their cell state and gating solved the vanishing gradient problem and made long-context learning practical. GRUs trade a little capacity for speed and simplicity. Today, Transformers dominate NLP, but LSTMs and GRUs remain excellent choices for small datasets, on-device inference, time series forecasting, and speech systems. Understanding gates is essential to understanding how sequence memory works.
  10. Exercise:
    1. Write an LSTM for text classification on the IMDB dataset.
    2. Replace LSTM with GRU and compare training time and accuracy.
    3. Explain how the cell state helps gradients flow during BPTT.
    4. Use a BiLSTM for named-entity recognition.
    5. Compare LSTM, GRU, and Transformer on a small translation task.

हिंदी (सरल)

  1. समस्या: Vanilla RNNs कुछ time steps के बाद information भूल जाते हैं क्योंकि recurrent weight matrix के repeated multiplications से gradient vanish हो जाता है। Machine translation, language modelling और long-document summarisation जैसे tasks के लिए network को सैकड़ों-हजारों steps पहले का context याद रखना होता है। Explicit memory और gating वाली नई recurrent unit चाहिए थी।
  2. परिभाषा: Long Short-Term Memory (LSTM) वह recurrent unit है जिसमें cell state (long-term memory) और तीन gates (input, forget, output) होते हैं जो तय करते हैं क्या लिखें, क्या रखें, क्या पढ़ें। Gated Recurrent Unit (GRU) सरल variant है जिसमें दो gates (update, reset) होते हैं और अक्सर कम parameters में समान performance देता है।
  3. उदाहरण: PyTorch में LSTM/GRU:
    import torch.nn as nn
    
    class SentimentLSTM(nn.Module):
        def __init__(self, vocab_size, embed=128, hidden=256, n_classes=2):
            super().__init__()
            self.embed = nn.Embedding(vocab_size, embed)
            self.lstm  = nn.LSTM(embed, hidden, num_layers=2,
                                 batch_first=True, bidirectional=True,
                                 dropout=0.3)
            self.fc    = nn.Linear(hidden * 2, n_classes)
    
        def forward(self, x):
            e = self.embed(x)
            out, (h, c) = self.lstm(e)
            # last timestep output (दोनों directions concatenated)
            return self.fc(out[:, -1, :])
    
    # GRU variant के लिए nn.LSTM को nn.GRU से बदलें।
  4. प्रकार:

    A. LSTM gates:

    Gate Role
    Forget gate (f) Cell state से क्या हटाएँ
    Input gate (i) क्या नई info लिखें
    Output gate (o) Hidden state में क्या expose करें
    Cell state (C) Long-term memory; धीरे बदलती है
    Hidden state (h) Short-term memory; output

    B. GRU gates:

    • Update gate (z): LSTM के forget + input को combine।
    • Reset gate (r): Past से कितना भूलें।
    • अलग cell state नहीं: सरल, तेज़।

    C. Variants: BiLSTM, BiGRU, stacked LSTM/GRU, peephole LSTM, ConvLSTM (video के लिए), attention-augmented LSTM।

  5. लाभ:
    • Long-term memory: Cell state कई steps तक info रखती है।
    • Gating: क्या याद रखें और भूलें — सीखती है।
    • Stable gradients: Additive cell state updates vanishing से लड़ते हैं।
    • GRU: कम parameters, तेज़ training, समान performance।
    • Proven: Speech, NLP और time series में strong baseline।
    • Variable length और sequential data naturally handle।
  6. नुकसान:
    • Slow to train: Sequential dependency parallelisation रोकती है।
    • LSTM complex: GRU से ज़्यादा gates और parameters।
    • Transformers अब long-sequence tasks पर dominante।
    • Memory hungry बहुत long sequences पर।
    • बहुत long contexts के लिए ideal नहीं — attention बेहतर।
    • Hyperparameter sensitivity — layers, hidden size, dropout matter।।
  7. विशेषताएँ:
    • Cell state: Gradient flow का highway (LSTM)।
    • Gating mechanism: Multiplicative interactions।
    • Sigmoid + tanh: Gates के लिए sigmoid, candidates के लिए tanh।
    • Bidirectional: Past और future दोनों से context।
    • GRU simplified: दो gates; cell और hidden merge।
    • Seq2Seq की नींव: Pre-Transformer translation LSTM + attention use करती थी।
  8. आरेख: LSTM cell
        LSTM cell (सरलीकृत):
    
                    C_{t-1} ──────────────────────► C_t
                       │  │                    ▲
                       │  │  ┌────┐            │
                       │  └─▶│ f  │───┐        │
                       │     └────┘   │        │
                       │     ┌────┐   │  ┌───┐ │
                       │  ┌─▶│ i  │───┼─▶│ × │ │
                       │  │  └────┘   │  └───┘ │
                       │  │  ┌────┐   │        │
                       │  └─▶│ c̃ │───┘        │
                       │     └────┘            │
                       │                        │
                       │     ┌────┐   ┌───┐    │
                       │  ┌─▶│ o  │──▶│ × │────┘
                       │  │  └────┘   └───┘
                       │  │             │
                       │  │             ▼
                       │  │            h_t
                       │  │
                       x_t, h_{t-1} ────┘
    
        GRU cell (सरलीकृत):
    
          z = σ(Wz·[h_{t-1}, x_t])       update
          r = σ(Wr·[h_{t-1}, x_t])       reset
          h̃ = tanh(W·[r * h_{t-1}, x_t])
          h_t = (1 − z)*h_{t-1} + z*h̃
  9. निष्कर्ष: LSTMs और GRUs Transformers से पहले sequence modelling के workhorses थे। उनका cell state और gating vanishing gradient problem हल करते हैं और long-context learning practical बनाते हैं। GRUs capacity का थोड़ा हिस्सा speed और simplicity से trade करते हैं। आज NLP पर Transformers dominante, पर LSTMs और GRUs छोटे datasets, on-device inference, time series forecasting और speech systems के लिए excellent choices हैं। Gates समझना sequence memory समझने के लिए essential है।
  10. अभ्यास:
    1. IMDB dataset पर text classification के लिए LSTM लिखिए।
    2. LSTM को GRU से replace करके training time और accuracy compare कीजिए।
    3. BPTT के दौरान cell state gradients कैसे help करता है समझाइए।
    4. Named-entity recognition के लिए BiLSTM use कीजिए।
    5. छोटे translation task पर LSTM, GRU और Transformer compare कीजिए।

10. Attention & Transformers

English

  1. Problem: RNNs process sequences one step at a time and compress the past into a fixed-size hidden state. For long sequences, this bottleneck loses information, and training cannot parallelise. Machine translation on long sentences was slow and lossy. A mechanism was needed that lets the model look at all past positions at once, focus on the relevant ones, and process sequences in parallel.
  2. Definition: Attention computes a weighted sum of value vectors, where weights come from the similarity between a query and a set of keys. Self-attention uses the same sequence for queries, keys, and values. Multi-head attention runs several attentions in parallel with different learned projections. The Transformer is an architecture built entirely from attention plus feedforward layers, with no recurrence.
  3. Example: Self-attention in PyTorch:
    import torch, math
    import torch.nn as nn
    
    class SelfAttention(nn.Module):
        def __init__(self, dim, heads=8):
            super().__init__()
            self.heads = heads
            self.to_qkv = nn.Linear(dim, dim * 3)
            self.out    = nn.Linear(dim, dim)
    
        def forward(self, x):
            B, T, C = x.shape
            qkv = self.to_qkv(x).chunk(3, dim=-1)
            q, k, v = [t.view(B, T, self.heads, C // self.heads)
                        .transpose(1, 2) for t in qkv]
            # Scaled dot-product attention
            scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
            attn   = scores.softmax(dim=-1)
            out    = (attn @ v).transpose(1, 2).reshape(B, T, C)
            return self.out(out)
  4. Types:

    A. Attention variants:

    Type Idea
    Dot-product attention Score = q · k
    Scaled dot-product Divide by √d to stabilise
    Additive (Bahdanau) Neural network to compute score
    Multi-head Parallel attention with different projections
    Self-attention Q, K, V from the same sequence
    Cross-attention Q from one sequence, K/V from another
    Causal (masked) Future positions masked; used in GPT
    Flash attention IO-aware exact attention; faster, less memory

    B. Transformer block:

    • Multi-Head Self-Attention
    • Add & LayerNorm (residual)
    • Feedforward (2 linear + GELU/ReLU)
    • Add & LayerNorm
    • Optional dropout

    C. Transformer families: Encoder-only (BERT, RoBERTa), Decoder-only (GPT, LLaMA), Encoder-decoder (T5, BART), Vision (ViT, Swin), Multimodal (CLIP, GPT-4V).

  5. Advantages:
    • Parallel training: All positions processed together.
    • Long-range dependencies: Direct connection between any two positions.
    • Scalable: Larger models keep improving (scaling laws).
    • Flexible: Same block works for text, images, audio, video.
    • Pretrained ecosystem: Hugging Face, BERT, GPT, ViT.
    • Interpretable: Attention weights can be visualised.
  6. Disadvantages:
    • Quadratic cost: Attention is O(T²) in sequence length.
    • Data-hungry: Needs massive datasets (or pretraining).
    • Compute-hungry: Training large Transformers is expensive.
    • Position encoding needed (no built-in order).
    • Memory for attention matrices on long sequences.
    • Hallucination: Large language models can generate false content.
  7. Characteristics:
    • Attention: Weighted sum over values using query-key similarity.
    • Multi-head: Each head learns a different relation.
    • Positional encoding: Sinusoidal or learned.
    • LayerNorm: Pre-norm or post-norm variants.
    • Residual connections: Enable deep stacks.
    • Scaling laws: Performance improves with size, data, compute.
  8. Diagram: Self-attention and Transformer block
        Self-attention:
    
          Input X (T × d)
             │
             ├─▶ Q = X·Wq
             ├─▶ K = X·Wk
             └─▶ V = X·Wv
    
          Scores = Q·Kᵀ / √d      (T × T)
          Attn   = softmax(Scores)
          Output = Attn · V       (T × d)
    
        Transformer encoder block:
    
          x ──▶ MultiHeadSelfAttn ──▶ Add & LayerNorm
                  │
                  └── (residual)
                                           │
                                           ▼
                                FeedForward (2 layers)
                                           │
                                           ▼
                                       Add & LayerNorm
                                           │
                                           ▼
                                           y
    
        Decoder adds masked self-attention + cross-attention.
  9. Conclusion: Attention and Transformers are the current frontier of deep learning. Self-attention solved the sequential bottleneck of RNNs and enabled training on enormous datasets. Transformers now power translation, chatbots, code assistants, image recognition, and multimodal models. Their quadratic cost drives research into efficient variants (Flash Attention, Linformer, Performer, Mamba). For practitioners, the dominant pattern is pretrain then fine-tune: start from a pretrained Transformer, adapt to your task, and only pretrain from scratch when you have the data and compute.
  10. Exercise:
    1. Implement scaled dot-product attention from scratch.
    2. Explain why the √d scaling matters.
    3. Compare RNN, LSTM and Transformer on a sequence task.
    4. Fine-tune a pretrained BERT for text classification.
    5. Compute the memory cost of attention for a 4,096-token sequence.

हिंदी (सरल)

  1. समस्या: RNNs sequences को एक step पर process करते हैं और past को fixed-size hidden state में compress करते हैं। Long sequences पर यह bottleneck information खो देता है और training parallelise नहीं होती। Long sentences पर machine translation धीमा और lossy था। ऐसा mechanism चाहिए जो model को सभी past positions एक साथ देखने दे, relevant पर focus करे, और sequences parallel process करे।
  2. परिभाषा: Attention value vectors का weighted sum compute करता है, जहाँ weights query और keys के similarity से आते हैं। Self-attention में queries, keys, values एक ही sequence से। Multi-head attention कई attentions parallel चलाता है अलग learned projections के साथ। Transformer पूरी तरह attention + feedforward layers से बना architecture है, कोई recurrence नहीं।
  3. उदाहरण: PyTorch में self-attention:
    import torch, math
    import torch.nn as nn
    
    class SelfAttention(nn.Module):
        def __init__(self, dim, heads=8):
            super().__init__()
            self.heads = heads
            self.to_qkv = nn.Linear(dim, dim * 3)
            self.out    = nn.Linear(dim, dim)
    
        def forward(self, x):
            B, T, C = x.shape
            qkv = self.to_qkv(x).chunk(3, dim=-1)
            q, k, v = [t.view(B, T, self.heads, C // self.heads)
                        .transpose(1, 2) for t in qkv]
            # Scaled dot-product attention
            scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
            attn   = scores.softmax(dim=-1)
            out    = (attn @ v).transpose(1, 2).reshape(B, T, C)
            return self.out(out)
  4. प्रकार:

    A. Attention variants:

    Type Idea
    Dot-product attention Score = q · k
    Scaled dot-product √d से divide, stabilise
    Additive (Bahdanau) Neural network से score
    Multi-head Parallel attention with different projections
    Self-attention Q, K, V एक ही sequence से
    Cross-attention Q एक sequence से, K/V दूसरे से
    Causal (masked) Future positions mask; GPT में use
    Flash attention IO-aware exact attention; तेज़, कम memory

    B. Transformer block:

    • Multi-Head Self-Attention
    • Add & LayerNorm (residual)
    • Feedforward (2 linear + GELU/ReLU)
    • Add & LayerNorm
    • Optional dropout

    C. Transformer families: Encoder-only (BERT, RoBERTa), Decoder-only (GPT, LLaMA), Encoder-decoder (T5, BART), Vision (ViT, Swin), Multimodal (CLIP, GPT-4V)।

  5. लाभ:
    • Parallel training: सभी positions एक साथ।
    • Long-range dependencies: किन्हीं दो positions के बीच direct connection।
    • Scalable: बड़े models और बेहतर (scaling laws)।
    • Flexible: वही block text, images, audio, video पर।
    • Pretrained ecosystem: Hugging Face, BERT, GPT, ViT।
    • Interpretable: Attention weights visualise।
  6. नुकसान:
    • Quadratic cost: Attention sequence length में O(T²)।
    • Data-hungry: Massive datasets (या pretraining)।
    • Compute-hungry: बड़े Transformers training महँगी।
    • Position encoding चाहिए (built-in order नहीं)।
    • Memory long sequences पर attention matrices।
    • Hallucination: बड़े language models गलत content generate कर सकते हैं।
  7. विशेषताएँ:
    • Attention: Query-key similarity से values का weighted sum।
    • Multi-head: हर head अलग relation सीखता है।
    • Positional encoding: Sinusoidal या learned।
    • LayerNorm: Pre-norm या post-norm variants।
    • Residual connections: Deep stacks enable।
    • Scaling laws: Size, data, compute के साथ performance।
  8. आरेख: Self-attention और Transformer block
        Self-attention:
    
          Input X (T × d)
             │
             ├─▶ Q = X·Wq
             ├─▶ K = X·Wk
             └─▶ V = X·Wv
    
          Scores = Q·Kᵀ / √d      (T × T)
          Attn   = softmax(Scores)
          Output = Attn · V       (T × d)
    
        Transformer encoder block:
    
          x ──▶ MultiHeadSelfAttn ──▶ Add & LayerNorm
                  │
                  └── (residual)
                                           │
                                           ▼
                                FeedForward (2 layers)
                                           │
                                           ▼
                                       Add & LayerNorm
                                           │
                                           ▼
                                           y
    
        Decoder adds masked self-attention + cross-attention।
  9. निष्कर्ष: Attention और Transformers deep learning का current frontier हैं। Self-attention ने RNNs की sequential bottleneck हल की और बहुत बड़े datasets पर training enable की। Transformers अब translation, chatbots, code assistants, image recognition और multimodal models में use होते हैं। उनकी quadratic cost efficient variants (Flash Attention, Linformer, Performer, Mamba) पर research drive कर रही है। Practitioners के लिए dominant pattern है pretrain then fine-tune: pretrained Transformer से शुरू करें, task पर adapt करें, scratch से pretrain सिर्फ तब जब data और compute हो।
  10. अभ्यास:
    1. Scaled dot-product attention scratch से implement कीजिए।
    2. √d scaling क्यों ज़रूरी है समझाइए।
    3. Sequence task पर RNN, LSTM और Transformer compare कीजिए।
    4. Text classification के लिए pretrained BERT fine-tune कीजिए।
    5. 4,096-token sequence पर attention की memory cost compute कीजिए।

11. Autoencoders & Generative Adversarial Networks (GANs)

English

  1. Problem: Supervised learning requires labels. But most of the world's data is unlabelled. We need models that learn representations without labels (autoencoders) and that can generate new, realistic data — images, text, audio — that didn't exist before (GANs, VAEs, diffusion). This unlocks denoising, anomaly detection, compression, augmentation, and creative synthesis.
  2. Definition: An autoencoder is a network trained to reconstruct its input through a bottleneck layer, learning a compressed representation. A Generative Adversarial Network (GAN) is a pair of networks — a generator that creates fake samples and a discriminator that tries to distinguish real from fake — trained in a minimax game.
  3. Example: A simple autoencoder in PyTorch:
    import torch.nn as nn, torch.nn.functional as F
    
    class Autoencoder(nn.Module):
        def __init__(self):
            super().__init__()
            self.encoder = nn.Sequential(
                nn.Linear(784, 128),
                nn.ReLU(),
                nn.Linear(128, 32)      # bottleneck
            )
            self.decoder = nn.Sequential(
                nn.Linear(32, 128),
                nn.ReLU(),
                nn.Linear(128, 784),
                nn.Sigmoid()
            )
    
        def forward(self, x):
            z = self.encoder(x)
            return self.decoder(z)
    
    # loss = F.mse_loss(output, x)
  4. Types:

    A. Autoencoder variants:

    Variant Key Idea
    Vanilla AE Reconstruction loss (MSE)
    Denoising AE Add noise, reconstruct clean
    Sparse AE Penalty on code activations
    Contractive AE Penalty on encoder Jacobian
    Variational AE (VAE) Probabilistic latent space, KL loss
    Convolutional AE Convs for images

    B. Generative models:

    Model Idea
    GAN Generator vs discriminator minimax
    DCGAN Convolutional GAN
    WGAN Wasserstein loss — stable training
    StyleGAN Style-based generator, photorealistic faces
    Conditional GAN Condition on label / text
    VAE Latent variable model with encoder-decoder
    Diffusion Denoise random noise step-by-step
  5. Advantages:
    • Unsupervised: No labels needed.
    • Learned representations: Useful for clustering, retrieval, transfer.
    • Anomaly detection: High reconstruction error = anomaly.
    • Denoising and compression.
    • GANs generate realistic images, audio, text.
    • Data augmentation and creative applications.
    • Foundation of modern generative AI.
  6. Disadvantages:
    • Autoencoders can copy input (learn identity).
    • GAN training unstable: Mode collapse, oscillation.
    • Evaluation of generators is hard (FID, IS are proxies).
    • Ethical risks: Deepfakes, misinformation.
    • Compute: Training large GANs/diffusion is expensive.
    • VAEs produce blurrier samples than GANs/diffusion.
  7. Characteristics:
    • Bottleneck forces compression in autoencoders.
    • Latent space is the learned code.
    • Adversarial training in GANs is a two-player game.
    • Discriminator is discarded at inference (in GANs).
    • Diffusion models now dominate image synthesis.
    • Latent interpolation: Smooth transitions in latent space.
  8. Diagram: Autoencoder and GAN
        Autoencoder:
    
          Input x ──▶ [Encoder] ──▶ z (bottleneck) ──▶ [Decoder] ──▶ x̂
                                                                        │
                                                                        ▼
                                                                  Loss = |x − x̂|
    
        GAN:
    
          Random noise z ──▶ [Generator] ──▶ fake x̂
                                                │
                                                ▼
                                    ┌──────────────────────┐
          Real x ─────────────────▶ │  Discriminator D(x)  │ ──▶ real/fake
                                    └──────────────────────┘
                                                │
                                                ▼
          Generator loss: fool D
          Discriminator: distinguish real vs fake
  9. Conclusion: Autoencoders and GANs represent the unsupervised and generative branches of deep learning. Autoencoders learn compact representations and power anomaly detection, denoising, and feature learning. GANs pioneered realistic image synthesis; diffusion models have now surpassed them for image generation. The field is moving fast, but the core ideas — bottlenecks, adversarial training, latent spaces — remain foundational. Practitioners should be aware of the ethical responsibilities that come with generative capabilities.
  10. Exercise:
    1. Train a denoising autoencoder on MNIST.
    2. Use an autoencoder for anomaly detection on credit card fraud.
    3. Implement a small DCGAN for generating 32×32 images.
    4. Explain mode collapse and one mitigation technique.
    5. Compare GAN, VAE and diffusion for image generation.

हिंदी (सरल)

  1. समस्या: Supervised learning को labels चाहिए। पर दुनिया का ज़्यादातर data unlabelled है। ऐसे models चाहिए जो बिना labels representations सीखें (autoencoders) और नया realistic data — images, text, audio — generate कर सकें जो पहले नहीं था (GANs, VAEs, diffusion)। यह denoising, anomaly detection, compression, augmentation और creative synthesis को unlock करता है।
  2. परिभाषा: Autoencoder वह network है जिसे अपना input bottleneck layer से reconstruct करने के लिए train किया जाता है, compressed representation सीखते हुए। Generative Adversarial Network (GAN) दो networks की जोड़ी है — generator जो fake samples बनाता है और discriminator जो real vs fake पहचानने की कोशिश करता है — minimax game में train।
  3. उदाहरण: PyTorch में simple autoencoder:
    import torch.nn as nn, torch.nn.functional as F
    
    class Autoencoder(nn.Module):
        def __init__(self):
            super().__init__()
            self.encoder = nn.Sequential(
                nn.Linear(784, 128),
                nn.ReLU(),
                nn.Linear(128, 32)      # bottleneck
            )
            self.decoder = nn.Sequential(
                nn.Linear(32, 128),
                nn.ReLU(),
                nn.Linear(128, 784),
                nn.Sigmoid()
            )
    
        def forward(self, x):
            z = self.encoder(x)
            return self.decoder(z)
    
    # loss = F.mse_loss(output, x)
  4. प्रकार:

    A. Autoencoder variants:

    Variant Key Idea
    Vanilla AE Reconstruction loss (MSE)
    Denoising AE Noise add, clean reconstruct
    Sparse AE Code activations पर penalty
    Contractive AE Encoder Jacobian पर penalty
    Variational AE (VAE) Probabilistic latent space, KL loss
    Convolutional AE Images के लिए Convs

    B. Generative models:

    Model Idea
    GAN Generator vs discriminator minimax
    DCGAN Convolutional GAN
    WGAN Wasserstein loss — stable training
    StyleGAN Style-based generator, photorealistic faces
    Conditional GAN Label / text पर condition
    VAE Latent variable model encoder-decoder के साथ
    Diffusion Random noise step-by-step denoise
  5. लाभ:
    • Unsupervised: Labels नहीं चाहिए।
    • Learned representations: Clustering, retrieval, transfer में।
    • Anomaly detection: High reconstruction error = anomaly।
    • Denoising और compression।
    • GANs realistic images, audio, text generate।
    • Data augmentation और creative applications।
    • Modern generative AI की नींव।
  6. नुकसान:
    • Autoencoders input copy कर सकते हैं (identity सीखें)।
    • GAN training unstable: Mode collapse, oscillation।
    • Evaluation generators का मुश्किल (FID, IS proxies)।
    • Ethical risks: Deepfakes, misinformation।
    • Compute: बड़े GANs/diffusion training महँगी।
    • VAEs GANs/diffusion से blurrier samples।
  7. विशेषताएँ:
    • Bottleneck autoencoders में compression force।
    • Latent space learned code।
    • Adversarial training GANs में two-player game।
    • Discriminator inference पर discard (GANs)।
    • Diffusion models अब image synthesis में dominante।
    • Latent interpolation: Latent space में smooth transitions।
  8. आरेख: Autoencoder और GAN
        Autoencoder:
    
          Input x ──▶ [Encoder] ──▶ z (bottleneck) ──▶ [Decoder] ──▶ x̂
                                                                        │
                                                                        ▼
                                                                  Loss = |x − x̂|
    
        GAN:
    
          Random noise z ──▶ [Generator] ──▶ fake x̂
                                                │
                                                ▼
                                    ┌──────────────────────┐
          Real x ─────────────────▶ │  Discriminator D(x)  │ ──▶ real/fake
                                    └──────────────────────┘
                                                │
                                                ▼
          Generator loss: D को fool करो
          Discriminator: real vs fake distinguish
  9. निष्कर्ष: Autoencoders और GANs deep learning की unsupervised और generative शाखाएँ हैं। Autoencoders compact representations सीखते हैं और anomaly detection, denoising, feature learning को power करते हैं। GANs ने realistic image synthesis की शुरुआत की; अब diffusion models ने image generation में उन्हें पीछे छोड़ दिया। Field तेज़ी से आगे बढ़ रही है, पर core ideas — bottlenecks, adversarial training, latent spaces — foundational हैं। Practitioners को generative capabilities के साथ आने वाली ethical ज़िम्मेदारियों के प्रति सजग रहना चाहिए।
  10. अभ्यास:
    1. MNIST पर denoising autoencoder train कीजिए।
    2. Credit card fraud पर anomaly detection के लिए autoencoder use कीजिए।
    3. 32×32 images generate करने के लिए छोटा DCGAN implement कीजिए।
    4. Mode collapse और एक mitigation technique समझाइए।
    5. Image generation के लिए GAN, VAE और diffusion compare कीजिए।

12. TensorFlow Fundamentals

English

  1. Problem: Implementing deep learning from scratch — forward pass, backward pass, GPU memory management, distributed training — is a huge engineering effort. Teams need a framework that handles tensors, automatic differentiation, hardware acceleration, and deployment. TensorFlow is one of the two dominant frameworks (with PyTorch) used across research and production.
  2. Definition: TensorFlow is an open-source end-to-end machine learning platform developed by Google. It provides a rich ecosystem: Keras (high level API), TensorFlow Lite (mobile/edge), TensorFlow.js (browser/Node), TensorFlow Serving (production), TFX (pipelines), and tf.data (input pipelines).
  3. Example: Training a model in Keras (TensorFlow):
    import tensorflow as tf
    from tensorflow.keras import layers, models
    
    # Load data
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
    x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
    x_test  = x_test.reshape(-1, 784).astype('float32') / 255.0
    
    # Build model
    model = models.Sequential([
        layers.Dense(128, activation='relu', input_shape=(784,)),
        layers.Dropout(0.3),
        layers.Dense(64,  activation='relu'),
        layers.Dense(10,  activation='softmax')
    ])
    
    model.compile(
        optimizer='adam',
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    
    history = model.fit(x_train, y_train,
                        epochs=5, batch_size=128,
                        validation_split=0.1)
    
    model.evaluate(x_test, y_test)
  4. Types:

    A. TensorFlow APIs:

    API Level Use
    Keras (tf.keras) High Standard model building
    tf.Module / tf.function Mid Custom training loops
    tf.GradientTape Low Manual gradient computation
    TensorFlow Lite Deployment Mobile & edge inference
    TensorFlow.js Deployment Browser / Node
    TensorFlow Serving Deployment Production REST/gRPC
    TFX Pipelines End-to-end ML pipelines
    tf.data Data Efficient input pipelines

    B. Execution models: Eager (default, Pythonic) and Graph (tf.function, faster, deployable).

    C. Distribution strategies: MirroredStrategy (single node multi-GPU), MultiWorkerMirroredStrategy (multi-node), TPUStrategy.

  5. Advantages:
    • Complete ecosystem from research to deployment.
    • Keras is beginner-friendly and production-ready.
    • TensorBoard for rich training visualisation.
    • TF Serving / TFLite for robust deployment.
    • Graph mode (tf.function) speeds up training.
    • Distributed training built-in.
    • Google support and large community.
  6. Disadvantages:
    • API churn: Multiple versions over the years confuse beginners.
    • Steeper low-level API than PyTorch.
    • Graph mode debugging harder than eager.
    • Larger framework — heavier install than PyTorch.
    • Documentation spans versions and can be inconsistent.
    • Research community has drifted toward PyTorch.
  7. Characteristics:
    • Tensors: Multi-dimensional arrays with GPU support.
    • Autograd: tf.GradientTape records operations.
    • Graphs: tf.function compiles Python code to a graph.
    • Keras: Sequential, Functional, and Subclassing APIs.
    • Callbacks: EarlyStopping, ModelCheckpoint, TensorBoard.
    • Saved models: SavedModel format for deployment.
  8. Diagram: TensorFlow ecosystem
        ┌────────────────────────────────────────────┐
        │             User Code (Python)             │
        ├────────────────────────────────────────────┤
        │       tf.keras  (Sequential/Functional)    │
        ├────────────────────────────────────────────┤
        │       tf.Module / tf.function              │
        ├────────────────────────────────────────────┤
        │       tf.GradientTape  (autograd)          │
        ├────────────────────────────────────────────┤
        │       TensorFlow Runtime (eager / graph)   │
        ├────────────────────────────────────────────┤
        │  CPU     GPU     TPU     Distributed       │
        └────────────────────────────────────────────┘
                 │            │             │
                 ▼            ▼             ▼
            TFLite       TF.js         TF Serving
            (mobile)     (browser)     (prod)
  9. Conclusion: TensorFlow is a mature, end-to-end platform. Keras makes prototyping easy, while tf.function and GradientTape give control when needed. Its deployment tools (TFLite, TF.js, TF Serving, TFX) make it strong for production. Many practitioners use both TensorFlow and PyTorch — TensorFlow for deployment, PyTorch for research. Learning TensorFlow means learning the whole pipeline: data, model, training, evaluation, deployment.
  10. Exercise:
    1. Train a CNN on CIFAR-10 with Keras.
    2. Add EarlyStopping and ModelCheckpoint callbacks.
    3. Write a custom training loop with tf.GradientTape.
    4. Convert the trained model to TFLite and run it.
    5. Log metrics with TensorBoard and view the dashboard.

हिंदी (सरल)

  1. समस्या: Deep learning scratch से implement करना — forward pass, backward pass, GPU memory management, distributed training — बहुत बड़ा engineering effort है। Teams को ऐसा framework चाहिए जो tensors, automatic differentiation, hardware acceleration और deployment संभाले। TensorFlow दो dominant frameworks में से एक है (PyTorch के साथ) जो research और production में use होती है।
  2. परिभाषा: TensorFlow Google द्वारा developed open-source end-to-end machine learning platform है। यह rich ecosystem देती है: Keras (high level API), TensorFlow Lite (mobile/edge), TensorFlow.js (browser/Node), TensorFlow Serving (production), TFX (pipelines), और tf.data (input pipelines)।
  3. उदाहरण: Keras (TensorFlow) में model training:
    import tensorflow as tf
    from tensorflow.keras import layers, models
    
    # Data load
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
    x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
    x_test  = x_test.reshape(-1, 784).astype('float32') / 255.0
    
    # Model बनाएँ
    model = models.Sequential([
        layers.Dense(128, activation='relu', input_shape=(784,)),
        layers.Dropout(0.3),
        layers.Dense(64,  activation='relu'),
        layers.Dense(10,  activation='softmax')
    ])
    
    model.compile(
        optimizer='adam',
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    
    history = model.fit(x_train, y_train,
                        epochs=5, batch_size=128,
                        validation_split=0.1)
    
    model.evaluate(x_test, y_test)
  4. प्रकार:

    A. TensorFlow APIs:

    API Level Use
    Keras (tf.keras) High Standard model building
    tf.Module / tf.function Mid Custom training loops
    tf.GradientTape Low Manual gradient computation
    TensorFlow Lite Deployment Mobile और edge inference
    TensorFlow.js Deployment Browser / Node
    TensorFlow Serving Deployment Production REST/gRPC
    TFX Pipelines End-to-end ML pipelines
    tf.data Data Efficient input pipelines

    B. Execution models: Eager (default, Pythonic) और Graph (tf.function, तेज़, deployable)।

    C. Distribution strategies: MirroredStrategy (single node multi-GPU), MultiWorkerMirroredStrategy (multi-node), TPUStrategy।

  5. लाभ:
    • Complete ecosystem research से deployment तक।
    • Keras beginner-friendly और production-ready।
    • TensorBoard rich training visualisation।
    • TF Serving / TFLite robust deployment।
    • Graph mode (tf.function) training तेज़।
    • Distributed training built-in।
    • Google support और बड़ी community।
  6. नुकसान:
    • API churn: सालों में कई versions, beginners confuse।
    • Steeper low-level API PyTorch से।
    • Graph mode debugging eager से कठिन।
    • बड़ा framework — PyTorch से heavy install।
    • Documentation versions में फैली, inconsistent।
    • Research community PyTorch की ओर झुकी।
  7. विशेषताएँ:
    • Tensors: GPU support वाले multi-dimensional arrays।
    • Autograd: tf.GradientTape operations record।
    • Graphs: tf.function Python code को graph में compile।
    • Keras: Sequential, Functional और Subclassing APIs।
    • Callbacks: EarlyStopping, ModelCheckpoint, TensorBoard।
    • Saved models: Deployment के लिए SavedModel format।
  8. आरेख: TensorFlow ecosystem
        ┌────────────────────────────────────────────┐
        │             User Code (Python)             │
        ├────────────────────────────────────────────┤
        │       tf.keras  (Sequential/Functional)    │
        ├────────────────────────────────────────────┤
        │       tf.Module / tf.function              │
        ├────────────────────────────────────────────┤
        │       tf.GradientTape  (autograd)          │
        ├────────────────────────────────────────────┤
        │       TensorFlow Runtime (eager / graph)   │
        ├────────────────────────────────────────────┤
        │  CPU     GPU     TPU     Distributed       │
        └────────────────────────────────────────────┘
                 │            │             │
                 ▼            ▼             ▼
            TFLite       TF.js         TF Serving
            (mobile)     (browser)     (prod)
  9. निष्कर्ष: TensorFlow mature, end-to-end platform है। Keras prototyping आसान बनाता है, जबकि tf.function और GradientTape ज़रूरत पड़ने पर control देते हैं। इसके deployment tools (TFLite, TF.js, TF Serving, TFX) production के लिए strong बनाते हैं। कई practitioners TensorFlow और PyTorch दोनों use करते हैं — TensorFlow deployment के लिए, PyTorch research के लिए। TensorFlow सीखना पूरी pipeline सीखना है: data, model, training, evaluation, deployment।
  10. अभ्यास:
    1. Keras से CIFAR-10 पर CNN train कीजिए।
    2. EarlyStopping और ModelCheckpoint callbacks जोड़िए।
    3. tf.GradientTape से custom training loop लिखिए।
    4. Trained model को TFLite में convert करके run कीजिए।
    5. TensorBoard से metrics log करके dashboard देखिए।

13. PyTorch Fundamentals

English

  1. Problem: Research moves fast. Researchers need a framework where debugging is easy (like Python), experiments are quick, and custom layers/architectures are trivial to write. TensorFlow's static graphs and complex APIs slowed down rapid iteration. PyTorch addressed this with dynamic graphs and Pythonic design, and became the default choice for research and increasingly for production.
  2. Definition: PyTorch is an open-source deep learning framework developed by Meta AI (now part of the Linux Foundation). It provides tensors with GPU support, automatic differentiation through autograd, a neural network module (torch.nn), optimizers (torch.optim), data utilities (torch.utils.data), and a rich ecosystem (torchvision, torchaudio, Hugging Face, Lightning).
  3. Example: Training a model in PyTorch:
    import torch, torch.nn as nn, torch.optim as optim
    from torch.utils.data import DataLoader, TensorDataset
    
    # Data
    X = torch.randn(1000, 784)
    y = torch.randint(0, 10, (1000,))
    loader = DataLoader(TensorDataset(X, y), batch_size=64, shuffle=True)
    
    # Model
    model = nn.Sequential(
        nn.Linear(784, 128), nn.ReLU(), nn.Dropout(0.3),
        nn.Linear(128, 64),  nn.ReLU(),
        nn.Linear(64, 10)
    )
    
    # Training
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    model.to(device)
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    
    for epoch in range(5):
        for xb, yb in loader:
            xb, yb = xb.to(device), yb.to(device)
            optimizer.zero_grad()
            out  = model(xb)
            loss = criterion(out, yb)
            loss.backward()
            optimizer.step()
        print(f"epoch {epoch} done")
  4. Types:

    A. Core components:

    Component Purpose
    torch.Tensor Multi-dim array with GPU support
    torch.autograd Automatic differentiation
    torch.nn Layers, losses, containers
    torch.optim Optimizers and LR schedulers
    torch.utils.data Dataset, DataLoader
    torchvision Pretrained vision models, transforms
    torchaudio / torchtext Audio and text utilities
    torch.compile (2.0+) JIT compile for speed
    TorchScript Export for deployment
    PyTorch Lightning High-level training loop wrapper

    B. Model APIs: Sequential, Module (custom class), Functional.

    C. Deployment: TorchScript, ONNX export, TorchServe, quantization.

  5. Advantages:
    • Pythonic: Debug with print, pdb, breakpoints.
    • Dynamic graphs: Change control flow on the fly.
    • Simple autograd: Just call loss.backward().
    • Huge research adoption: Most papers release PyTorch code.
    • Rich ecosystem: torchvision, Hugging Face, Lightning.
    • Performance: torch.compile closes gap with static frameworks.
    • Deployment path: TorchScript, ONNX, TorchServe.
  6. Disadvantages:
    • Deployment historically behind TensorFlow (improving).
    • No single production platform comparable to TF Serving / TFX.
    • Mobile / edge is less mature than TFLite.
    • You write the training loop — more code than Keras.fit().
    • Memory management for very large models is manual.
    • Ecosystem fragmentation — many third-party tools.
  7. Characteristics:
    • Eager by default: Code runs line-by-line.
    • Autograd: Records operations, backward pass via chain rule.
    • zero_grad, backward, step: The canonical training loop.
    • Devices: tensor.to('cuda'), model.to(device).
    • nn.Module: Base class for all layers and models.
    • state_dict: Standard way to save/load weights.
  8. Diagram: PyTorch training loop and ecosystem
        Canonical training loop:
    
          for epoch in epochs:
            for xb, yb in loader:
              optimizer.zero_grad()   # reset grads
              pred = model(xb)         # forward
              loss = criterion(pred, yb)
              loss.backward()          # backward
              optimizer.step()         # update
    
        Ecosystem:
    
          torch.nn        → layers, losses
          torch.optim     → SGD, Adam, AdamW
          torch.utils.data→ Dataset, DataLoader
          torchvision     → ResNet, transforms
          Hugging Face    → transformers, datasets
          Lightning       → high-level Trainer
  9. Conclusion: PyTorch's Pythonic design and dynamic graphs made it the research standard. Its training loop is explicit, which is a feature: you see exactly what happens at each step. The same explicitness helps when debugging or implementing custom logic. With torch.compile, TorchScript, ONNX and Lightning, PyTorch is now viable for production too. Whether you choose PyTorch or TensorFlow, learning one deeply makes the other easy — the concepts (tensors, autograd, layers, optimizers, data loaders) are the same.
  10. Exercise:
    1. Train a CNN on CIFAR-10 with a custom PyTorch training loop.
    2. Save and load the model's state_dict.
    3. Add a learning rate scheduler and observe loss.
    4. Fine-tune a pretrained ResNet-18 on a small dataset.
    5. Convert the model to TorchScript and run inference.

हिंदी (सरल)

  1. समस्या: Research तेज़ चलती है। Researchers को ऐसा framework चाहिए जहाँ debugging आसान (Python जैसी), experiments तेज़, और custom layers/architectures लिखना trivial हो। TensorFlow की static graphs और complex APIs rapid iteration धीमा करती थीं। PyTorch ने dynamic graphs और Pythonic design से इसे हल किया और research का default बन गया, और अब production में भी बढ़ रहा है।
  2. परिभाषा: PyTorch Meta AI द्वारा developed open-source deep learning framework है (अब Linux Foundation का हिस्सा)। यह GPU support वाले tensors, autograd से automatic differentiation, torch.nn neural network module, torch.optim optimizers, torch.utils.data data utilities और rich ecosystem (torchvision, torchaudio, Hugging Face, Lightning) देता है।
  3. उदाहरण: PyTorch में model training:
    import torch, torch.nn as nn, torch.optim as optim
    from torch.utils.data import DataLoader, TensorDataset
    
    # Data
    X = torch.randn(1000, 784)
    y = torch.randint(0, 10, (1000,))
    loader = DataLoader(TensorDataset(X, y), batch_size=64, shuffle=True)
    
    # Model
    model = nn.Sequential(
        nn.Linear(784, 128), nn.ReLU(), nn.Dropout(0.3),
        nn.Linear(128, 64),  nn.ReLU(),
        nn.Linear(64, 10)
    )
    
    # Training
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    model.to(device)
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    
    for epoch in range(5):
        for xb, yb in loader:
            xb, yb = xb.to(device), yb.to(device)
            optimizer.zero_grad()
            out  = model(xb)
            loss = criterion(out, yb)
            loss.backward()
            optimizer.step()
        print(f"epoch {epoch} done")
  4. प्रकार:

    A. Core components:

    Component उद्देश्य
    torch.Tensor GPU support वाला multi-dim array
    torch.autograd Automatic differentiation
    torch.nn Layers, losses, containers
    torch.optim Optimizers और LR schedulers
    torch.utils.data Dataset, DataLoader
    torchvision Pretrained vision models, transforms
    torchaudio / torchtext Audio और text utilities
    torch.compile (2.0+) Speed के लिए JIT compile
    TorchScript Deployment के लिए export
    PyTorch Lightning High-level training loop wrapper

    B. Model APIs: Sequential, Module (custom class), Functional।

    C. Deployment: TorchScript, ONNX export, TorchServe, quantization।

  5. लाभ:
    • Pythonic: Print, pdb, breakpoints से debug।
    • Dynamic graphs: Control flow on-the-fly बदलें।
    • Simple autograd: सिर्फ loss.backward()।
    • Huge research adoption: ज़्यादातर papers PyTorch code release।
    • Rich ecosystem: torchvision, Hugging Face, Lightning।
    • Performance: torch.compile static frameworks की gap बंद।
    • Deployment path: TorchScript, ONNX, TorchServe।
  6. नुकसान:
    • Deployment historically TensorFlow से पीछे (improving)।
    • TF Serving / TFX जैसा single production platform नहीं।
    • Mobile / edge TFLite से कम mature।
    • Training loop खुद लिखें — Keras.fit() से ज़्यादा code।
    • Memory management बहुत बड़े models पर manual।
    • Ecosystem fragmentation — कई third-party tools।
  7. विशेषताएँ:
    • Eager by default: Code line-by-line चलता है।
    • Autograd: Operations record, chain rule से backward pass।
    • zero_grad, backward, step: Canonical training loop।
    • Devices: tensor.to('cuda'), model.to(device)।
    • nn.Module: हर layer और model का base class।
    • state_dict: Weights save/load का standard।
  8. आरेख: PyTorch training loop और ecosystem
        Canonical training loop:
    
          for epoch in epochs:
            for xb, yb in loader:
              optimizer.zero_grad()   # grads reset
              pred = model(xb)         # forward
              loss = criterion(pred, yb)
              loss.backward()          # backward
              optimizer.step()         # update
    
        Ecosystem:
    
          torch.nn        → layers, losses
          torch.optim     → SGD, Adam, AdamW
          torch.utils.data→ Dataset, DataLoader
          torchvision     → ResNet, transforms
          Hugging Face    → transformers, datasets
          Lightning       → high-level Trainer
  9. निष्कर्ष: PyTorch का Pythonic design और dynamic graphs ने इसे research standard बना दिया। इसका training loop explicit है, जो एक feature है: हर step पर क्या हो रहा है साफ दिखता है। यही explicitness debugging और custom logic में मदद करती है। torch.compile, TorchScript, ONNX और Lightning के साथ PyTorch अब production के लिए भी viable है। चाहे PyTorch चुनें या TensorFlow, एक को गहराई से सीखना दूसरे को आसान बना देता है — concepts (tensors, autograd, layers, optimizers, data loaders) वही हैं।
  10. अभ्यास:
    1. Custom PyTorch training loop से CIFAR-10 पर CNN train कीजिए।
    2. Model का state_dict save और load कीजिए।
    3. Learning rate scheduler जोड़कर loss observe कीजिए।
    4. Pretrained ResNet-18 को छोटे dataset पर fine-tune कीजिए।
    5. Model को TorchScript में convert करके inference चलाइए।

14. Transfer Learning & Pretrained Models

English

  1. Problem: Training a deep network from scratch needs millions of labelled examples and days of GPU time. Most real projects have thousands of examples, not millions. Without transfer learning, deep learning would be inaccessible to small teams and niche domains (medical imaging, agriculture, industrial inspection). Transfer learning solves this by reusing knowledge learned on large datasets.
  2. Definition: Transfer learning is the practice of taking a model pretrained on a large dataset (ImageNet for vision, Wikipedia/Common Crawl for NLP) and adapting it to a new task with less data. Common strategies: feature extraction (freeze the backbone, train a new head), fine-tuning (unfreeze some or all layers and train with a small learning rate), and domain adaptation (adjust to a different data distribution).
  3. Example: Fine-tuning ResNet-18 in PyTorch:
    import torch, torch.nn as nn, torch.optim as optim
    import torchvision.models as models
    
    # Load pretrained ResNet-18
    model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
    
    # Replace the classifier for 5 classes
    model.fc = nn.Linear(model.fc.in_features, 5)
    
    # Freeze backbone (feature extraction)
    for p in model.parameters():
        p.requires_grad = False
    for p in model.fc.parameters():
        p.requires_grad = True
    
    # Train only the head first
    optimizer = optim.Adam(model.fc.parameters(), lr=1e-3)
    
    # Later: unfreeze more layers and fine-tune with smaller LR
    # for p in model.parameters():
    #     p.requires_grad = True
    # optimizer = optim.Adam(model.parameters(), lr=1e-5)
  4. Types:

    A. Strategies:

    Strategy Frozen Layers Data Needed
    Feature extraction All backbone Small (hundreds)
    Partial fine-tuning Early layers Medium (thousands)
    Full fine-tuning None Large (tens of thousands)
    Domain adaptation Depends Unsupervised or semi-supervised
    Adapter tuning Backbone frozen, small adapters trained Small
    LoRA Backbone frozen, low-rank updates Small; efficient for LLMs
    Prompt tuning Model frozen; learn prompts Very small

    B. Popular pretrained models:

    • Vision: ResNet, EfficientNet, ConvNeXt, ViT, CLIP, SAM.
    • NLP: BERT, RoBERTa, GPT, T5, LLaMA, Mistral.
    • Speech: wav2vec 2.0, Whisper.
    • Multimodal: CLIP, BLIP, Flamingo, GPT-4V.

    C. Sources: torchvision, Hugging Face Hub, TensorFlow Hub, TIMM.

  5. Advantages:
    • Less data: Works with hundreds instead of millions of examples.
    • Faster training: Days instead of weeks.
    • Better accuracy on small datasets.
    • Accessible: Small teams can build strong models.
    • Reusable: One backbone serves many tasks.
    • Foundational for LLMs: Pretraining + fine-tuning is the standard paradigm.
  6. Disadvantages:
    • Domain mismatch: ImageNet features may not fit medical or satellite images.
    • Catastrophic forgetting: Fine-tuning can destroy useful features.
    • Licensing: Not all pretrained models allow commercial use.
    • Compute for fine-tuning: Large models still need serious GPUs.
    • Bias: Pretrained models carry the biases of their training data.
    • Overfitting head: Small head can overfit if not regularized.
  7. Characteristics:
    • Freeze then unfreeze: Start with frozen backbone, then fine-tune.
    • Smaller LR for fine-tuning than for training from scratch.
    • Discriminative LR: Lower LR for early layers, higher for later layers.
    • BatchNorm: Keep in eval mode if data is small.
    • Data augmentation helps even with pretrained models.
    • LoRA / adapters: Efficient fine-tuning for large models.
  8. Diagram: Transfer learning strategies
        Pretrained backbone (e.g., ResNet-50 on ImageNet):
    
          [ Conv1 ] → [ Conv2 ] → ... → [ Conv5 ] → [ FC-1000 ]
    
        Feature extraction:
    
          [ Conv1 ... Conv5 ] (frozen) → [ New FC-n ]  ← train only this
    
        Partial fine-tuning:
    
          [ Conv1 ] (frozen) → [ Conv2 ... Conv5 ] → [ New FC-n ]
                                ↑ train with small LR
    
        Full fine-tuning:
    
          [ Conv1 ... Conv5 ] → [ New FC-n ]  ← all train with small LR
    
        LoRA / adapters (for large models):
    
          [ Backbone frozen ] + [ small adapters trained ]
  9. Conclusion: Transfer learning is the single biggest practical accelerator in deep learning. Instead of reinventing features, we reuse the ones learned on ImageNet, Wikipedia, or massive multimodal corpora. Modern practice: always start from a pretrained model unless you have a truly unique dataset and huge compute. Learn the recipe — freeze backbone, train head, then unfreeze with small LR — and you can build strong models for almost any domain with modest resources. For LLMs, LoRA and adapters make fine-tuning feasible on a single GPU.
  10. Exercise:
    1. Fine-tune ResNet-18 on a small custom image dataset.
    2. Compare feature extraction vs full fine-tuning.
    3. Fine-tune a pretrained BERT on a text classification task.
    4. Apply LoRA to fine-tune a small language model.
    5. Visualise first-layer filters of a pretrained model.

हिंदी (सरल)

  1. समस्या: Deep network scratch से train करने के लिए millions of labelled examples और दिनों का GPU time चाहिए। ज़्यादातर real projects में हजारों examples होते हैं, millions नहीं। Transfer learning के बिना deep learning छोटी teams और niche domains (medical imaging, agriculture, industrial inspection) के लिए inaccessible रहती। Transfer learning बड़े datasets पर सीखी knowledge reuse करके इसे हल करती है।
  2. परिभाषा: Transfer learning वह practice है जिसमें बड़े dataset (vision के लिए ImageNet, NLP के लिए Wikipedia/Common Crawl) पर pretrained model लेकर उसे कम data वाले नए task पर adapt करते हैं। Common strategies: feature extraction (backbone freeze, नया head train), fine-tuning (कुछ या सभी layers unfreeze करके छोटी learning rate से train), और domain adaptation (अलग data distribution पर adjust)।
  3. उदाहरण: PyTorch में ResNet-18 fine-tuning:
    import torch, torch.nn as nn, torch.optim as optim
    import torchvision.models as models
    
    # Pretrained ResNet-18 load
    model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
    
    # 5 classes के लिए classifier बदलें
    model.fc = nn.Linear(model.fc.in_features, 5)
    
    # Backbone freeze (feature extraction)
    for p in model.parameters():
        p.requires_grad = False
    for p in model.fc.parameters():
        p.requires_grad = True
    
    # पहले सिर्फ head train करें
    optimizer = optim.Adam(model.fc.parameters(), lr=1e-3)
    
    # बाद में: और layers unfreeze करके छोटी LR से fine-tune
    # for p in model.parameters():
    #     p.requires_grad = True
    # optimizer = optim.Adam(model.parameters(), lr=1e-5)
  4. प्रकार:

    A. Strategies:

    Strategy Frozen Layers Data Needed
    Feature extraction पूरा backbone छोटा (सैकड़ों)
    Partial fine-tuning Early layers मध्यम (हजारों)
    Full fine-tuning कोई नहीं बड़ा (दसियों हज़ार)
    Domain adaptation Depends Unsupervised / semi-supervised
    Adapter tuning Backbone frozen, छोटे adapters train छोटा
    LoRA Backbone frozen, low-rank updates छोटा; LLMs के लिए efficient
    Prompt tuning Model frozen; prompts सीखें बहुत छोटा

    B. Popular pretrained models:

    • Vision: ResNet, EfficientNet, ConvNeXt, ViT, CLIP, SAM।
    • NLP: BERT, RoBERTa, GPT, T5, LLaMA, Mistral।
    • Speech: wav2vec 2.0, Whisper।
    • Multimodal: CLIP, BLIP, Flamingo, GPT-4V।

    C. Sources: torchvision, Hugging Face Hub, TensorFlow Hub, TIMM।

  5. लाभ:
    • कम data: Millions की जगह सैकड़ों examples।
    • तेज़ training: हफ्तों की जगह दिन।
    • Better accuracy छोटे datasets पर।
    • Accessible: छोटी teams strong models बना सकें।
    • Reusable: एक backbone कई tasks पर।
    • LLMs के लिए foundational: Pretraining + fine-tuning standard।
  6. नुकसान:
    • Domain mismatch: ImageNet features medical या satellite images पर fit न हों।
    • Catastrophic forgetting: Fine-tuning useful features नष्ट कर सकती है।
    • Licensing: सभी pretrained models commercial use allow नहीं करते।
    • Compute for fine-tuning: बड़े models को serious GPUs चाहिए।
    • Bias: Pretrained models training data का bias ले आते हैं।
    • Overfitting head: छोटा head regularize न हो तो overfit।
  7. विशेषताएँ:
    • Freeze then unfreeze: पहले frozen backbone, फिर fine-tune।
    • Fine-tuning के लिए छोटी LR scratch training से।
    • Discriminative LR: Early layers कम, later layers ज़्यादा।
    • BatchNorm: छोटे data पर eval mode में रखें।
    • Data augmentation pretrained models के साथ भी मदद।
    • LoRA / adapters: बड़े models के लिए efficient fine-tuning।
  8. आरेख: Transfer learning strategies
        Pretrained backbone (जैसे ResNet-50 on ImageNet):
    
          [ Conv1 ] → [ Conv2 ] → ... → [ Conv5 ] → [ FC-1000 ]
    
        Feature extraction:
    
          [ Conv1 ... Conv5 ] (frozen) → [ New FC-n ]  ← सिर्फ यह train
    
        Partial fine-tuning:
    
          [ Conv1 ] (frozen) → [ Conv2 ... Conv5 ] → [ New FC-n ]
                                ↑ छोटी LR से train
    
        Full fine-tuning:
    
          [ Conv1 ... Conv5 ] → [ New FC-n ]  ← सब छोटी LR से train
    
        LoRA / adapters (बड़े models के लिए):
    
          [ Backbone frozen ] + [ छोटे adapters train ]
  9. निष्कर्ष: Transfer learning deep learning का सबसे बड़ा practical accelerator है। Features दोबारा बनाने के बजाय, ImageNet, Wikipedia या massive multimodal corpora पर सीखे features reuse करते हैं। Modern practice: हमेशा pretrained model से शुरू करें, जब तक आपके पास truly unique dataset और बहुत compute न हो। Recipe सीखें — backbone freeze, head train, फिर छोटी LR से unfreeze — और आप लगभग किसी भी domain में modest resources से strong models बना सकते हैं। LLMs के लिए, LoRA और adapters एक single GPU पर fine-tuning feasible बनाते हैं।
  10. अभ्यास:
    1. छोटे custom image dataset पर ResNet-18 fine-tune कीजिए।
    2. Feature extraction और full fine-tuning compare कीजिए।
    3. Text classification task पर pretrained BERT fine-tune कीजिए।
    4. छोटे language model पर LoRA apply कीजिए।
    5. Pretrained model के first-layer filters visualise कीजिए।

15. Evaluation & Hyperparameter Tuning

English

  1. Problem: A model that gets 99% accuracy on the training set can fail on new data. Accuracy alone hides important failures (rare classes, imbalanced data, calibration). And a model's performance depends on dozens of choices — learning rate, batch size, layers, activation, optimizer, augmentation. Without a disciplined evaluation and tuning process, results are not reproducible and cannot be trusted.
  2. Definition: Evaluation is measuring how well a model performs on data it has not seen, using proper splits and metrics. Hyperparameter tuning is the systematic search over configuration choices (learning rate, architecture, regularization) to maximise validation performance. The test set is used only once, at the end, to report final performance.
  3. Example: Proper splits and metrics:
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import classification_report, confusion_matrix
    
    # Splits
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.15, stratify=y)
    X_tr, X_val, y_tr, y_val = train_test_split(X_tr, y_tr, test_size=0.15, stratify=y_tr)
    
    # Train on X_tr with early stopping on X_val
    # ...
    
    # Final evaluation on X_te (ONLY once)
    preds = model.predict(X_te)
    print(classification_report(y_te, preds))
    print(confusion_matrix(y_te, preds))
  4. Types:

    A. Data splits:

    Split Purpose
    Training Learn weights
    Validation Model selection, early stopping, hyperparameter tuning
    Test Final unbiased estimate (used once)
    K-fold cross-validation Small datasets; average across folds
    Stratified split Preserves class proportions
    Time-series split Respects temporal order

    B. Metrics:

    Task Metrics
    Binary classification Precision, Recall, F1, ROC-AUC, PR-AUC
    Multi-class Accuracy, macro F1, confusion matrix, top-k accuracy
    Regression MSE, MAE, RMSE, R², MAPE
    Ranking / detection mAP, IoU, NDCG
    Generation BLEU, ROUGE, FID, IS, perplexity
    Calibration Reliability diagrams, ECE

    C. Tuning methods: Grid search, random search, Bayesian optimization (Optuna, Hyperopt, Ax), population-based training, ASHA.

  5. Advantages:
    • Trustworthy estimates: Test set gives unbiased performance.
    • Better models: Tuning finds configurations that generalize.
    • Reproducibility: Fixed splits and seeds.
    • Diagnosis: Confusion matrices reveal where models fail.
    • Comparison: Fair benchmark against baselines.
    • Resource efficiency: Bayesian search finds good configs faster than grid.
  6. Disadvantages:
    • Tuning is expensive: Each trial trains a model.
    • Overfitting validation: Too many trials can leak into val set.
    • Data leakage risk: Wrong splits ruin results.
    • Metric misuse: Accuracy on imbalanced data is misleading.
    • Reproducibility challenges: Nondeterminism across GPUs and frameworks.
    • Time and compute cost for large models.
  7. Characteristics:
    • Discipline: Never tune on the test set.
    • Stratification: Preserve class balance.
    • Early stopping: Stop when val loss increases.
    • Seed control: Fix random seeds for reproducibility.
    • Cross-validation: Small data → k-fold averages.
    • Experiment tracking: MLflow, Weights & Biases, TensorBoard.
  8. Diagram: Evaluation workflow
        Data splits:
    
          Total Data
          ├── Train (70%)           ── learn weights
          ├── Validation (15%)      ── tune hyperparams, early stop
          └── Test (15%)            ── final unbiased estimate
    
        Workflow:
    
          1. Split data
          2. Train on train, monitor on val
          3. Tune hyperparameters using val
          4. Retrain with best config (optional)
          5. Evaluate once on test
          6. Report + compare baseline
    
        Confusion matrix (binary):
    
                         Pred +    Pred -
           Actual +       TP        FN
           Actual -       FP        TN
    
        Precision = TP/(TP+FP)   Recall = TP/(TP+FN)
        F1 = 2·P·R/(P+R)         Accuracy = (TP+TN)/All
  9. Conclusion: Rigorous evaluation and disciplined tuning are what turn deep learning from a promising experiment into a reliable product. Use proper splits, choose metrics matched to the problem, tune on validation, and touch the test set only once. Track experiments, fix seeds, and always compare against a strong baseline. For hyperparameter search, random and Bayesian methods beat grid search in practice. When a model underperforms, diagnose with confusion matrices and per-class metrics — accuracy alone hides the real story.
  10. Exercise:
    1. Split a dataset into train/val/test and compute all three accuracies.
    2. Plot a confusion matrix for a 10-class classifier.
    3. Run a small random search over learning rates and batch sizes.
    4. Compare accuracy and macro F1 on an imbalanced dataset.
    5. Track experiments with Weights & Biases or MLflow.

हिंदी (सरल)

  1. समस्या: जो model training set पर 99% accuracy दे, वह नए data पर fail हो सकता है। Accuracy अकेले important failures छिपा देती है (rare classes, imbalanced data, calibration)। और model की performance दर्जनों choices पर depend करती है — learning rate, batch size, layers, activation, optimizer, augmentation। Disciplined evaluation और tuning process के बिना results reproducible नहीं होते और भरोसेमंद नहीं।
  2. परिभाषा: Evaluation यह measure करना है कि model ऐसे data पर कैसा perform करता है जो उसने देखा नहीं, proper splits और metrics से। Hyperparameter tuning configuration choices (learning rate, architecture, regularization) पर systematic search है ताकि validation performance maximum हो। Test set सिर्फ एक बार, अंत में, final performance report करने के लिए use होता है।
  3. उदाहरण: Proper splits और metrics:
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import classification_report, confusion_matrix
    
    # Splits
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.15, stratify=y)
    X_tr, X_val, y_tr, y_val = train_test_split(X_tr, y_tr, test_size=0.15, stratify=y_tr)
    
    # X_tr पर train करें, X_val पर early stopping
    # ...
    
    # Final evaluation X_te पर (सिर्फ एक बार)
    preds = model.predict(X_te)
    print(classification_report(y_te, preds))
    print(confusion_matrix(y_te, preds))
  4. प्रकार:

    A. Data splits:

    Split उद्देश्य
    Training Weights सीखें
    Validation Model selection, early stopping, hyperparameter tuning
    Test Final unbiased estimate (एक बार)
    K-fold cross-validation छोटे datasets; folds का average
    Stratified split Class proportions preserve
    Time-series split Temporal order respect

    B. Metrics:

    Task Metrics
    Binary classification Precision, Recall, F1, ROC-AUC, PR-AUC
    Multi-class Accuracy, macro F1, confusion matrix, top-k accuracy
    Regression MSE, MAE, RMSE, R², MAPE
    Ranking / detection mAP, IoU, NDCG
    Generation BLEU, ROUGE, FID, IS, perplexity
    Calibration Reliability diagrams, ECE

    C. Tuning methods: Grid search, random search, Bayesian optimization (Optuna, Hyperopt, Ax), population-based training, ASHA।

  5. लाभ:
    • Trustworthy estimates: Test set unbiased performance।
    • Better models: Tuning generalization वाली configurations।
    • Reproducibility: Fixed splits और seeds।
    • Diagnosis: Confusion matrices बताती हैं model कहाँ fail।
    • Comparison: Baselines के साथ fair benchmark।
    • Resource efficiency: Bayesian search grid से तेज़।
  6. नुकसान:
    • Tuning महँगी: हर trial एक model train।
    • Overfitting validation: बहुत trials से val set में leak।
    • Data leakage risk: गलत splits results बर्बाद।
    • Metric misuse: Imbalanced data पर accuracy misleading।
    • Reproducibility challenges: GPUs और frameworks में nondeterminism।
    • Time और compute cost बड़े models के लिए।
  7. विशेषताएँ:
    • Discipline: Test set पर कभी tune न करें।
    • Stratification: Class balance preserve।
    • Early stopping: Val loss बढ़े तो रोकें।
    • Seed control: Reproducibility के लिए seeds fix।
    • Cross-validation: छोटा data → k-fold averages।
    • Experiment tracking: MLflow, Weights & Biases, TensorBoard।
  8. आरेख: Evaluation workflow
        Data splits:
    
          Total Data
          ├── Train (70%)           ── weights सीखें
          ├── Validation (15%)      ── hyperparams tune, early stop
          └── Test (15%)            ── final unbiased estimate
    
        Workflow:
    
          1. Data split करें
          2. Train पर train, val पर monitor
          3. Val से hyperparameters tune करें
          4. Best config से retrain (optional)
          5. Test पर एक बार evaluate
          6. Report + baseline compare
    
        Confusion matrix (binary):
    
                         Pred +    Pred -
           Actual +       TP        FN
           Actual -       FP        TN
    
        Precision = TP/(TP+FP)   Recall = TP/(TP+FN)
        F1 = 2·P·R/(P+R)         Accuracy = (TP+TN)/All
  9. निष्कर्ष: Rigorous evaluation और disciplined tuning ही deep learning को promising experiment से reliable product बनाते हैं। Proper splits use करें, problem से मेल खाती metrics चुनें, validation पर tune करें, और test set सिर्फ एक बार touch करें। Experiments track करें, seeds fix करें, और हमेशा strong baseline से compare करें। Hyperparameter search में, random और Bayesian methods practice में grid search से बेहतर हैं। जब model underperform करे, confusion matrices और per-class metrics से diagnose करें — accuracy अकेले असली कहानी छिपा देती है।
  10. अभ्यास:
    1. Dataset को train/val/test में split करके तीनों accuracies compute कीजिए।
    2. 10-class classifier के लिए confusion matrix plot कीजिए।
    3. Learning rates और batch sizes पर छोटा random search चलाइए।
    4. Imbalanced dataset पर accuracy और macro F1 compare कीजिए।
    5. Weights & Biases या MLflow से experiments track कीजिए।

16. Deployment, Ethics & Real-World Applications

English

  1. Problem: A model that gets 95% accuracy in a Jupyter notebook is not the same as a model running in production for thousands of users. Deployment introduces new challenges: latency, throughput, hardware constraints, model updates, monitoring, drift, and — increasingly — ethical and legal responsibilities. AI systems affect real people, so building them well goes beyond accuracy.
  2. Definition: Deployment is packaging a trained model so that applications and users can call it reliably. It covers model serving (REST, gRPC, batch), optimisation (quantization, pruning, distillation, ONNX), hardware (CPU, GPU, TPU, edge devices), and MLOps (CI/CD, monitoring, drift detection, retraining). Ethics in AI covers fairness, transparency, privacy, safety, and accountability.
  3. Example: Deploy a model with FastAPI and TorchServe:
    # FastAPI microservice
    from fastapi import FastAPI
    import torch
    from torchvision import transforms
    
    app   = FastAPI()
    model = torch.jit.load("model.pt").eval()
    
    @app.post("/predict")
    def predict(payload: dict):
        x = preprocess(payload["image"])
        with torch.no_grad():
            y = model(x).softmax(-1)
        return {"class": int(y.argmax()), "confidence": float(y.max())}
    
    # Run: uvicorn app:app --host 0.0.0.0 --port 8000
    
    # Or TorchServe / TF Serving for scalable production serving.
    
    # Optimisation: quantize to int8
    quantized = torch.quantization.quantize_dynamic(
        model, {torch.nn.Linear}, dtype=torch.qint8
    )
  4. Types:

    A. Deployment patterns:

    Pattern Description
    Batch inference Run on data dumps; cheap, offline
    Online / real-time REST/gRPC API; low latency
    Streaming Kafka + inference workers
    Edge / on-device TFLite, Core ML, ONNX Runtime, NCNN
    Serverless Cloud Functions, AWS Lambda + model files
    GPU inference servers TorchServe, TF Serving, Triton, vLLM

    B. Optimisation techniques:

    • Quantization: FP32 → INT8, 4× smaller, faster.
    • Pruning: Remove small weights.
    • Knowledge distillation: Small model learns from large model.
    • ONNX: Portable format across runtimes.
    • Batching and caching: Higher throughput.
    • Compilation: torch.compile, TensorRT, XLA.

    C. Ethical AI pillars: Fairness, Explainability, Privacy, Safety, Accountability, Transparency.

  5. Advantages:
    • Business value: Models create impact only when deployed.
    • Scalability: Serve millions of requests.
    • Optimisation: Quantization makes models cheap to run.
    • MLOps: Reliable, monitored systems.
    • Responsible AI: Fairness and privacy reduce harm.
    • Edge deployment: Low latency, privacy by design.
  6. Disadvantages:
    • Complexity: Many moving parts (serving, monitoring, retraining).
    • Latency vs accuracy: Smaller models are faster but often weaker.
    • Data drift: Performance decays silently.
    • Cost: GPUs are expensive; scaling multiplies costs.
    • Security: Model extraction, adversarial inputs, prompt injection.
    • Ethical risks: Bias, deepfakes, surveillance, job displacement.
  7. Characteristics:
    • MLOps lifecycle: Data → train → evaluate → deploy → monitor → retrain.
    • Monitoring: Latency, throughput, accuracy, drift, data quality.
    • A/B testing: Compare models live.
    • Shadow deployments: Run new model silently.
    • Rollback: Ability to revert quickly.
    • Explainability: SHAP, LIME, attention maps, feature importance.
  8. Diagram: MLOps lifecycle and ethical pillars
        MLOps lifecycle:
    
          Data → Train → Evaluate → Deploy → Monitor → Retrain
             ▲                                            │
             └─────────── drift detected ─────────────────┘
    
        Serving options:
    
          Client ─▶ API Gateway ─▶ Inference Service ─▶ Model
                   (REST/gRPC)        (TorchServe,
                                       TF Serving,
                                       Triton, vLLM)
    
        Ethical pillars:
    
          ┌────────────────────────────────┐
          │ Fairness  · Explainability     │
          │ Privacy   · Safety             │
          │ Accountability · Transparency  │
          └────────────────────────────────┘
    
        Real-world uses:
    
          Vision    : medical imaging, autonomous vehicles, retail
          Language  : chat, translation, code, search
          Speech    : assistants, transcription, voice cloning
          Science   : drug discovery, climate, protein folding
  9. Conclusion: Deployment turns a trained model into a product, and ethics turns a product into something society can trust. Modern practice: containerise the model, serve with TorchServe/TF Serving/Triton, optimise with quantization/ONNX, monitor for drift, and keep a retraining pipeline. On the ethical side, follow fairness audits, document capabilities and limits (model cards), respect privacy (differential privacy, federated learning), and design for transparency. Neural networks and deep learning are powerful — and the responsibility to use them well is ours.
  10. Exercise:
    1. Serve a small PyTorch model with FastAPI and call it with curl.
    2. Quantize a model to INT8 and measure latency and accuracy change.
    3. Export a model to ONNX and run it with onnxruntime.
    4. Write a short model card for a fictional classifier.
    5. List three sources of bias in a face-recognition system.

हिंदी (सरल)

  1. समस्या: जो model Jupyter notebook में 95% accuracy दे, वह हजारों users के लिए production में चलने वाले model जैसा नहीं। Deployment नई चुनौतियाँ लाता है: latency, throughput, hardware constraints, model updates, monitoring, drift — और बढ़ती हुई ethical और legal ज़िम्मेदारियाँ। AI systems असली लोगों को affect करते हैं, इसलिए उन्हें अच्छे से बनाना accuracy से आगे जाता है।
  2. परिभाषा: Deployment trained model को package करना है ताकि applications और users उसे reliably call कर सकें। इसमें model serving (REST, gRPC, batch), optimisation (quantization, pruning, distillation, ONNX), hardware (CPU, GPU, TPU, edge devices) और MLOps (CI/CD, monitoring, drift detection, retraining) शामिल हैं। AI Ethics fairness, transparency, privacy, safety और accountability cover करती है।
  3. उदाहरण: FastAPI और TorchServe से model deploy:
    # FastAPI microservice
    from fastapi import FastAPI
    import torch
    from torchvision import transforms
    
    app   = FastAPI()
    model = torch.jit.load("model.pt").eval()
    
    @app.post("/predict")
    def predict(payload: dict):
        x = preprocess(payload["image"])
        with torch.no_grad():
            y = model(x).softmax(-1)
        return {"class": int(y.argmax()), "confidence": float(y.max())}
    
    # Run: uvicorn app:app --host 0.0.0.0 --port 8000
    
    # या scalable production serving के लिए TorchServe / TF Serving।
    
    # Optimisation: int8 पर quantize
    quantized = torch.quantization.quantize_dynamic(
        model, {torch.nn.Linear}, dtype=torch.qint8
    )
  4. प्रकार:

    A. Deployment patterns:

    Pattern विवरण
    Batch inference Data dumps पर चलाएँ; सस्ता, offline
    Online / real-time REST/gRPC API; low latency
    Streaming Kafka + inference workers
    Edge / on-device TFLite, Core ML, ONNX Runtime, NCNN
    Serverless Cloud Functions, AWS Lambda + model files
    GPU inference servers TorchServe, TF Serving, Triton, vLLM

    B. Optimisation techniques:

    • Quantization: FP32 → INT8, 4× छोटा, तेज़।
    • Pruning: छोटे weights हटाएँ।
    • Knowledge distillation: छोटा model बड़े से सीखे।
    • ONNX: Portable format across runtimes।
    • Batching and caching: Higher throughput।
    • Compilation: torch.compile, TensorRT, XLA।

    C. Ethical AI pillars: Fairness, Explainability, Privacy, Safety, Accountability, Transparency।

  5. लाभ:
    • Business value: Models का असर तभी जब deployed।
    • Scalability: Millions of requests serve।
    • Optimisation: Quantization से models सस्ते।
    • MLOps: Reliable, monitored systems।
    • Responsible AI: Fairness और privacy harm घटाते हैं।
    • Edge deployment: Low latency, privacy by design।
  6. नुकसान:
    • Complexity: कई moving parts (serving, monitoring, retraining)।
    • Latency vs accuracy: छोटे models तेज़ पर कमज़ोर।
    • Data drift: Performance चुपचाप गिरती है।
    • Cost: GPUs महँगे; scaling costs multiply।
    • Security: Model extraction, adversarial inputs, prompt injection।
    • Ethical risks: Bias, deepfakes, surveillance, job displacement।
  7. विशेषताएँ:
    • MLOps lifecycle: Data → train → evaluate → deploy → monitor → retrain।
    • Monitoring: Latency, throughput, accuracy, drift, data quality।
    • A/B testing: Live models compare।
    • Shadow deployments: नया model चुपचाप चलाएँ।
    • Rollback: जल्दी revert करने की क्षमता।
    • Explainability: SHAP, LIME, attention maps, feature importance।
  8. आरेख: MLOps lifecycle और ethical pillars
        MLOps lifecycle:
    
          Data → Train → Evaluate → Deploy → Monitor → Retrain
             ▲                                            │
             └─────────── drift detected ─────────────────┘
    
        Serving options:
    
          Client ─▶ API Gateway ─▶ Inference Service ─▶ Model
                   (REST/gRPC)        (TorchServe,
                                       TF Serving,
                                       Triton, vLLM)
    
        Ethical pillars:
    
          ┌────────────────────────────────┐
          │ Fairness  · Explainability     │
          │ Privacy   · Safety             │
          │ Accountability · Transparency  │
          └────────────────────────────────┘
    
        Real-world uses:
    
          Vision    : medical imaging, autonomous vehicles, retail
          Language  : chat, translation, code, search
          Speech    : assistants, transcription, voice cloning
          Science   : drug discovery, climate, protein folding
  9. निष्कर्ष: Deployment trained model को product बनाता है, और ethics product को ऐसा बनाती है जिस पर society भरोसा कर सके। Modern practice: model को containerise करें, TorchServe/TF Serving/Triton से serve करें, quantization/ONNX से optimize करें, drift monitor करें, और retraining pipeline रखें। Ethical side पर fairness audits follow करें, capabilities और limits document करें (model cards), privacy respect करें (differential privacy, federated learning), और transparency के लिए design करें। Neural networks और deep learning powerful हैं — और उन्हें अच्छे से use करने की ज़िम्मेदारी हमारी है।
  10. अभ्यास:
    1. FastAPI से छोटा PyTorch model serve करके curl से call कीजिए।
    2. Model को INT8 पर quantize करके latency और accuracy change measure कीजिए।
    3. Model को ONNX में export करके onnxruntime से run कीजिए।
    4. Fictional classifier के लिए छोटा model card लिखिए।
    5. Face-recognition system में bias के तीन sources list कीजिए।