Transformers and BERT

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


🔶 1. Transformers: Introduction

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

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

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


📐 Transformer की Key Idea: Self-Attention

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


🔧 Architecture Overview

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

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

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


🔁 Self-Attention Mechanism

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

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

🔢 Attention Equation:

जहाँ:

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

⚙️ Transformer के Components:

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

🧠 2. BERT: Bidirectional Encoder Representations from Transformers

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


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

  • Language Understanding — Chatbots, Q&A, classification

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

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

📊 Pretraining Tasks:

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

📦 Pretrained BERT Models:

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

🔧 BERT Applications:

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

🧰 Example: HuggingFace Transformers

from transformers import BertTokenizer, BertModel

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

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

🧠 Transformer vs BERT

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

📈 Transformers & BERT Impact

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

📝 Practice Questions:

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

🧠 Summary Table

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

Sequence Models for Text (RNN, LSTM)

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


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

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

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


🔁 2. Recurrent Neural Network (RNN)

📌 उद्देश्य:

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

🔧 Working (Step-by-step):

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

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

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


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

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

🔄 3. LSTM (Long Short-Term Memory)

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


📌 Core Idea:

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


🧠 Key Components of LSTM:

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

📊 LSTM Architecture (Flow)

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

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


🔢 Equations (Simplified):


🧪 Practical Example:

📌 Use Case: Text Generation

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

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


🧰 Python Code Example (PyTorch)

import torch.nn as nn

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

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

🤖 RNN vs LSTM Comparison

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

📈 Applications of Sequence Models

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

📝 Practice Questions:

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

🧠 Summary Table

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

Word Embeddings (Word2Vec, GloVe)

ब हम Natural Language Processing (NLP) का एक बहुत ही महत्वपूर्ण विषय सीखते हैं —
🧠 Word Embeddings, जो deep learning-based NLP की नींव रखते हैं।


🔶 1. Word Embeddings क्या हैं?

Word Embeddings वो तकनीक है जिससे शब्दों को संख्याओं (vectors) में represent किया जाता है — इस तरह कि उनके semantic (meaningful) रिश्ते भी capture हों।

🎯 “Word Embeddings words को mathematical space में ऐसे map करते हैं कि उनके बीच के अर्थ संबंध भी साफ़ दिखें।”


🧠 क्यों ज़रूरी हैं?

Traditional NLP methods जैसे One-Hot Encoding सिर्फ पहचानते हैं कि कोई शब्द है या नहीं — लेकिन वो शब्दों के अर्थ या संबंध को नहीं समझते।

Techniqueसमस्या
One-HotHigh dimensional, sparse, no meaning
EmbeddingDense, low-dimensional, meaningful representation

📏 2. Embedding Vector कैसा होता है?

Word → Vector (जैसे 300 dimensions का dense vector):

WordVector (छोटा version)
king[0.25, 0.67, …, 0.12]
queen[0.23, 0.65, …, 0.14]
banana[0.10, 0.32, …, 0.91]
democracy[0.55, 0.40, …, 0.60]

👉 Words जो अर्थ में करीब होते हैं, उनके vectors भी पास होते हैं।


📊 3. Word2Vec

🧪 Developed By:

Google (2013) — Tomas Mikolov et al.

⚙️ Idea:

  • शब्दों के context के आधार पर embedding सीखना।
  • “You shall know a word by the company it keeps.”

🔁 Two Architectures:

Architectureकार्य
CBOW (Continuous Bag of Words)Nearby words से center word predict करता है
Skip-GramCenter word से आसपास के words predict करता है

🔍 Word2Vec Diagram:

[The] [king] [of] [Spain] → [rules]
↑ context → target

CBOW: Predict “rules”
Skip-Gram: Predict “The”, “king”, “Spain” ← “rules”


🧠 4. GloVe (Global Vectors)

🧪 Developed By:

Stanford (2014) — Jeffrey Pennington et al.

⚙️ Idea:

  • Word2Vec local context पर निर्भर करता है
  • GloVe पूरे corpus के co-occurrence matrix का उपयोग करता है

🧾 Objective:

Find word vectors so that: 

जहाँ Pij​ दो शब्दों के co-occurrence का ratio है।


🔍 Word2Vec vs GloVe

AspectWord2VecGloVe
ContextLocal windowGlobal corpus statistics
TypePredictiveCount-based
TrainingFasterSlower (matrix-based)
AccuracyHighSlightly better for analogies
Use CaseFast semantic learningFine-grained vector space

🧪 5. Real Example: Word Analogy

king−man+woman≈queen

Word Embeddings में ये relation mathematically मिल जाता है! 🔥


🧰 6. Python Example (Gensim – Word2Vec)

from gensim.models import Word2Vec

sentences = [["I", "love", "deep", "learning"],
["Word2Vec", "captures", "semantic", "meaning"]]

