6.5.2 · HinglishResearch Frontiers & Practice

Implementing models from scratch

3,442 words16 min readRead in English

6.5.2 · AI-ML › Research Frontiers & Practice

Core Motivation

Jab tum torch.nn.Linear import karte ho, tum ek computational abstraction use kar rahe ho jo chhupata hai:

  • Gradients actually kaise propagate karte hain (backprop mechanics)
  • Memory layout aur computation order
  • Numerical stability ke trade-offs
  • Kyun kuch design choices exist karti hain

Scratch se build karna tumhe force karta hai jawab dene ke liye: Ye layer actually kya compute kar rahi hai, aur ye update rule kyun kaam karta hai?

The Three Pillars of From-Scratch Implementation

1. Forward Pass: Outputs Compute Karna

Ek Simple Dense Layer ke liye Derivation:

Fundamental question se shuru karo: Hum ek input vector ko output space mein kaise transform karein?

Linear transformation (sabse simple learnable operation):

Ye form kyun?

  • (weight matrix): Input space ko rotate aur scale karta hai
  • (bias vector): Decision boundary ko translate karta hai
  • Ye sabse general affine transformation hai

Input ke liye, output :

  • (har row ek alag linear function hai)

Phir activation function apply karo:

Activation kyun? Iske bina, layers stack karna sirf ek aur linear function deta hai: . Activation non-linearity inject karta hai, universal function approximation enable karta hai.

2. Backward Pass: Gradients Compute Karna

Chain Rule se Derivation:

Loss diya hai, hum chahte hain aur .

Maano hum agle layer se receive karte hain (ise kaho).

Weights ke liye, chain rule use karte hue:

compute karna:

se, element ke liye:

Matrix form mein:

Transpose kyun? Dimensionality check:

  • :
  • :
  • Result: ✓ ( ke same shape mein)

Bias ke liye: jahan ones ka vector hai (batch dimension ke across sum karta hai).

Sum kyun? Bias saare samples mein shared hai—hum unke individual gradient contributions accumulate karte hain.

Previous layer ko gradient pass karne ke liye:

Yahan transpose kyun? Hum forward multiplication ko "undo" kar rahe hain— ne transform kiya tha, toh gradients ko backwards transform karta hai.

3. Parameter Update: Learning

Ye kaam kyun karta hai? ke around Taylor expansion:

Doosra term negative hai, toh loss decrease hota hai (itne chote ke liye).

Stochastic Gradient Descent (SGD) Derivation:

Dataset par true gradient:

Problem: Isko compute karne ke liye poore dataset ka full pass chahiye (expensive!).

Solution: Ek mini-batch use karke estimate karo:

Ye kyun kaam karta hai: Law of large numbers ke by, sample average true expectation mein converge karta hai. Chote batches bhi (32-256) achhe estimates dete hain.

Common Pitfalls

Complete End-to-End Example

Key Implementation Patterns

Initialization Strategy

Kyun matter karta hai: Buri initialization → vanishing/exploding gradients → network train nahi hoga.

Xavier/Glorot Initialization:

Derivation: inputs wale linear layer ke liye, agar variance 1 ho:

rakhne ke liye, humein chahiye.

He Initialization (ReLU ke liye):

Alag kyun? ReLU aadhe neurons ko kill karta hai, isliye compensate karne ke liye 2× variance chahiye.

Numerical Stability Tricks

# BAD: Direct softmax (can overflow)
def softmax_bad(z):
    return np.exp(z) / np.sum(np.exp(z))
 
# GOOD: Subtract max for stability
def softmax_stable(z):
    # WHY subtract max? exp(z - max) is bounded by exp(0) = 1
    # This prevents overflow while keeping ratios identical
    exp_z = np.exp(z - np.max(z, axis=0, keepdims=True))
    return exp_z / np.sum(exp_z, axis=0, keepdims=True)

Ye kyun kaam karta hai: kisi bhi constant ke liye. choose karna overflow rokta hai.

Recall Ek 12-Saal ke Bacche ko Samjhao

Socho tum ek robot bana rahe ho jo cats pehchanna seekhta hai. Jab koi tumhe store se ready-made fancy robot kit use karna sikhata hai, tum use aasaani se use kar sakte ho—lekin tumhe samajh nahi aata kyun ye kaam karta hai.

Neural network scratch se banana aise hai jaise robot ko alag-alag parts se banana: motors, sensors, wires. Tumhe karna hoga:

  1. Sahi wiring (forward pass): Sensors → brain → wheels connect karo taaki information flow kare
  2. Galtiyon se seekhna (backward pass): Jab robot galti kare, pata lagao ki kaun si wires ne galat signals bheje aur unhe adjust karo
  3. Dheere-dheere behtar hona (update): Har baar thode chote adjustments karo taaki overcorrect na ho

