3.5.6 · HinglishSequence Models

Bidirectional RNNs

3,345 words15 min readRead in English

3.5.6 · AI-ML › Sequence Models

Is Problem Ka Solution Kyun Chahiye?

Vanilla RNNs mein, time par hidden state sirf inputs ki information encode karta hai. Ye causal tasks ke liye perfect hai (next word predict karna) lekin un tasks ke liye bahut bura hai jahan answer puri context par depend karta hai:

  • Named Entity Recognition: "Paris" in "I live in Paris" (city) vs "Paris Hilton visited" (person) – tumhe "Paris" ke baad wale words chahiye
  • Machine Translation: Word order alag-alag languages mein alag hoti hai; word 3 translate karne ke liye word 7 jaanna pad sakta hai
  • Speech Recognition: Ek phoneme ki identity aksar baad wale phonemes par depend karti hai
  • Sentiment Analysis: "This movie is not bad" – "not" sab kuch badal deta hai, lekin "bad" se pehle aata hai

Standard RNNs causally constrained hote hain – ye "aage dekh" nahi sakte. Bidirectional RNNs ye constraint hatate hain jab inference time par poori sequence available ho.

Architecture: Do RNNs, Ek Forward, Ek Backward

Figure — Bidirectional RNNs

Forward Pass Ko First Principles Se Derive Karna

Step-by-step banate hain. Ek standard RNN cell equation se shuru karo:

Ye form kyun? Hidden state (1) previous hidden state (memory) aur (2) current input (nayi information) ka nonlinear combination hai. tanh [-1, 1] tak squash karta hai taaki values explode na karein.

Ab, ek bidirectional architecture ke liye:

Forward RNN (left-to-right process karta hai):

  • se start karta hai (ya learned initialization se)
  • par: sirf par depend karta hai
  • par: , par depend karta hai ( ke through)
  • par: poori past sequence encode karta hai

Backward RNN (right-to-left process karta hai):

  • se start karta hai
  • par: sirf par depend karta hai
  • par: , par depend karta hai ( ke through)
  • par: poori future sequence encode karta hai

Alag weight matrices kyun? Forward aur backward RNNs alag patterns learn kar rahe hain (past vs. future dependencies), isliye unhe independent parameters chahiye. Weights share karne se dono directions ek compromise representation seekhne par majboor ho jaate.

Har timestep par outputs combine karna:

Final output layer (kisi task jaise NER ya POS tagging ke liye):

Yahan softmax kyun? Hum har timestep par ek classification decision le rahe hain (jaise "kya ye word PERSON hai ya LOCATION?"), isliye humein classes par ek probability distribution chahiye.

Poora Forward Pass Algorithm

Input sequence diya gaya hai:

  1. Initialize: ,

  2. Forward pass (left-to-right):

    for t = 1 to T:
        h⃗ₜ = tanh(W_h⃗ h⃗ₜ₋₁ + W_x⃗ xₜ + b_h⃗)
    
  3. Backward pass (right-to-left):

    for t = T down to 1:
        h⃖ₜ = tanh(W_h⃖ h⃖ₜ₊₁ + W_x⃖ xₜ + b_h⃖)
    
  4. Combine:

    for t = 1 to T:
        hₜ = [h⃗ₜ; h⃖ₜ]
        yₜ = softmax(Wᵧ hₜ + bᵧ)
    

Do alag loops kyun? Forward RNN complete hona chahiye pehle backward RNN outputs compute karne se, kyunki , par depend karta hai, jiske liye right-to-left processing chahiye. Practice mein, frameworks ise efficiently vectorize kar dete hain.

Worked Example: Named Entity Recognition

Bidirectional RNNs Kab Use Karein (Aur Kab Nahi)

BiRNNs tab use karo jab:

  • Inference time par poori sequence available ho (offline processing)
  • Task non-causal ho: position par label/output, positions par inputs par depend kar sakti hai
  • Examples: NER, POS tagging, machine translation (encoder side), speech recognition (offline), sentiment analysis, question answering (question ya passage encode karna)

BiRNNs tab mat use karo jab:

  • Task causal/autoregressive ho: next token predict karna (language modeling, text generation, online speech recognition)
  • Kyun? Time par, tumhare paas abhi available nahi hain. Yahan BiRNN use karna "cheating" hoga – tumhara model real-time setting mein deploy nahi ho sakta.
  • Real-world constraint: Agar tumhe predictions banana hai jaise sequence aati hai (jaise live captioning, chatbots), tum backward pass run karne ke liye poori sequence ka wait nahi kar sakte.

