📥 Download Complete 2026 Printable PDF Notes, Architecture Diagrams & GitHub Code
Get instant free access to the 2026 printable PDF cheat-sheet, runnable lab repositories, interview evaluation rubric, and AI Campus 6-Month Paid Corporate Internship roadmap.
Download Free PDF & Syllabus Roadmap →Top 12 Hugging Face, Transformers & NLP Interview Questions & Answers (2026)
Modern Natural Language Processing, Transformer architecture, Self-Attention, LLM fine-tuning (LoRA/QLoRA), and vector search interview questions with code examples for AI/ML engineers:
Q1 Explain the Self-Attention mechanism in Transformers: Query, Key, Value calculations.
Q2 Why is Multi-Head Attention superior to Single-Head Attention in language comprehension?
Q3 Compare BERT (Encoder) vs GPT (Decoder) vs T5 (Encoder-Decoder) model architectures.
Q4 How do modern Tokenization algorithms work: Byte-Pair Encoding (BPE), WordPiece, and SentencePiece?
Q5 What are Rotary Position Embeddings (RoPE) and why have they replaced absolute positional encodings?
Q6 Explain Parameter-Efficient Fine-Tuning (PEFT): LoRA vs QLoRA internals.
Q7 How do you evaluate generative language models: Perplexity, BLEU, ROUGE, and LLM-as-a-Judge?
Q8 Compare Word2Vec (Skip-Gram / CBOW) vs Contextual Embeddings (BERT / OpenAI text-embedding-3).
Q9 Explain Generation Sampling Parameters: Temperature, Top-k, Top-p (Nucleus), and Min-p.
Q10 How do you prevent and mitigate Hallucinations in LLMs (RAG, Guardrails, Fact-Checking)?
Q11 How do Vector Databases index high-dimensional embeddings (HNSW vs IVFFlat)?
Q12 Explain Cross-Entropy Loss with Label Smoothing in language model training.
Q1 How does Self-Attention work in Transformers (Query, Key, Value matrix math)?
Self-attention allows the model to relate tokens to every other token in the sequence regardless of positional distance. The input embeddings matrix X is linearly projected into Queries (Q = X * W_Q), Keys (K = X * W_K), and Values (V = X * W_V).
The attention score is computed using scaled dot-product attention: Attention(Q, K, V) = softmax((Q * K^T) / sqrt(d_k)) * V. The dot product (Q * K^T) measures token pairwise compatibility, scaling prevents softmax saturation in high dimensions, and multiplying by V produces a contextualized representation for each token.
Q2 What is the architectural difference between BERT (Autoencoding) and GPT (Autoregressive) models?
BERT (Bidirectional Encoder Representations from Transformers) is an encoder-only architecture trained using Masked Language Modeling (MLM) and Next Sentence Prediction (NSP). It sees both left and right context simultaneously, making it ideal for classification, NER, and semantic search.
GPT (Generative Pre-trained Transformer) is a decoder-only architecture utilizing causal (masked) self-attention, predicting the next token t_i conditioned strictly on previous tokens t_1...t_{i-1}. This autoregressive formulation makes GPT state-of-the-art for open-ended generation, reasoning, and instruction following.
Q3 How do you fine-tune a Hugging Face LLM using PEFT, LoRA, and 4-bit QLoRA (bitsandbytes) in Python?
Parameter-Efficient Fine-Tuning (PEFT) with Low-Rank Adaptation (LoRA) freezes pretrained weights W_0 and injects trainable rank-decomposition matrices A and B (delta W = B * A, where rank r << d). This reduces trainable parameters by >99% while matching full fine-tuning performance.
QLoRA quantizes pretrained base weights into NormalFloat4 (NF4) with double quantization, page optimizers, and trains adapter matrices in FP16/BF16, enabling fine-tuning of 7B-70B models on a single commercial GPU.
Q4 Subword Tokenization: BPE vs WordPiece vs SentencePiece (Unigram)?
Byte Pair Encoding (BPE, used in GPT-2/3/4, RoBERTa) starts with a character vocabulary and iteratively merges the most frequent adjacent pair of symbols until a target vocabulary size is reached.
WordPiece (used in BERT) maximizes the likelihood of the training data using a language model scoring metric before merging pairs rather than raw pair frequency.
SentencePiece treats input as a raw byte/character stream including whitespace as a meta-symbol ('_'), eliminating language-specific pre-tokenizers. It can train with BPE or Unigram (which starts from a large vocabulary and iteratively prunes candidates based on likelihood reduction).
Q5 How do you use Hugging Face pipeline(), AutoTokenizer, and AutoModelForSequenceClassification?
Hugging Face's Auto classes dynamically instantiate the correct model architecture and tokenizer from configuration metadata stored on the Hugging Face Hub.
For high-throughput inference or training pipelines, tokenize raw strings into tensor inputs (`input_ids`, `attention_mask`), pass them to the model, and take the argmax of output logits.
Q6 What is Perplexity in Language Models and how is it calculated from Cross-Entropy Loss?
Perplexity (PPL) is the standard intrinsic evaluation metric for autoregressive language models, representing the exponentiated average negative log-likelihood per token: PPL = exp(CrossEntropyLoss).
Intuitively, perplexity represents the effective branching factor: a PPL of 12 means the model is as confused when predicting the next word as if it were choosing uniformly among 12 equally likely words. Lower perplexity indicates superior predictive performance.
Q7 Why do we scale dot-product attention by 1/sqrt(d_k)?
For large projection dimensions d_k, the dot products grow large in magnitude under the assumption that Q and K components are independent random variables with zero mean and unit variance, resulting in variance Var(Q dot K) = d_k.
Large dot products push the softmax function into regions with extremely small gradients (vanishing gradients), halting model convergence. Scaling by 1/sqrt(d_k) restores unit variance and maintains stable gradient propagation.
Q8 Positional Encoding: Sinusoidal vs RoPE (Rotary Position Embeddings)?
Absolute Sinusoidal encodings add fixed trigonometric vectors (sin/cos of different frequencies) directly to token embeddings. However, they do not inherently capture relative token distance and struggle to generalize beyond training context lengths.
Rotary Position Embeddings (RoPE, used in LLaMA 3, Mistral, Qwen) encode positional information into the Queries and Keys by multiplying them with a 2D rotation matrix. The inner product
Q9 How to reduce hallucinations in RAG pipelines using Cross-Encoder Rerankers (BAAI/bge-reranker)?
Standard vector retrieval uses bi-encoders (cosine similarity of isolated dense embeddings), which misses subtle query-context token interactions and often returns irrelevant top-k chunks that cause LLM hallucination.
Cross-encoders process both Query and Candidate Passage simultaneously through all transformer layers with full cross-attention. Reranking top-50 vector matches down to top-5 high-precision passages dramatically improves retrieval precision and reduces hallucination.
Q10 Word2Vec (CBOW vs Skip-Gram) vs FastText vs Dense Transformer Embeddings?
CBOW (Continuous Bag of Words) predicts the target word from context words, training faster and excelling at frequent words. Skip-Gram predicts context words from the center word, performing better on rare words.
FastText enhances Word2Vec by representing words as bags of character n-grams, enabling robust embeddings for out-of-vocabulary (OOV) words and morphologically rich languages.
Dense Transformer Embeddings (BERT, BGE, OpenAI ada-002) provide dynamic, contextualized embeddings where polysemous words (e.g. 'Apple' company vs fruit) receive entirely different vector representations depending on sentence context.
Q11 KV-Cache optimization, FlashAttention-2, and PagedAttention in vLLM?
During autoregressive LLM decoding, recomputing Keys and Values for preceding tokens is O(N^2) redundant. KV-Caching caches past K and V tensors, reducing per-token generation complexity to O(N).
FlashAttention-2 optimizes GPU memory hierarchy by tiling Query/Key/Value blocks into fast SRAM cache and computing softmax without materializing the massive N x N attention matrix in slow HBM, accelerating throughput 2-4x.
PagedAttention (developed for vLLM) partitions continuous KV tensors into non-contiguous virtual memory pages (like an OS virtual memory manager), eliminating memory fragmentation and boosting batching concurrency up to 24x.
Q12 How do you evaluate NLP & LLM systems using BLEU, ROUGE, BERTScore, and RAGAS?
BLEU (Bilingual Evaluation Understudy) measures n-gram precision against human references (standard for translation). ROUGE (Recall-Oriented Understudy for Gesting Evaluation) measures n-gram recall (standard for text summarization).
BERTScore computes cosine similarities between contextual token embeddings of generation and reference, capturing semantic equivalence beyond exact lexical matching.
RAGAS evaluates retrieval-augmented generation across 4 core metrics: Faithfulness (is the answer grounded in context?), Answer Relevance (does it address the query?), Context Precision (are relevant chunks ranked highest?), and Context Recall (did retrieval capture all needed facts?).
Accelerate Your Career with Guaranteed Paid Internship*
Transparent ₹1,20,000 Fee (Inclusive of GST) • ₹10,000/month No-Cost EMI • 6-Month Corporate Paid Internship (₹15,000 – ₹35,000/mo stipend) with official IBM & Microsoft Credly credentials.
