AI / ML — NLP & LLMs

NLP & LLMs

Transformers, BERT, GPT, tokenization, embeddings, RAG pipelines, speech recognition, and fine-tuning strategies — how machines understand human language.

IntermediateTransformersHuggingFace
10+Topics
TransformersBERT / GPT
RAGPipelines
SpeechRecognition
40mRead Time
Fundamentals
Embeddings
Transformer
Key Models
NLP Tasks
Fine-Tuning
Code
Interview Q&A
Cheat Sheet
Speech Recognition
Quiz
100+NLP Tasks
2017Transformer paper
1T+Training tokens (GPT-4)
96%GLUE benchmark (GPT-4)
00
What is NLP?
Natural Language Processing is the branch of AI that handles human language — text and speech. NLP converts messy, ambiguous language into structured representations that machines can process. The pipeline: raw text → tokenise → embed → model → output (label, translation, generated text, etc.).
Text → Tokens → Embeddings → Model → Output (label / generated text)
01
Tokenisation — How Models See Text
Models can't process characters directly — they process integer token IDs. Word tokenisation: split on spaces — simple but fails on rare words. Subword (BPE / WordPiece): the modern standard. Rare words split into known sub-pieces — "unhappiness" → ["un", "happiness"]. BERT uses WordPiece; GPT uses BPE. ~1 token ≈ 0.75 words in English.
"unhappiness" → ["un", "happiness"] · "2024" → ["20", "24"] · ~100k token vocabulary
02
Text Preprocessing — Classical NLP
Before deep learning, NLP required heavy preprocessing: Lowercasing, punctuation removal, stopword removal (the, is, a), stemming (running → run), lemmatisation (better → good). Still useful for TF-IDF and classical ML. Modern Transformers handle raw text directly — minimal preprocessing needed.
"I am Loving AI!!!" → lower → strip → lemmatise → ["love", "ai"] (classical)
03
Bag of Words & TF-IDF
Bag of Words (BoW): represent text as word counts — ignores order. Produces sparse high-dimensional vectors. TF-IDF: weights each word by how often it appears in the document (TF) vs how rare it is across all documents (IDF). "The" gets low weight; "photosynthesis" gets high weight. Still effective baseline for classification.
TF-IDF(t,d) = TF(t,d) × log(N / df(t)) · high score = important rare term
04
n-gram Language Models
Predict the next word given the previous n-1 words. Bigram: P("sat" | "cat") — uses only 1 previous word. Trigram uses 2. Simple but no long-range understanding. Suffers from data sparsity for rare n-grams. Foundation for understanding modern language models — same idea, vastly more powerful with neural networks.
P("the cat sat") = P(the) · P(cat|the) · P(sat|the,cat) (trigram chain rule)
Key tools: NLTK (classic NLP, tokenisation, stemming) · spaCy (fast, production NER, dependency parsing) · Hugging Face Transformers (modern models, tokenisers, fine-tuning) · Sentence-Transformers (embeddings).
00
Why Embeddings?
Models can't process text directly — only numbers. Embeddings convert words, sentences, or documents into dense vectors where semantic similarity = geometric proximity. "dog" and "cat" are close in embedding space; "dog" and "democracy" are far apart. This numeric representation is what enables all downstream NLP tasks.
cosine_sim(embed("king") - embed("man") + embed("woman"), embed("queen")) ≈ 1.0
01
One-Hot Encoding (baseline)
Each word is represented as a sparse vector of size |vocabulary|, with a 1 at the word's index and 0 everywhere else. No semantic information — "cat" is as far from "dog" as from "democracy". Vocabulary of 50,000 words = 50,000-dimensional vector per word. Impractical and semantically empty.
"cat" → [0,0,1,0,0,...,0] · |vocab| = 50k dims · no semantics
02
Word2Vec — Static Embeddings (2013)
Trains a shallow neural net to predict a word from its context (CBOW) or context from a word (Skip-gram). Result: 300-dim dense vectors with rich semantic structure. Famous analogy: king − man + woman ≈ queen. Limitation: one vector per word regardless of context — "bank" always the same vector whether financial or riverbank.
CBOW: predict word from context · Skip-gram: predict context from word · 300 dims
03
Contextual Embeddings — BERT & GPT
Transformer models produce different vectors for the same word depending on context. "bank" in "river bank" gets a completely different 768-dim vector than "bank" in "savings bank." This contextual sensitivity is the fundamental reason Transformers crushed all previous NLP benchmarks in 2018. The embedding is computed dynamically from the full context window.
BERT("bank" in "river bank") ≠ BERT("bank" in "savings bank") · context-sensitive
04
Sentence & Document Embeddings
SBERT (Sentence-BERT): fine-tunes BERT with a siamese network on sentence pairs to produce semantically meaningful sentence-level vectors. OpenAI text-embedding-3-small: 1536-dim general-purpose embeddings, best for RAG. Used for: semantic search, clustering, duplicate detection, recommendation. Cosine similarity between sentence vectors = semantic similarity.
sim = cos(embed("I love dogs"), embed("Dogs are great")) ≈ 0.92 · high = similar
Embedding Model Comparison
ModelTypeDimsContext-awareBest For
One-HotSparse|vocab|NoBaseline only
Word2Vec / GloVeStatic300NoFast similarity, older systems
BERT [CLS]Contextual768YesClassification, NER, QA
SBERTSentence768YesSemantic search, RAG, similarity
text-embedding-3-smallSentence1536YesRAG, production, best general
BGE-large / E5Sentence1024YesOpen-source RAG alternative
00
"Attention Is All You Need" — 2017
Google Brain's 2017 paper replaced recurrent networks entirely with a self-attention mechanism. Key properties: parallelisable (no sequential bottleneck), global receptive field (every token attends to every other), scales efficiently with compute. Every modern LLM descends from this single paper.
RNN: sequential, O(n) steps · Transformer: parallel, O(1) steps · all tokens at once
01
Self-Attention — Q, K, V
Each token produces three vectors via learned matrices: Q (Query): what am I looking for? K (Key): what do I offer? V (Value): what information do I contain? Attention score = Q·Kᵀ / √d_k → softmax → weighted sum of Vs. The √d_k prevents dot products from getting too large (which would push softmax into near-zero gradient regions).
Attention(Q,K,V) = softmax(QKᵀ / √d_k) · V · Q=XWq, K=XWk, V=XWv (learned)
02
Multi-Head Attention
Run attention H times in parallel with different weight matrices. Each head specialises in a different relationship type — one may track syntactic dependencies, another coreference, another semantic roles. Concatenate all head outputs, project to original dimension. GPT-3 uses 96 heads across 96 layers.
MultiHead(Q,K,V) = Concat(head₁,...,headₕ)·Wₒ · each head independently attends
03
Positional Encoding
Self-attention is permutation-invariant — "cat sat mat" and "mat cat sat" produce the same attention scores without position signals. Fix: add a position encoding to each token embedding before the first layer. Original paper: sinusoidal. Modern: learned positional embeddings (BERT) or RoPE / ALiBi for length generalisation (Llama, Mistral).
token_input = token_embedding + position_encoding · RoPE rotates Q&K vectors by position
04
Transformer Block
One Transformer block = Multi-Head Attention → Add&Norm → Feed-Forward Network → Add&Norm. Residual connections (Add) prevent gradient vanishing and allow very deep stacks. LayerNorm stabilises training. FFN is typically 4× wider than model dim — where most parameters live.
x = x + MHA(LN(x)) · x = x + FFN(LN(x)) · stack 12–96 blocks for BERT/GPT
05
Encoder vs Decoder Transformers
Encoder-only (BERT): all tokens attend to all others (bidirectional). Best for understanding tasks: classification, NER, QA. Pretrained with masked language modelling. Decoder-only (GPT, Claude, Llama): causal masking — each token only attends to previous tokens. Best for generation. Pretrained with next-token prediction. Encoder-Decoder (T5, BART): best for seq2seq tasks: translation, summarisation.
BERT: bidirectional → understand · GPT: causal → generate · T5: both → translate/summarise
Model Landscape
ModelTypeParamsContextPretrainingBest For
BERTEncoder110M–340M512 tokensMLM + NSPClassification, NER, QA
RoBERTaEncoder125M–355M512 tokensMLM (no NSP)Stronger BERT alternative
GPT-2Decoder117M–1.5B1024 tokensCLMText generation, fine-tuning base
GPT-4oDecoder~1.8T (est)128k tokensCLM + RLHFFrontier reasoning, multimodal
Claude 3.5 SonnetDecoderUnknown200k tokensCLM + RLHFCoding, reasoning, long docs
T5Enc-Dec60M–11B512 tokensSpan maskingTranslation, summarisation, QA
Llama 3 70BDecoder70B128k tokensCLMBest open-source LLM
Mistral 7BDecoder7B32k tokensCLMEfficient, fast, open
Gemini 1.5 ProDecoderUnknown1M tokensCLM + RLHFUltra-long context tasks
How to Choose
Classify
Text Classification / NER
BERT or RoBERTa fine-tuned. Add a linear head. 500+ labelled examples. Training in minutes on a GPU.
Generate
Text / Code Generation
GPT-4o or Claude for best quality. Llama 3 70B for open-source. GPT-2 for lightweight fine-tuning.
Translate
Translation / Summarisation
T5 or BART fine-tuned. Or zero-shot with GPT-4 for high quality without training data.
Search
Semantic Search / RAG
SBERT or text-embedding-3-small for embeddings. BGE-large for open-source. Then vector DB + reranker.
Sentiment Analysis
Classify text as positive / negative / neutral. Product reviews, social media monitoring, brand tracking.
Model: BERT fine-tuned · Metric: Accuracy, F1
Named Entity Recognition
Tag tokens: PERSON, ORG, LOC, DATE, MONEY. "Apple [ORG] in Cupertino [LOC]." Sequence labelling task.
Model: BERT + CRF · Metric: F1 per entity type
Machine Translation
English → French, Japanese, etc. Seq2seq Transformer. Google Translate, DeepL, NLLB-200 (200 languages).
Model: T5 / NLLB · Metric: BLEU score
Summarisation
Extractive (pick key sentences) or abstractive (generate new text). News summarisation, legal docs, meetings.
Model: BART / T5 / Claude · Metric: ROUGE-L
Question Answering
Extractive QA: find answer span in a passage. Generative QA: generate free-form answer. SQuAD benchmark.
Model: BERT / GPT-4 · Metric: F1, Exact Match
Text Classification
Spam detection, intent classification, topic labelling, content moderation. Multi-label or multi-class.
Model: BERT + linear head · Metric: F1, AUC
Relation Extraction
Identify relationships between entities in text. "Elon Musk [founded] SpaceX." Knowledge graph construction.
Model: BERT + classification head · Metric: F1
Dialogue & Chatbots
Maintain conversation context, understand intent, generate helpful replies. Customer support, virtual assistants.
Model: GPT-4o / Claude / Llama · Metric: Human eval
Evaluation metrics by task: Classification → Accuracy, F1, AUC. NER → per-entity F1. Translation → BLEU. Summarisation → ROUGE. QA → Exact Match + F1. Generation → Human evaluation + GPT-4-as-judge for automated evaluation at scale.
00
The Fine-Tuning Spectrum
From cheapest to most expensive, you have four options for adapting a pretrained model: (1) Zero/few-shot prompting — no training, free. (2) Adapter layers / prompt tuning — train tiny additions. (3) LoRA / QLoRA — train 0.1–1% of params. (4) Full fine-tuning — train all params. Always try in this order.
Prompt → LoRA → Full FT · each 10–100× more expensive than previous
01
BERT Fine-Tuning for Classification
Add a linear classification head on top of BERT's [CLS] token embedding. Fine-tune all layers on labelled data for 3–5 epochs with lr=2e-5. With just 500–2000 labelled examples and 30 minutes on a GPU, this beats all traditional ML approaches for most text classification tasks.
BERT([CLS] token) → Linear(768, num_classes) → CrossEntropy · lr=2e-5, epochs=3
02
LoRA Fine-Tuning for LLMs
Freeze the base model. Add rank-decomposition matrices to query and value projection matrices of each attention layer. Only A and B are trained — typically r=8 or r=16, reducing trainable parameters to <1% of the total. QLoRA: quantise the base model to 4-bit first, enabling fine-tuning a 70B model on a single 80GB A100.
pip install trl peft · LoraConfig(r=16, target_modules=["q_proj","v_proj"]) · SFTTrainer
03
Instruction Fine-Tuning
Format training data as instruction → response pairs. Transforms a base language model into a helpful assistant. Standard formats: Alpaca (instruction, input, output), ChatML (system/user/assistant roles). Quality over quantity: 1000 carefully curated examples beat 100k noisy ones. GPT-4 can generate diverse training pairs from seed examples.
{"role":"user","content":"Summarize this text..."}, {"role":"assistant","content":"Summary: ..."}
04
DPO — Direct Preference Optimisation
Simpler alternative to RLHF. Directly optimise on preference pairs (chosen vs rejected) without a separate reward model. More stable training, fewer hyperparameters. Standard format: {prompt, chosen_response, rejected_response}. Used to align Llama 3, Mistral, and most open models. Implemented in Hugging Face TRL library.
L_DPO = -log σ(β(log π_θ(chosen|x) - log π_θ(rejected|x) - same for ref model))
Fine-tuning decision guide: Classification with >500 labels → BERT fine-tune. Need custom LLM behaviour → LoRA on Llama 3 or Mistral. Need SOTA quality → GPT-4 API fine-tuning. Need private/local → QLoRA on 7–13B model. Never fine-tune for knowledge — use RAG instead.
python — BERT sentiment classifier (Hugging Face Trainer)
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
import numpy as np
from sklearn.metrics import accuracy_score, f1_score