Computational Considerations

Time complexity:

  • Unidirectional RNN: length ki sequence aur hidden dimension ke liye
  • Bidirectional RNN: (same order, lekin 2× constants)

Kyun? Tum do RNNs run kar rahe ho, har ek timesteps ke saath aur har step par kaam (matrix multiply ).

Space complexity:

  • Backpropagation ke liye dono aur store karne padte hain
  • Total: memory

Parallelization:

  • Forward aur backward passes apne andar parallelizable nahi hain (sequential dependency: , par depend karta hai)
  • Lekin forward aur backward RNNs independent hain, isliye agar tumhare paas multiple GPUs hain ya multiple sequences batch-process kar rahe ho, toh inhe parallel compute kar sakte ho
  • Transformers se contrast: Transformers saare timesteps parallel process karte hain (self-attention), jo unhe modern hardware par bahut faster banata hai

Backpropagation Through Time (BPTT) for BiRNNs

Training ke dauran, hume saare parameters ke respect mein gradients chahiye: .

Loss function (jaise sequence tagging ke liye):

Gradient flow:

  1. compute karo (combined hidden state ke respect mein gradient)
  2. Kyunki hai, aur mein split karo
  3. Forward RNN gradients time mein backward flow karte hain (forward chain ke through right-to-left):
  4. Backward RNN gradients time mein forward flow karte hain (backward chain ke through left-to-right):

Ye tricky kyun hai: Tumhare paas do vanishing/exploding gradient problems hain (ek har RNN ke liye). Wohi solutions apply hote hain: LSTMs/GRUs use karo, gradient clipping karo, careful initialization karo.

Bidirectional LSTMs (BiLSTMs)

Practice mein, vanilla BiRNNs vanishing gradients ki wajah se rarely use hote hain. Uski jagah, hum Bidirectional LSTMs (BiLSTMs) ya Bidirectional GRUs (BiGRUs) use karte hain.

Architecture bilkul same hai, bas har RNN cell ko LSTM/GRU cell se replace karte hain:

LSTMs kyun? Cell state gradients ke liye ek "highway" provide karta hai, jo long sequences par vanishing gradients ko mitigate karta hai. NLP tasks ke liye ye crucial hai jahan dependencies 20+ words tak span kar sakti hain.

Example task: "The movie was not particularly bad, but the acting was terrible" par sentiment analysis.

  • "not" par Forward LSTM: "The movie was not" encode karta hai
  • "not" par Backward LSTM: "not particularly bad, but the acting was terrible" encode karta hai
  • Combined: model seekhta hai ki "not...bad" ek negation hai, lekin "acting was terrible" sentiment ko dominate karta hai

Recall Ek 12-Saal-Ke Bachche Ko Explain Karo

Socho tum ek game khel rahe ho jahan tumhe guess karna hai ki ek sentence mein har word kya karta hai (kya ye kisi ka naam hai? koi jagah? koi action?).

Agar tum sirf left-to-right padhoge, kabhi kabhi confuse ho jaoge. Jaise agar tum "Apple" dekhte ho, tum nahi jaante ki ye fruit hai ya company jab tak aur nahi padhte. Lekin agar tum sirf left dekh rahe ho, toh aage kya hai nahi dekh sakte!

Ek Bidirectional RNN aisa hai jaise do robots hon:

  1. Robot A sentence ko left-to-right padhta hai (normal reading). Ye sab kuch yaad rakhta hai jo usne ab tak dekha hai.
  2. Robot B sentence ko right-to-left padhta hai (ulta padhna). Ye sab kuch yaad rakhta hai jo aage aane wala hai.

Har word par, tum dono robots se poochte ho kya sochte hain, phir unke answers combine karte ho. Robot A kehta hai "Maine 'Apple' dekha aur usse pehle kuch nahi," aur Robot B kehta hai "'Apple' ke baad 'released iOS' aata hai, toh ye shayad tech company hai!" Milke, wo sahi answer dhundh lete hain.