model = Word2Vec(sentences, vector_size=50, window=2, min_count=1, sg=1)
print(model.wv["deep"]) # Embedding vector
print(model.wv.most_similar("learning"))

📌 7. Pretrained Embedding Sources

EmbeddingSource
GloVehttps://nlp.stanford.edu/projects/glove/
Word2Vechttps://code.google.com/archive/p/word2vec/
FastTexthttps://fasttext.cc/
BERT EmbeddingsHuggingFace (transformers library)

📈 8. Applications

Use CaseHow Embeddings Help
🗣️ ChatbotsWords with similar meanings treated similarly
📝 Sentiment Analysis“bad” vs “awful” को पहचानना
🔁 TranslationSemantic similarity across languages
💬 Q&A SystemsUnderstanding user intent

📝 Practice Questions:

  1. Word Embeddings क्या होते हैं?
  2. Word2Vec के दो architecture कौन-कौन से हैं?
  3. GloVe और Word2Vec में मुख्य अंतर बताइए।
  4. एक embedding vector की structure को समझाइए।
  5. Word analogy कैसे काम करता है embedding space में?

🧠 Summary Table

TopicSummary
Word EmbeddingWords → meaningful vectors
Word2VecLearns from local context (CBOW, Skip-gram)
GloVeLearns from global co-occurrence
AdvantageSemantic similarity capture करना
ApplicationChatbots, translation, classification

Introduction of Natural Process Language

अब हम Deep Learning के एक बेहद लोकप्रिय और उपयोगी क्षेत्र की ओर बढ़ते हैं:
🗣️ Natural Language Processing (NLP) with Deep Learning
जहाँ मशीनें हमारी भाषा को समझना, बोलना, और लिखना सीखती हैं।

🧠 Natural Language Processing (NLP) क्या है?

Natural Language Processing (NLP) एक तकनीक है जो कंप्यूटर और मानव भाषा (जैसे हिंदी, इंग्लिश, तमिल, उर्दू आदि) के बीच संचार (communication) को संभव बनाती है। इसका उद्देश्य है —

“कंप्यूटर को मानव भाषा समझना, विश्लेषण करना, उत्पन्न करना, और प्रतिक्रिया देना सिखाना।”


🎯 NLP का मूल उद्देश्य:

  • मनुष्यों की तरह भाषा को समझकर कार्य करना
  • बोलचाल, लेखन, और प्रश्नों का प्राकृतिक उत्तर देना

📋 उदाहरण:

इनपुट (User)आउटपुट (NLP System)
“कल मौसम कैसा रहेगा?”“कल बारिश की संभावना है।”
“Translate: I love India”“मुझे भारत से प्यार है”
“Summarize this article”“यह लेख AI के विकास पर आधारित है।”

🔍 NLP किन स्तरों पर काम करता है?

  1. Phonology — ध्वनि की पहचान (Speech to Text)
  2. Morphology — शब्दों के अंदर के parts (un + break + able)
  3. Syntax — व्याकरणिक ढाँचा (subject-verb-object)
  4. Semantics — शब्दों का अर्थ समझना
  5. Pragmatics — संदर्भ के अनुसार अर्थ निकालना
  6. Discourse — वाक्य-से-वाक्य संबंध
  7. World Knowledge — आम इंसानी ज्ञान

🧩 NLP की प्रक्रिया कैसे काम करती है?

👉 Step-by-step Pipeline:

  1. Text Input: Raw human language
  2. Tokenization: Text को छोटे टुकड़ों (tokens) में तोड़ना
  3. Normalization: Lowercase करना, punctuation हटाना
  4. Stop-word Removal: “the”, “is”, “and” जैसे सामान्य शब्द हटाना
  5. Stemming/Lemmatization: शब्दों को उनकी मूल form में लाना
  6. Vectorization: Text को संख्याओं (vectors) में बदलना
  7. Model Prediction: Output generate करना (translation, classification, etc.)

⚙️ NLP के दो प्रमुख हिस्से

क्षेत्रविवरण
Rule-based NLPmanually बनाए गए grammar और rules पर आधारित
Statistical/Deep NLPData और models (machine learning, deep learning) के माध्यम से सीखने वाला NLP

आजकल Deep Learning आधारित NLP सबसे अधिक प्रयोग में है।


🎯 NLP का महत्व

क्षेत्रउपयोग
🗣️ ChatbotsWhatsApp, वेबसाइटों पर जवाब देना
📞 Voice AssistantsAlexa, Siri
📰 Text Summarizationन्यूज़ का सार निकालना
🧾 Document Analysisमेडिकल रिपोर्ट या लीगल दस्तावेज पढ़ना
📚 शिक्षाऑटोमैटिक उत्तर जाँच (auto-grading)
🛒 ई-कॉमर्सप्रोडक्ट रिव्यू की भावना समझना

🧠 NLP को Deep Learning की क्यों ज़रूरत पड़ी?

