Lesson 5 � Intermediate

GPT ARCHITECTURE:
TEXT GENERATION KA KING.

GPT sabse popular LLM hai � GPT-3, GPT-4, ChatGPT sab GPT architecture pe based hain. Ye decoder-only transformer hai jo text generation ke liye best hai. Samajhna zaroori hai ki ye kaise kaam karta hai.

? 22 min✓ Intermediate✓ Prerequisite: Transformers

WHY: GPT kyun important hai?

GPT ne modern AI ko define kiya hai. ChatGPT, GitHub Copilot, DALL-E � sab GPT family se aaye hain. Agar tumhe LLMs samajhne hain toh GPT architecture samajhna zaroori hai. Ye decoder-only approach hai jo text generation ke liye sabse efficient hai.

GENERATIVE

Text generate karta hai � prompt se start hokar coherent completion deta hai. Har token previous context pe depend karta hai.

PRE-TRAINED

Bade text corpus pe pehle se trained hai. Phir specific tasks ke liye fine-tune kar sakte ho � bina scratch se shuru kiye.

TRANSFORMER

Transformer architecture use karta hai with self-attention. Parallel processing possible hai, unlike old RNNs.

DECODER-ONLY

Sirf decoder use hota hai (encoder nahi). Left-to-right text generation ke liye perfect hai ye approach.

WHAT: GPT kya hai?

GPT ek decoder-only transformer architecture hai jo auto-regressive language modeling se kaam karta hai. Iska matlab hai � ye left-to-right direction mein text generate karta hai. Har token ko previous tokens ke context mein dekhke predict karta hai.

python
# GPT ka kaam samjho
# 1. Input: "I love"
# 2. Model dekhta hai: ["I", "love"]
# 3. Predicts next token probabilities
# 4. "learning" ko sabse zyada weight milta hai
# 5. Output: "I love learning"

# Simple tokenization example
tokens = ["I", "love", "learning", "AI"]
token_ids = [15496, 2831, 4023, 15340] # GPT-2 token IDs
print(f"Tokens: {tokens}")
print(f"IDs: {token_ids}")
Key difference: BERT bidirectional hai (dono taraf dekhta hai), GPT left-to-right hai (sirf past dekhta hai). Isliye GPT text generation ke liye better hai, BERT classification ke liye.

Architecture ka breakdown

GPT ka architecture transformer ka decoder hai with some modifications. Ye masked self-attention use karta hai taaki future tokens pe na dekh sake.

MASKED ATTENTION

Future tokens hide hain � model sirf past aur present dekh sakta hai. Isse prediction meaningful hoti hai.

POSITIONAL ENCODING

Words ki position track hoti hai. "Cat dog" aur "dog cat" alag hain � position se farak padta hai.

FEED FORWARD

Attention ke baad har position independently process hota hai. Ye non-linear transformations add karta hai.

LAY STACKING

Multiple transformer layers stacked hain. GPT-2 mein 48 layers, GPT-3 mein 96 layers � depth badhne se capability badhti hai.

Pre-training: Kaise seekhta hai GPT

GPT ko sabse pehle bahut bade text corpus pe train kiya jaata hai using next-token prediction. Ye unsupervised learning hai � koi labels nahi chahiye, bas text hai.

python
# Pre-training concept (simplified)
# Training data: "The cat sat on the mat"

# Step 1: Input sequence
input_text = "The cat sat on"
target = "the" # next token

# Step 2: Model predicts probability distribution
# P(the | The cat sat on) = 0.35
# P(a | The cat sat on) = 0.25
# P(floor | The cat sat on) = 0.15
# ... (vocabulary mein baaki tokens)

# Step 3: Loss calculate karo (cross-entropy)
# Step 4: Backpropagation se weights update karo
# Step 5: Millions of examples pe repeat karo
Scale matters: GPT-3 ko ~300 billion tokens pe train kiya gaya tha. Ye(Common Crawl, books, Wikipedia sab included hai). Data ka scale hi GPT ko powerful banata hai.

Fine-tuning: Task adaptation