Trick ye hai: ye sirf tab kaam karta hai jab tumhare paas poora sentence pehle se ho. Agar koi abhi bhi sentence type kar raha hai (jaise chatbot mein), Robot B aage nahi dekh sakta kyunki words abhi exist hi nahi karte. Isliye hum bidirectional RNNs sirf tab use karte hain jab hamare paas analyze karne ke liye complete sentence ya document ho.


Connections

  • Recurrent Neural Networks (RNNs): Bidirectional RNNs do unidirectional RNNs se bane hote hain
  • LSTM and GRU Cells: BiLSTMs aur BiGRUs, BiRNNs mein vanishing gradients solve karte hain
  • Encoder-Decoder Architecture: BiRNNs commonly encoder mein use hote hain (poora source sentence encode karo) lekin kabhi decoder mein nahi (autoregressive generation)
  • Attention Mechanism: Aksar BiRNN outputs ke upar apply hota hai timesteps ko alag-alag weight karne ke liye
  • Transformers: BiRNNs ko self-attention se replace karte hain better parallelization ke liye, lekin intuition (full-sequence context) similar hai
  • Named Entity Recognition: BiRNNs/BiLSTMs ka canonical application
  • Part-of-Speech Tagging: Ek aur sequence labeling task jahan BiRNNs excel karte hain
  • Sequence-to-Sequence Models: Encoder mein BiRNNs decoder ko poore input context par attend karne dete hain

#flashcards/ai-ml

Ek unidirectional RNN aur ek Bidirectional RNN mein kya main fark hai? :: Ek unidirectional RNN sequence ko ek direction mein (left-to-right) process karta hai, isliye sirf past inputs par depend karta hai. Ek Bidirectional RNN mein do RNNs hote hain: ek left-to-right process karta hai (), ek right-to-left (), aur har timestep par hota hai, jo past aur future dono context access deta hai.

Tum language modeling (next-word prediction) ke liye Bidirectional RNN kyun nahi use kar sakte?
Language modeling ek causal/autoregressive task hai: time par tum predict kar rahe ho, jo abhi exist nahi karta. BiRNN ka backward pass future tokens ka access maangta hai, jo data leakage hai. Inference mein, wo tokens exist nahi karte, isliye model fail ho jaata.
Timestep par ek Bidirectional RNN ka forward pass equation likhao.
Forward: . Backward: . Combined: .
Hum add karne ki jagah concatenate kyun karte hain?
Concatenation past context (from ) aur future context (from ) dono ko alag signals ke roop mein preserve karta hai. Addition unhe mix kar deta hai, jo information lose kar sakta hai. Downstream layers past vs. future ko appropriately weight karna seekh sakti hain agar unhe alag rakha jaaye.
Do tasks do jahan Bidirectional RNNs appropriate hain aur ek jahan nahi.
Appropriate: Named Entity Recognition (poora sentence available hai, label surrounding words par depend karta hai), Machine Translation encoder (poora source sentence encode karo). Appropriate nahi: Text generation (decoder side), kyunki autoregressive generation ke dauran future tokens abhi exist nahi karte.
Length aur hidden dimension wale Bidirectional RNN ki time complexity kya hai?
, ek unidirectional RNN jaisi hi lekin 2× constant factor ke saath (kyunki tum do RNNs run karte ho). Har timestep par ek matrix multiplication () chahiye.
BiRNN mein kya encode karta hai? kya encode karta hai?
sirf pehla input encode karta hai (koi past context nahi). poori future sequence encode karta hai (right-to-left process kiya gaya). Milke, mein local ( hi) aur global (baaki sequence) dono information hoti hai.
Practice mein vanilla BiRNNs ki jagah BiLSTMs zyada common kyun hain?
Vanilla RNNs ko long sequences par vanishing gradients ki problem hoti hai. LSTMs mein cell states hote hain jo gradient highways ki tarah kaam karte hain, jisse information bahut saare timesteps par bina degrade hue flow kar sake. BiLSTMs isko bidirectional context ke saath combine karte hain, jo unhe NER ya machine translation jaise long-sequence tasks ke liye powerful banata hai.

Concept Map

only encodes past

fails on

examples

solved by

contains

contains

reads left to right

reads right to left

combined via concat or sum

combined via concat or sum

requires

Vanilla RNN

Causally Constrained

Full-Context Tasks

NER, Translation, Speech, Sentiment

Bidirectional RNN

Forward RNN

Backward RNN

Past Context

Future Context

Combined Hidden State

Full Sequence at Inference