dataset   = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model     = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)

def tokenize(batch):
    return tokenizer(batch["text"], padding="max_length", truncation=True, max_length=512)

dataset = dataset.map(tokenize, batched=True)
dataset.set_format("torch", columns=["input_ids", "attention_mask", "label"])

def compute_metrics(p):
    preds = np.argmax(p.predictions, axis=1)
    return {"accuracy": accuracy_score(p.label_ids, preds),
            "f1": f1_score(p.label_ids, preds, average="weighted")}

trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="./bert-imdb", num_train_epochs=3,
        per_device_train_batch_size=16, learning_rate=2e-5,
        warmup_steps=200, weight_decay=0.01, evaluation_strategy="epoch",
    ),
    train_dataset=dataset["train"].select(range(5000)),
    eval_dataset=dataset["test"].select(range(1000)),
    compute_metrics=compute_metrics,
)
trainer.train()
trainer.evaluate()
python — Semantic search with sentence-transformers
from sentence_transformers import SentenceTransformer, util
import torch

model = SentenceTransformer("all-MiniLM-L6-v2")  # fast + good quality

# Your document corpus
corpus = [
    "Machine learning finds patterns in data.",
    "Deep learning uses neural networks with many layers.",
    "Python is a popular programming language.",
    "Transformers use self-attention mechanisms.",
]