Traditional NLP की समस्याDeep Learning का समाधान
Language rules complex हैंAutomatically patterns सीखता है
Context को समझ नहीं पाताTransformers contextual meaning पकड़ते हैं
Sparse featuresDense word embeddings
Manually tuned featuresNeural networks auto-learn features

📌 उदाहरण से समझें:

इनपुट: “मैंने बैंक में खाता खोला।”
प्रश्न: “बैंक” का मतलब क्या है?

  • Traditional NLP confusion में पड़ सकता है (Bank – नदी का किनारा या बैंक संस्था?)
  • लेकिन Deep Learning आधारित NLP (जैसे BERT) sentence के context से सही अर्थ पकड़ सकता है।

📝 अभ्यास प्रश्न (Practice Questions):

  1. NLP क्या है और इसका मुख्य उद्देश्य क्या है?
  2. NLP किन स्तरों पर कार्य करता है?
  3. NLP Pipeline में tokenization और vectorization क्या है?
  4. Deep Learning NLP में कैसे मदद करता है?
  5. कोई दो real-world NLP applications बताइए।

🧠 सारांश (Summary Table)

TopicDetail
NLPमानव भाषा को मशीन द्वारा समझने और process करने की तकनीक
ProcessTokenization → Vectorization → Prediction
TechniquesTraditional rules → Deep Learning models
ModelsRNN, LSTM, Transformer, BERT, GPT
ApplicationsChatbot, summarizer, translator, sentiment analyzer

Applications in Games and Robotics

अब हम Reinforcement Learning (RL) की दो सबसे रोमांचक और व्यावहारिक domains में उपयोग को समझेंगे —
🎮 Games और 🤖 Robotics


🎮 1. Applications of RL in Games

Reinforcement Learning का सबसे ज़्यादा प्रसिद्ध और सफल इस्तेमाल Games में हुआ है, जहाँ agent को complex decision sequences सीखने होते हैं।


🧠 Key Use-Cases in Gaming:

Game TypeApplication
📺 Atari GamesBreakout, Pong, Space Invaders, etc.
♟️ Board GamesChess, Go → AlphaZero, AlphaGo
🧠 Strategy GamesStarCraft, Dota 2
💡 Puzzle GamesLearning exploration strategies
🎲 Simulation GamesFlight Simulators, Car Racing (CarRacing-v0)

🔧 Example: DQN in Atari

  • Agent sees game screen (pixel input)
  • Chooses action using learned Q-values
  • Learns which actions give maximum score
Input: Frame (state)
→ CNN → Fully Connected Layers
→ Output: Q-values (actions)

✅ Breakthrough:

DeepMind’s DQN (2015) outperformed humans in many Atari games using only raw pixels as input!


📈 Benefits of RL in Games:

AdvantageExplanation
🧠 Human-level intelligenceAgents beat world champions (AlphaGo)
🧪 Safe experimentationTry many strategies in simulation
🚀 GeneralizationSame algorithm can learn many games
🔁 Real-time learningAgents adapt during gameplay

🤖 2. Applications of RL in Robotics

Reinforcement Learning ने robotics में autonomy और adaptability को नया आयाम दिया है।


🧠 Key Use-Cases in Robotics:

DomainApplication
🦿 MovementWalking, balancing, crawling (e.g., Biped robots)
🦾 ManipulationArm movement, grasping objects
📦 WarehousePath optimization, item picking
🚗 Self-drivingNavigation, obstacle avoidance
🛰️ DronesAerial control and target tracking
🧽 Cleaning botsEnvironment exploration, coverage optimization

🔧 Example: Proximal Policy Optimization (PPO) for Robot Arm

  • Goal: Learn to grasp objects with correct force and angle
  • State: joint angles, object location
  • Action: motor control
  • Reward: +1 for successful grasp, -1 for dropping

🧠 Simulators Used in RL for Robotics:

SimulatorPurpose
🔧 MuJoCoPhysics-based locomotion tasks
🤖 PyBulletArm control, object manipulation
🌐 GazeboComplex robot environment simulation
🎮 Unity ML Agents3D agent training

📈 Benefits of RL in Robotics:

AdvantageExplanation
🚫 No hard-codingLearns behavior through trial and error
🔁 AdaptabilityLearns even with changing environment
📦 GeneralizationTransfer learning from simulation to real robot
🧪 Safe testingUse simulators before deploying to hardware

📊 Summary Table

DomainApplicationExample
GamesControl, strategyDQN in Atari, AlphaGo
RoboticsNavigation, manipulationPPO in robot arms, drone pathing

📝 Practice Questions:

  1. Games में RL का सबसे बड़ा breakthrough क्या रहा है?
  2. RL का Robotics में क्या role है?
  3. Self-driving cars RL से कैसे benefit होते हैं?
  4. Robotics में simulation क्यों जरूरी है?
  5. PPO और DQN का इस्तेमाल कहाँ होता है?