Pre-training ke baad GPT ko specific tasks ke liye fine-tune kar sakte ho. Ye supervised learning hai � labelled data use karke model ko task-specific banate hain.

python
# Fine-tuning example (conceptual)
# Pre-trained GPT-2 model lo
# Apne custom data pe train karo

# Example: Sentiment classification fine-tune
# Input: "This movie is great"
# Label: POSITIVE

# Pre-trained model already samajhta hai:
# - "great" ka matlab positive hai
# - "movie" ek film hai
# Fine-tuning sirf classification head add karti hai

# HuggingFace se fine-tune karna:
# from transformers import GPT2LMHeadModel
# model = GPT2LMHeadModel.from_pretrained("gpt2")
# ... training loop ...

GPT Evolution: Version by version

GPT-1 (2018)

117M parameters. Pre-training + fine-tuning approach introduce kiya. Basic text completion ka kaam karta tha.

GPT-2 (2019)

1.5B parameters. Zero-shot learning � bina fine-tuning ke kaam karta tha. Surprisingly coherent text generate karta tha.

GPT-3 (2020)

175B parameters � sabse bada model. Few-shot learning, in-context learning � prompt mein instructions de sakte the.

GPT-4 (2023)

Multi-modal � text aur images dono accept karta hai. Better reasoning, more accurate aur safer outputs.

Temperature: Creativity control

Temperature parameter se control hota hai ki model kitna random ya deterministic hona chahiye. Ye logits pe apply hota hai before softmax.

python
# Temperature effect on output
# Low temperature (0.1-0.3): Deterministic
# - Same input pe same output
# - Factual tasks ke liye best
# - "The capital of France is Paris"

# Medium temperature (0.5-0.7): Balanced
# - Thoda variation hai
# - Creative writing ke liye good
# - "The old man sat on the bench, watching..."

# High temperature (0.8-1.2): Creative/Random
# - Zyada variety
# - Artistic tasks ke liye
# - "Quantum elephants dance on moonbeams..."

# API call mein temperature set karna:
# response = client.chat.completions.create(
# model="gpt-4",
# temperature=0.7, # yahan set karo
# messages=[...]
# )
Pro tip: Factual tasks ke liye temperature 0.1-0.3 rakho. Creative tasks ke liye 0.7-0.9 try karo. Temperature 1.0 se zyada mat rakho � output bahut random ho jayega.

OpenAI API: GPT use karna

OpenAI ka API use karke tum GPT models ko directly access kar sakte ho. Chat completions endpoint sabse popular hai.

python
# OpenAI API example
import openai

# client = openai.OpenAI(api_key="your-key")

# Basic chat completion
# response = client.chat.completions.create(
# model="gpt-3.5-turbo",
# messages=[
# {"role": "system", "content": "You are helpful."},
# {"role": "user", "content": "Explain GPT in simple words"}
# ]
# )
# print(response.choices[0].message.content)

# GPT models ka comparison
models = {
 "GPT-3.5-turbo": {"params": "~175B", "speed": "Fast"},
 "GPT-4": {"params": "Unknown", "speed": "Medium"},
 "GPT-4-turbo": {"params": "Unknown", "speed": "Fast"},
 "GPT-4o": {"params": "Unknown", "speed": "Fastest"},
}
for name, info in models.items():
 print(f"{name}: {info['speed']}")

Try it: Tokenization simulator

Neeche apna text likho aur dekho ki GPT kaise tokenize karega. Real GPT tokenizer complex hai, but ye basic idea deta hai.

GPT Tokenizer SimulatorText ko tokens mein convert karo
✓ Run Python dabayein

Quick check

GPT ka full form kya hai✓ Check karne ke baad concept clear hona chahiye.

GPT ka matlab hai Generative (text generate karta hai) + Pre-trained (pehle se trained hai) + Transformer (transformer architecture use karta hai).

Key Takeaways

GPT Architecture complete?

Ab Prompt Engineering par chalo � GPT se best results nikalne ke liye effective prompts kaise likhte hain.