# Encode all documents
corpus_emb = model.encode(corpus, convert_to_tensor=True)

# Search
query = "How do attention mechanisms work?"
query_emb = model.encode(query, convert_to_tensor=True)
scores = util.cos_sim(query_emb, corpus_emb)[0]
top_k = torch.topk(scores, k=2)
for score, idx in zip(top_k.values, top_k.indices):
    print(f"{score:.3f} | {corpus[idx]}")
python — LoRA fine-tuning with TRL (QLoRA pattern)
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from trl import SFTTrainer, SFTConfig
import torch

# 4-bit quantisation (QLoRA)
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", quantization_config=bnb)

# LoRA config: only train attention projections
lora = LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj","v_proj"], lora_dropout=0.05)
model = get_peft_model(model, lora)
model.print_trainable_parameters()  # ~0.2% of total params

trainer = SFTTrainer(
    model=model, train_dataset=dataset,
    args=SFTConfig(output_dir="./mistral-lora", num_train_epochs=3,
                   per_device_train_batch_size=4, learning_rate=2e-4),
)
trainer.train()
The most frequently asked NLP and LLM questions at Google, Meta, OpenAI, Cohere, and NLP-focused ML roles.
Q1
What is the difference between BERT and GPT?
BERT (Encoder-only): bidirectional attention — each token sees all other tokens simultaneously. Pretrained with Masked Language Modelling (predict [MASK] tokens). Best for understanding tasks: classification, NER, QA, similarity. GPT (Decoder-only): causal/autoregressive — each token only sees previous tokens. Pretrained with next-token prediction. Best for generation tasks: chatbots, completion, summarisation. BERT = read the whole book to understand; GPT = write the next chapter.
BERT: [word₁,...,wordₙ] all attend to each other · GPT: wordₙ only sees word₁...wordₙ₋₁
Q2
How does self-attention work?
Each token t creates three vectors: Q, K, V (Query, Key, Value) via learned linear projections. Attention score between tokens i and j = QᵢKⱼᵀ / √d_k. The √d_k prevents vanishing gradients in softmax for large d. Apply softmax to get attention weights — how much token i "attends to" token j. Output for token i = weighted sum of all V vectors. This is computed for all token pairs simultaneously (O(n²) in sequence length).
score(i,j) = QᵢKⱼᵀ/√d_k · weight(i,j) = softmax(score) · out_i = Σⱼ weight(i,j)·Vⱼ
Q3
What is the difference between static and contextual embeddings?
Static (Word2Vec, GloVe): one fixed vector per word, regardless of context. "bank" always the same 300-dim vector. Can't distinguish river bank from financial bank. Contextual (BERT, GPT): each token gets a different vector depending on its surrounding context. Computed dynamically by the full model. "bank" in "river bank" → very different vector than "bank" in "savings bank." Contextual embeddings are why Transformers dominate NLP.
Word2Vec("bank") → fixed vector · BERT("river bank") ≠ BERT("savings bank")
Q4
How do you handle class imbalance in NLP classification?
Same approaches as general ML, plus NLP-specific: (1) Weighted loss — class_weight='balanced' or manual weights in CrossEntropyLoss. (2) Data augmentation — back-translation (translate to another language and back), synonym replacement with WordNet, EDA (Easy Data Augmentation). (3) Oversampling: SMOTE on embeddings (not raw text). (4) Metric: use F1/AUC not accuracy. (5) Few-shot fine-tuning: with imbalanced data, BERT fine-tuning with weighted loss usually outperforms all augmentation techniques.
loss = CrossEntropyLoss(weight=class_weights) · metric: macro-F1, not accuracy
Q5
Explain tokenisation and why it matters for LLMs.
Tokenisation splits text into subword units from a fixed vocabulary (~50k–100k tokens). Affects: cost (billed per token), context window usage (tokens ≠ words), and model behaviour on rare words/languages. BPE (GPT) learns merges from frequency. WordPiece (BERT) maximises language model likelihood. SentencePiece handles multilingual. Critical insight: "ChatGPT" = 1 token; "令和" (Japanese) may be 3 tokens — expensive for non-English text.
~1 token ≈ 0.75 English words · non-Latin scripts use more tokens per word
Q6
What metrics do you use for NLP tasks?
Classification: Accuracy (balanced), F1 (imbalanced), AUC-ROC. NER: entity-level F1 (exact match of span + label). Translation: BLEU score (n-gram precision with brevity penalty). Summarisation: ROUGE-L (longest common subsequence recall). QA: Exact Match + F1 (token-level). Generation: BLEU, BERTScore (embedding similarity), human evaluation, GPT-4-as-judge. Never use accuracy alone for imbalanced NLP tasks.
Classify→F1 · NER→entity-F1 · Translate→BLEU · Summarise→ROUGE · Gen→BERTScore
Q7
RAG vs fine-tuning for an enterprise Q&A chatbot — which do you use?
For a Q&A chatbot over company documents: Use RAG. Documents change frequently (RAG updates without retraining). The system needs to cite sources (RAG retrieves and shows the actual chunks). Company data is sensitive (RAG keeps it in your vector DB, never in model weights). Fine-tune only if: you need a specific response style, the base model doesn't understand your domain vocabulary, or you need to reduce context length (smaller retrieved context after fine-tuning).
Enterprise Q&A → RAG (updateable, citable, private) → add fine-tuning only for style
Everything you need for NLP interviews and projects — model selection, task→metric mapping, tokenisation facts, and key formulas.
Task → Model → Metric
Task
Best Model
Open Alt.
Metric
Sentiment / Classification
BERT fine-tuned
RoBERTa
F1 (macro)
Named Entity Recognition
BERT + CRF
spaCy
Entity F1
Translation
T5 / NLLB-200
opus-mt
BLEU
Summarisation
BART / Claude
T5
ROUGE-L
Question Answering
BERT on SQuAD
GPT-4 (zero-shot)
Exact Match + F1
Semantic Search / RAG
text-embedding-3
SBERT / BGE
NDCG, MRR
Text Generation
GPT-4o / Claude
Llama 3 70B
BERTScore, Human
Embedding Quick Reference
Model
Dims / Type
Best For
Word2Vec / GloVe
300 · static
Legacy, fast similarity
BERT [CLS]
768 · contextual
Classification, NER
SBERT (all-MiniLM)
384 · sentence
Semantic search, fast
text-embedding-3-small
1536 · sentence
RAG, production
BGE-large-en
1024 · sentence
Open-source RAG
Key Formulas
Self-Attention
softmax(QKᵀ / √d_k) · V
Q,K,V = learned projections · √d_k prevents saturation
TF-IDF
TF(t,d) × log(N / df(t))
TF = term freq in doc · df = docs containing term
Cosine Similarity
cos(A,B) = A·B / (|A|·|B|)
1.0 = identical · 0 = orthogonal · used in RAG retrieval
BLEU Score
BP × exp(Σ wₙ log pₙ)
n-gram precision with brevity penalty · 0–100 scale
ROUGE-L
LCS / reference_length
Longest common subsequence recall · for summarisation
CLM Loss (GPT)
L = −(1/T) Σ log P(xₜ|x<ₜ)
Next-token prediction · lower = better language model
Tokenisation Quick Facts
~0.75
Words per token
1 token ≈ 0.75 English words. "Hello world" = 2 tokens. Non-Latin scripts use more tokens per word.
BPE
GPT Tokeniser
Byte Pair Encoding. Learns most frequent character merges from training corpus. Used by GPT-2, GPT-3, GPT-4, Llama.
WP
BERT Tokeniser
WordPiece. Similar to BPE but selects merges by maximising LM likelihood. "##" prefix for continuation tokens.
100k
Typical vocab size
GPT-4: 100,277 tokens. BERT: 30,522. Larger vocab = fewer tokens per sentence = cheaper inference.
3 rules for NLP in production: (1) Never tune hyperparameters on the test set — use a validation set. (2) Always check for data leakage (future information in features). (3) Benchmark your fine-tuned model against a strong zero-shot baseline (GPT-4) before spending GPU time — it's often competitive or better.
01
What is Speech Recognition?
Speech Recognition (also called Automatic Speech Recognition — ASR) is the field of AI that converts spoken language into machine-readable text. It sits at the intersection of NLP, signal processing, and deep learning. Modern ASR systems like OpenAI Whisper use Transformer encoders trained on thousands of hours of multilingual audio.
Audio waveform → Feature extraction (MFCCs) → Acoustic model → Language model → Text
02
Core ASR Tasks
Speech-to-Text (STT): Converting audio signal to a text transcript — the core task.
Voice Activity Detection (VAD): Identifying segments where someone is actively speaking vs silence/noise.
Speaker Identification / Diarization: Recognizing who is speaking and segmenting by speaker.
Language / Accent Adaptation: Adapting the model to specific dialects, accents, or domain vocabulary.
Command Recognition: Detecting specific trigger words or structured commands ("Hey Siri", "Play music").
03
Audio Preprocessing Pipeline
Raw audio must be preprocessed before feeding to a model:
1. Capture audio → 2. Noise reduction → 3. Sampling & framing → 4. Feature extraction (MFCCs / Log-Mel Spectrograms) → 5. Model input
MFCCs (Mel-Frequency Cepstral Coefficients) — the most common audio feature. Maps raw audio to a compact representation that mimics how human hearing perceives frequency.
Log-Mel Spectrograms — used by Whisper and most modern Transformer ASR models. Visual 2D representation of audio frequency over time.
04
Popular Tools & Libraries
OpenAI Whisper — state-of-the-art open-source model, 99-language support, runs locally.
Google Speech-to-Text API — production-grade, cloud-based, streaming support.
Mozilla DeepSpeech — open-source, runs on-device, privacy-friendly.
SpeechRecognition (Python lib) — high-level wrapper around Google, Sphinx, and other backends.
Kaldi — research-grade ASR toolkit, highly configurable.
CMU Sphinx — offline-first, used in embedded systems.
05
Python Example — SpeechRecognition Library
import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) # calibrate noise level print("Speak now...") audio = r.listen(source) try: text = r.recognize_google(audio) print("You said:", text) except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print("API error:", e)
06
OpenAI Whisper — Modern ASR
import whisper model = whisper.load_model("base") # tiny / base / small / medium / large result = model.transcribe("audio.mp3") print(result["text"]) # Multilingual + timestamps result = model.transcribe("audio.mp3", language="hi", word_timestamps=True)
Whisper is trained on 680,000 hours of multilingual web audio. It handles accents, background noise, and code-switching robustly — the current recommended baseline for any ASR project.
07
Real-World Applications
Voice Assistants: Alexa, Siri, Google Assistant — always-on, low-latency ASR pipelines.
Live Transcription: Real-time meeting transcription (Otter.ai, Google Meet captions).
Call Center Automation: Transcribe support calls, extract intent, route tickets.
Accessibility: Voice-to-text for users with motor disabilities.
Voice Biometrics: Speaker authentication ("your voice is your password").
Language Learning Apps: Pronunciation scoring and feedback.
08
Key Challenges in ASR
Background noise: Overlapping sounds degrade transcription quality significantly.
Accents & dialects: Models trained on one accent underperform on others — requires domain adaptation.
Overlapping speech: Multiple simultaneous speakers is still an open research problem.
Real-time latency: Streaming ASR needs sub-300ms latency for natural conversation.
Domain vocabulary: Medical, legal, or technical jargon requires specialized fine-tuning.
Interview tip: If asked about NLP + speech, mention that modern end-to-end ASR (Whisper, wav2vec 2.0) uses Transformer encoders on spectrograms — bridging speech and NLP into a unified architecture, removing the need for separate acoustic + language model pipelines.