"From scratch" wala part matlab hai tum basic tools (jaise simple math operations) use kar rahe ho pre-built kits ki jagah. Mushkil hai, lekin ab tum exactly samajhte ho ki robot ke brain mein information kaise flow karta hai, ye errors se kaise seekhta hai, aur jab kuch toot jaaye toh kaise fix karein.

Key insight: Seekhna sirf patterns dhundhna hai cheezein try karke, maapna ki tum kitne galat ho, aur "knobs" (weights) ko thodi si us direction mein adjust karna jo galti kam kare. Ye haazaron baar karo, aur jaadu se, ye seekh leta hai!

Connections

#flashcards/ai-ml

Models scratch se implement karne ka primary purpose kya hai? :: Computational machinery—gradient flow, memory layout, numerical stability—ko samajhna jo frameworks abstract kar dete hain, taaki better debugging, optimization, aur innovation ho sake.

From-scratch implementation ke teen core components kya hain?
1) Forward pass (inputs se outputs compute karna), 2) Backward pass (backpropagation se gradients compute karna), 3) Parameter update (gradients apply karke seekhna).
Forward pass values cache kyun karni chahiye?
Kyunki backward pass ko chain rule se gradients compute karne ke liye intermediate activations aur pre-activation values chahiye; unhe recompute karna inefficient hai aur numerically unstable ho sakta hai.
Dense layer ke forward pass ka formula kya hai?
, jahan input space ko rotate/scale karta hai aur decision boundary translate karta hai.
Activation functions kyun chahiye?
Non-linear activations ke bina, layers stack karna sirf ek aur linear function deta hai: . Non-linearity universal function approximation enable karti hai.
Dense layer ka weights ke saath gradient derive karo.
aur chain rule se: , jahan .
Weight gradients compute karte waqt X ko transpose kyun karte hain?
Dimensionality matching: hai, hai, result hota hai jo ke shape se match karta hai.
Dense layer ka input ke saath gradient kya hai?
, jahan forward transformation ko "reverse" karta hai taaki gradients backward flow karein.
Bias ke liye batch ke across gradients sum kyun karte hain?
Bias ek batch ke saare samples mein shared hota hai, isliye hum single shared bias parameter update karne ke liye har sample ke gradient contributions accumulate karte hain.
ReLU activation ka derivative kya hai?
— gradient sirf wahan flow karta hai jahan input positive tha.
Gradient descent update rule derive karo.
Taylor expansion se, doosra term negative hai, isliye direction mein move karna loss decrease karta hai. Update: .
Mini-batch SGD kya hai aur ye kyun kaam karta hai?
Full gradient ko ek chote batch se approximate karna. Law of large numbers se kaam karta hai: sample average true expectation mein converge karta hai.
Optimization mein momentum kya hai aur ye kaise help karta hai?
Momentum gradients ka exponential moving average accumulate karta hai: . Noisy gradients smooth karta hai aur consistent directions mein inertia add karke accelerate karta hai.
Xavier/Glorot initialization kya hai aur kyun?
. Variance stable rakhta hai: , isliye set karne se maintain hota hai.
He initialization Xavier se alag kyun hai?
He initialization use karta hai kyunki ReLU aadhe neurons kill kar deta hai (unhe 0 set karta hai), isliye reduced activations compensate karne ke liye 2× variance chahiye.
Softmax computation mein max kyun subtract karte hain?
Numerical stability: kisi bhi ke liye. choose karna bound karta hai, overflow rokta hai aur ratios identical rakhta hai.
Activation wale layer se complete backpropagation equation kya hai?
, jahan element-wise multiplication hai aur activation derivative hai.
Backprop mein shapes match karne ke liye randomly transpose kyun nahi karna chahiye?
Sahi shape galat gradient guarantee nahi karta. Pehle chain rule se symbolically derive karo: galat transposes mathematically invalid gradients compute karte hain jo dimensionally sahi lagte hain.
Agar activation derivatives bhool jayein toh kya hoga?
Gradients activation ke information flow par effect ko account nahi karte. Example: saturated sigmoid (, ) vanishing gradients cause karta hai— ignore karna is critical signal death ko miss karta hai.
XOR ke liye hidden layer kyun chahiye?
XOR linearly separable nahi hai—koi single line classes ko separate nahi kar sakti. Hidden layer non-linear activation ke saath ek naya feature space create karta hai jahan classes separable ho jaati hain.

Concept Map

removes

enables

hides

hides

rests on

uses

W

b

feeds

injects

allows

caches X for

Build from scratch

Computational abstraction

Debug and optimize

Backprop mechanics

Numerical stability

Forward pass

Linear transform Wx+b

Rotates and scales

Translates boundary

Activation sigma

Non-linearity

Universal approximation