InterviewTreedInterviewTreed

InterviewTreed Question Bank

Deep Learning Interview Questions and Answers

Study neural networks, backpropagation, optimization algorithms, CNNs, RNNs, transformers, model training, and deep learning applications.

Total Questions

100

Beginner

30

Intermediate

40

Advanced

30

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Fundamentals

What is deep learning?

Interview question about what is deep learning?

Answer

Deep learning uses neural networks with multiple layers to learn increasingly abstract representations from data. It is useful for images, language, audio, and other high-dimensional tasks, but requires careful data preparation and evaluation.

Syntax

input → multilayer neural network → prediction

Example

An image model learns edges and textures before classifying an object.

Code example

model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 3))

Diagram

Input → Hidden layers → Output

Key Points

  • Understand the core idea of what is deep learning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q2Fundamentals

What is a neural network?

Interview question about what is a neural network?

Answer

A neural network is a parameterized function made of connected units. Each unit combines inputs with weights and a bias, then often applies a nonlinear activation. Training adjusts these parameters to reduce a loss.

Syntax

z = Wx + b; a = φ(z)

Example

A dense layer maps 20 input features to 64 learned features.

Code example

layer = nn.Linear(20, 64)
y = layer(torch.randn(4, 20))

Diagram

Features → weighted sum + bias → activation

Key Points

  • Understand the core idea of what is a neural network?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q3Fundamentals

What is a tensor?

Interview question about what is a tensor?

Answer

A tensor is a multidimensional array used for inputs, parameters, activations, and gradients. Shape, dtype, and device determine how it can be used in operations.

Syntax

tensor.shape, tensor.dtype, tensor.device

Example

A batch of RGB images may have shape [32, 3, 224, 224].

Code example

images = torch.randn(32, 3, 224, 224)
print(images.shape)

Diagram

Batch × Channels × Height × Width

Key Points

  • Understand the core idea of what is a tensor?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q4Fundamentals

What are weights and biases?

Interview question about what are weights and biases?

Answer

Weights determine how strongly inputs influence a neuron; biases provide an adjustable offset. Both are learned through optimization rather than manually set for each prediction.

Syntax

z = Σ(wᵢxᵢ) + b

Example

A linear layer has a weight vector and bias for each output unit.

Code example

layer = nn.Linear(5, 2)
print(layer.weight.shape, layer.bias.shape)

Diagram

Inputs × weights + bias → pre-activation

Key Points

  • Understand the core idea of what are weights and biases?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q5Fundamentals

What is an activation function?

Interview question about what is an activation function?

Answer

An activation transforms a neuron's pre-activation. Nonlinear activations allow stacked layers to represent nonlinear functions; a stack of linear layers alone is still equivalent to one linear transformation.

Syntax

a = φ(z)

Example

ReLU is commonly used between hidden layers.

Code example

x = torch.tensor([-2., 0., 3.])
y = torch.relu(x)

Diagram

z → activation → next layer

Key Points

  • Understand the core idea of what is an activation function?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q6Activations

What is ReLU?

Interview question about what is relu?

Answer

ReLU returns max(0, x). It is computationally simple and often supports effective optimization, although units that remain negative can become inactive.

Syntax

ReLU(x) = max(0, x)

Example

[-3, -1, 2] becomes [0, 0, 2].

Code example

x = torch.tensor([-3., -1., 2.])
print(torch.relu(x))

Diagram

Negative → 0; positive → unchanged

Key Points

  • Understand the core idea of what is relu?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q7Activations

What is sigmoid?

Interview question about what is sigmoid?

Answer

Sigmoid maps real-valued inputs to values strictly between zero and one. It is useful for binary probability outputs, but can saturate and produce small gradients for extreme inputs.

Syntax

σ(x) = 1 / (1 + e⁻ˣ)

Example

A binary classifier can convert one logit to a positive-class probability.

Code example

probs = torch.sigmoid(logits)

Diagram

Logit → sigmoid → probability

Key Points

  • Understand the core idea of what is sigmoid?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q8Activations

What is softmax?

Interview question about what is softmax?

Answer

Softmax converts class logits into nonnegative values that sum to one. For PyTorch multiclass training, pass logits directly to CrossEntropyLoss for numerical stability.

Syntax

softmax(zᵢ) = exp(zᵢ) / Σ exp(zⱼ)

Example

Three class scores become three class probabilities.

Code example

probs = torch.softmax(logits, dim=-1)

Diagram

Class logits → softmax → probabilities

Key Points

  • Understand the core idea of what is softmax?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q9Training

What is a loss function?

Interview question about what is a loss function?

Answer

A loss function measures the mismatch between predictions and targets. The optimizer tries to reduce it; the loss must match the task and output representation.

Syntax

L = loss(prediction, target)

Example

Cross-entropy is common for classification; MSE is common for regression.

Code example

loss = nn.CrossEntropyLoss()(logits, labels)

Diagram

Prediction + target → scalar loss

Key Points

  • Understand the core idea of what is a loss function?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q10Training

What is an epoch?

Interview question about what is an epoch?

Answer

An epoch is one complete pass through the training dataset. A batch is a subset processed together, while a training step usually means one optimizer update.

Syntax

steps ≈ ceil(dataset_size / batch_size)

Example

1,000 examples with batch size 100 means about 10 steps per epoch.

Code example

steps = (1000 + 100 - 1) // 100
print(steps)

Diagram

Dataset → batches → steps → epoch complete

Key Points

  • Understand the core idea of what is an epoch?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q11Training

What is batch size?

Interview question about what is batch size?

Answer

Batch size is the number of examples used to estimate a gradient per update. Large batches can improve hardware utilization but use more memory; small batches introduce noisier gradients.

Syntax

gradient ≈ average over batch

Example

Compare batch sizes 32 and 64 with the same validation protocol.

Code example

loader = DataLoader(dataset, batch_size=32, shuffle=True)

Diagram

Dataset → mini-batches → updates

Key Points

  • Understand the core idea of what is batch size?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q12Evaluation

What are training, validation, and test sets?

Interview question about what are training, validation, and test sets?

Answer

Training data updates parameters; validation data selects hyperparameters and checkpoints; test data estimates final performance. Repeatedly tuning on the test set leaks information into model selection.

Syntax

train = fit; validation = choose; test = final estimate

Example

Use a stratified split for imbalanced classification when appropriate.

Code example

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=.2, random_state=42)

Diagram

Data → train / validation / test

Key Points

  • Understand the core idea of what are training, validation, and test sets?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q13Evaluation

What is overfitting?

Interview question about what is overfitting?

Answer

Overfitting occurs when a model learns training-specific noise and performs worse on unseen data. A common signal is training loss falling while validation loss rises.

Syntax

train loss ↓ while validation loss ↑

Example

A large model memorizes a tiny dataset but fails on new examples.

Code example

# Track train_loss and val_loss each epoch
print(train_loss, val_loss)

Diagram

Training fit improves → generalization gap grows

Key Points

  • Understand the core idea of what is overfitting?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q14Evaluation

What is underfitting?

Interview question about what is underfitting?

Answer

Underfitting occurs when a model is too limited or insufficiently trained to capture the data structure. Both training and validation performance are often poor.

Syntax

train error high + validation error high

Example

A linear model may underfit a nonlinear classification task.

Code example

model = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 1))

Diagram

Insufficient model fit on both splits

Key Points

  • Understand the core idea of what is underfitting?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q15Data preparation

What is input normalization?

Interview question about what is input normalization?

Answer

Normalization scales input features to help optimization. Fit statistics on training data only, then reuse them for validation, test, and production to avoid leakage.

Syntax

x' = (x − μ_train) / σ_train

Example

Standardize numeric columns with training mean and standard deviation.

Code example

mu = X_train.mean(0)
sigma = X_train.std(0).clip(min=1e-8)
X_valid_scaled = (X_valid - mu) / sigma

Diagram

Train data → fit scaler → transform all splits

Key Points

  • Understand the core idea of what is input normalization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q16Optimization

What is gradient descent?

Interview question about what is gradient descent?

Answer

Gradient descent updates parameters in the negative gradient direction to reduce loss locally. The learning rate controls the update size.

Syntax

θₜ₊₁ = θₜ − η∇L(θₜ)

Example

Each update nudges weights toward lower loss.

Code example

loss.backward()
with torch.no_grad():
    for p in model.parameters(): p -= lr * p.grad

Diagram

Loss → gradient → parameter update

Key Points

  • Understand the core idea of what is gradient descent?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q17Optimization

What is a learning rate?

Interview question about what is a learning rate?

Answer

The learning rate controls the size of optimizer updates. Too large can cause divergence; too small can make learning slow. Schedules and warmup can improve training stability.

Syntax

θ ← θ − ηg

Example

Test a few candidate rates on a pilot run.

Code example

optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)

Diagram

Small steps may crawl; large steps may overshoot

Key Points

  • Understand the core idea of what is a learning rate?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q18Optimization

What is an optimizer?

Interview question about what is an optimizer?

Answer

An optimizer converts gradients into parameter updates. SGD uses gradient steps, momentum smooths them, and Adam maintains moving estimates of gradients and squared gradients. AdamW decouples weight decay.

Syntax

zero_grad → backward → step

Example

AdamW is a common starting point for transformer fine-tuning.

Code example

optimizer.zero_grad(); loss.backward(); optimizer.step()

Diagram

Gradients + optimizer state → updated weights

Key Points

  • Understand the core idea of what is an optimizer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q19Training

What is a forward pass?

Interview question about what is a forward pass?

Answer

A forward pass sends inputs through layers to compute activations, logits, or predictions. During training, operations are recorded so gradients can later be calculated.

Syntax

ŷ = fθ(x)

Example

A classifier maps feature vectors to class logits.

Code example

logits = model(inputs)

Diagram

Input → layers → prediction

Key Points

  • Understand the core idea of what is a forward pass?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q20Training

What is a backward pass?

Interview question about what is a backward pass?

Answer

A backward pass computes derivatives of the loss with respect to parameters and intermediate tensors. It calculates gradients; the optimizer applies the updates separately.

Syntax

loss.backward() → ∂L/∂θ

Example

After classification loss is calculated, gradients are propagated through layers.

Code example

optimizer.zero_grad(); loss.backward(); optimizer.step()

Diagram

Forward → loss → backward gradients → update

Key Points

  • Understand the core idea of what is a backward pass?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q21Backpropagation

What is backpropagation?

Interview question about what is backpropagation?

Answer

Backpropagation efficiently applies the chain rule from the loss back through the computation graph to compute parameter gradients.

Syntax

∂L/∂x = (∂L/∂y)(∂y/∂x)

Example

Output-layer gradients propagate into hidden layers.

Code example

loss = criterion(model(x), y)
loss.backward()

Diagram

Loss gradient ← output ← hidden layers

Key Points

  • Understand the core idea of what is backpropagation?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q22Backpropagation

What is automatic differentiation?

Interview question about what is automatic differentiation?

Answer

Automatic differentiation records differentiable operations and applies derivative rules to calculate gradients. PyTorch autograd builds a dynamic graph as operations execute.

Syntax

x.requires_grad_(True); y.backward()

Example

Differentiate y = x² + 2x at x=3.

Code example

x = torch.tensor(3., requires_grad=True)
y = x*x + 2*x
y.backward(); print(x.grad)

Diagram

Operations → graph → reverse-mode gradients

Key Points

  • Understand the core idea of what is automatic differentiation?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q23Normalization

What is batch normalization?

Interview question about what is batch normalization?

Answer

Batch normalization normalizes activations using batch statistics in training and running estimates in evaluation, then applies learned scale and shift. Small batches may make statistics noisy.

Syntax

BatchNorm(x) = γ·normalize(x) + β

Example

Use BatchNorm1d in a dense network where appropriate.

Code example

block = nn.Sequential(nn.Linear(64,64), nn.BatchNorm1d(64), nn.ReLU())

Diagram

Activations → normalize → scale/shift

Key Points

  • Understand the core idea of what is batch normalization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q24Regularization

What is dropout?

Interview question about what is dropout?

Answer

Dropout randomly zeros activations during training to discourage fragile co-adaptations. It is disabled in evaluation mode.

Syntax

training: h' = mask ⊙ h

Example

Add dropout between hidden layers.

Code example

model = nn.Sequential(nn.Linear(128,64), nn.ReLU(), nn.Dropout(.2), nn.Linear(64,2))

Diagram

Training → random mask; evaluation → normal flow

Key Points

  • Understand the core idea of what is dropout?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q25Regularization

What is weight decay?

Interview question about what is weight decay?

Answer

Weight decay discourages large parameter values and can improve generalization. AdamW decouples weight decay from the adaptive gradient update.

Syntax

optimizer update + decay toward zero

Example

Tune a modest weight_decay using validation performance.

Code example

optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)

Diagram

Optimizer update → weight decay

Key Points

  • Understand the core idea of what is weight decay?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q26Data preparation

What is data augmentation?

Interview question about what is data augmentation?

Answer

Augmentation creates varied training views while preserving labels. Image transforms include crops and flips; transformations must reflect plausible variation and must not corrupt labels.

Syntax

x_aug = transform(x)

Example

Random crops and flips can help image classifiers.

Code example

transform = transforms.Compose([transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()])

Diagram

Original → valid random transform → training

Key Points

  • Understand the core idea of what is data augmentation?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q27Representations

What is an embedding?

Interview question about what is an embedding?

Answer

An embedding maps a discrete ID to a dense vector. Embeddings are used for tokens, categories, and items in recommendation systems.

Syntax

embedding[id] → vector in Rᵈ

Example

A vocabulary token maps to a 768-dimensional vector.

Code example

emb = nn.Embedding(30000, 768)
vectors = emb(token_ids)

Diagram

Token ID → lookup → vector

Key Points

  • Understand the core idea of what is an embedding?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q28Architectures

What is a feed-forward network?

Interview question about what is a feed-forward network?

Answer

A feed-forward network passes information from input to output without recurrent cycles. A multilayer perceptron combines dense layers and nonlinear activations.

Syntax

h = φ(W₁x+b₁); y = W₂h+b₂

Example

A tabular classifier processes fixed-size features.

Code example

model = nn.Sequential(nn.Linear(20,64), nn.ReLU(), nn.Linear(64,3))

Diagram

Input → dense layers → output

Key Points

  • Understand the core idea of what is a feed-forward network?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q29Architectures

What is a convolutional neural network?

Interview question about what is a convolutional neural network?

Answer

CNNs use local filters shared across spatial locations to detect patterns. They exploit image locality and often use fewer parameters than fully connected pixel-level layers.

Syntax

feature_map = Conv2D(input, filters, kernel)

Example

A convolution layer learns edge and texture detectors.

Code example

conv = nn.Conv2d(3, 16, kernel_size=3, padding=1)
y = conv(torch.randn(8,3,64,64))

Diagram

Image → convolution maps → pooling → classifier

Key Points

  • Understand the core idea of what is a convolutional neural network?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q30Architectures

What is an RNN?

Interview question about what is an rnn?

Answer

An RNN processes a sequence step by step while carrying a hidden state. Basic RNNs can struggle with long-range dependencies because gradients may vanish or explode.

Syntax

hₜ = φ(Wₓxₜ + Wₕhₜ₋₁ + b)

Example

A sentiment model updates state for each token.

Code example

rnn = nn.RNN(32, 64, batch_first=True)
out, h = rnn(torch.randn(8,20,32))

Diagram

Token₁ → state₁ → token₂ → state₂

Key Points

  • Understand the core idea of what is an rnn?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q31Architectures

What are LSTMs and GRUs?

Interview question about what are lstms and grus?

Answer

LSTMs and GRUs use gates to regulate information flow across sequence steps. They help preserve useful signals and remain useful in some time-series and streaming tasks.

Syntax

new state = gated combination of input and prior state

Example

An LSTM can process sensor readings in time order.

Code example

lstm = nn.LSTM(16, 64, batch_first=True)
out, (h, c) = lstm(torch.randn(4,50,16))

Diagram

Input + previous state → gates → next state

Key Points

  • Understand the core idea of what are lstms and grus?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q32Transformers

What is a transformer?

Interview question about what is a transformer?

Answer

A transformer uses attention and position information so sequence positions can exchange information. Typical blocks combine multi-head attention, feed-forward layers, residual connections, and normalization.

Syntax

block = attention + residual/norm + feed-forward + residual/norm

Example

A text model contextualizes tokens through transformer blocks.

Code example

layer = nn.TransformerEncoderLayer(d_model=128, nhead=4, batch_first=True)
y = layer(torch.randn(2,10,128))

Diagram

Tokens + positions → attention blocks → representations

Key Points

  • Understand the core idea of what is a transformer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q33Transformers

What is self-attention?

Interview question about what is self-attention?

Answer

Self-attention lets each token gather information from other allowed tokens. Query-key compatibility determines weights; weighted value vectors form the output.

Syntax

Attention(Q,K,V)=softmax(QKᵀ/√dₖ)V

Example

A pronoun can attend to relevant earlier context.

Code example

scores = Q @ K.transpose(-2,-1) / math.sqrt(Q.size(-1))
out = scores.softmax(-1) @ V

Diagram

QKᵀ → scale → softmax → weighted V

Key Points

  • Understand the core idea of what is self-attention?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q34Transformers

What are queries, keys, and values?

Interview question about what are queries, keys, and values?

Answer

Queries express what a position seeks, keys describe positions for matching, and values carry information to aggregate. Learned projections create these vectors from token states.

Syntax

Q=XWQ; K=XWK; V=XWV

Example

Each token is projected into Q, K, and V spaces.

Code example

Q, K, V = x @ Wq, x @ Wk, x @ Wv

Diagram

Token states → Q/K similarity → weighted V

Key Points

  • Understand the core idea of what are queries, keys, and values?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q35Transformers

Why scale attention scores by √dₖ?

Interview question about why scale attention scores by √dₖ?

Answer

Dot products tend to grow with vector dimension. Scaling helps keep softmax scores from becoming excessively large and saturated, supporting more stable gradients.

Syntax

scores = QKᵀ / √dₖ

Example

For dₖ=64, raw scores are divided by 8.

Code example

scores = Q @ K.transpose(-2,-1) / math.sqrt(K.size(-1))

Diagram

Dot products → scale → softmax

Key Points

  • Understand the core idea of why scale attention scores by √dₖ?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q36Transformers

What is multi-head attention?

Interview question about what is multi-head attention?

Answer

Multi-head attention runs several attention operations with different learned projections, then concatenates and projects their outputs. Heads can represent different relationships.

Syntax

MHA(X)=Concat(head₁,…,headₕ)WO

Example

With d_model 128 and 4 heads, each head often has dimension 32.

Code example

mha = nn.MultiheadAttention(128, 4, batch_first=True)
y, _ = mha(x, x, x, need_weights=False)

Diagram

Input → parallel heads → concatenate → projection

Key Points

  • Understand the core idea of what is multi-head attention?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q37Transformers

What is positional encoding?

Interview question about what is positional encoding?

Answer

Self-attention alone does not inherently encode token order. Positional information may be fixed sinusoidal, learned absolute embeddings, relative positions, or rotary embeddings.

Syntax

input = token_embedding + position_features

Example

A token receives position-specific information before transformer blocks.

Code example

positions = torch.arange(seq_len)
# Add model-specific positional embeddings to token embeddings.

Diagram

Token embeddings + positions → transformer

Key Points

  • Understand the core idea of what is positional encoding?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q38Transformers

What is a causal attention mask?

Interview question about what is a causal attention mask?

Answer

A causal mask prevents a token from attending to future tokens. It avoids leakage in next-token prediction, where each position must predict from its available prefix.

Syntax

mask[i,j] disallowed when j > i

Example

At position 3, only positions 0 through 3 are visible.

Code example

mask = torch.triu(torch.ones(5,5,dtype=torch.bool), diagonal=1)

Diagram

Position i → reads positions ≤ i

Key Points

  • Understand the core idea of what is a causal attention mask?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q39Transformers

What is an encoder-only transformer?

Interview question about what is an encoder-only transformer?

Answer

Encoder-only models commonly use bidirectional context and work well for classification, tagging, and semantic representations. Masked-language modeling is a common pretraining objective.

Syntax

tokens → bidirectional encoder → representations

Example

A text classifier pools encoder outputs to predict sentiment.

Code example

batch = tokenizer(text, return_tensors='pt')
outputs = model(**batch)

Diagram

Text → encoder → representation → task head

Key Points

  • Understand the core idea of what is an encoder-only transformer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q40Transformers

What is a decoder-only transformer?

Interview question about what is a decoder-only transformer?

Answer

Decoder-only models use causal self-attention to predict the next token from previous tokens. Generation repeatedly selects or samples a token and appends it to the context.

Syntax

P(x₁…xₙ)=ΠₜP(xₜ|x₁…xₜ₋₁)

Example

Given “The sky is”, the model predicts a distribution for the next token.

Code example

result = generator('The sky is', max_new_tokens=12, do_sample=False)

Diagram

Prompt → next token → append → repeat

Key Points

  • Understand the core idea of what is a decoder-only transformer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q41Transformers

What is an encoder-decoder transformer?

Interview question about what is an encoder-decoder transformer?

Answer

An encoder-decoder model encodes a source sequence and generates a target sequence. Decoder cross-attention lets generated tokens attend to encoder representations.

Syntax

encoder(source) → memory; decoder(prefix,memory) → next token

Example

A translation model encodes English and generates French.

Code example

translation = translator('Good morning.')

Diagram

Source → encoder memory → decoder → target

Key Points

  • Understand the core idea of what is an encoder-decoder transformer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q42Transformers

What is tokenization?

Interview question about what is tokenization?

Answer

Tokenization converts text into model-specific token IDs. A token may be a word, subword, punctuation, or byte unit; the tokenizer must match the pretrained model.

Syntax

text → tokenizer → token IDs + attention mask

Example

A word may split into multiple subword tokens.

Code example

encoded = tokenizer('Deep learning rocks!', return_tensors='pt')

Diagram

Text → token pieces → vocabulary IDs

Key Points

  • Understand the core idea of what is tokenization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q43Transformers

What is a language-model objective?

Interview question about what is a language-model objective?

Answer

The objective defines what a model predicts during pretraining. Autoregressive models predict the next token; masked language models predict selected masked tokens using surrounding context.

Syntax

causal: P(xₜ|x<ₜ); masked: predict selected token

Example

Shift input tokens so each position predicts the next token.

Code example

shift_logits = logits[:, :-1, :]
shift_labels = input_ids[:, 1:]

Diagram

Tokens → targets → loss → gradients

Key Points

  • Understand the core idea of what is a language-model objective?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q44Training

What is transfer learning?

Interview question about what is transfer learning?

Answer

Transfer learning reuses a pretrained model for a target task. It can reduce data and compute needs, but transfer quality depends on domain fit and must be validated.

Syntax

pretrained model → adapt → evaluate

Example

Adapt an image model to a small set of product categories.

Code example

model = resnet18(weights=ResNet18_Weights.DEFAULT)
model.fc = nn.Linear(model.fc.in_features, 5)

Diagram

Source data → pretrained weights → target task

Key Points

  • Understand the core idea of what is transfer learning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q45Training

What is fine-tuning?

Interview question about what is fine-tuning?

Answer

Fine-tuning continues training a pretrained model on target examples. It can adapt to a domain, but small or noisy datasets can overfit or degrade prior capabilities.

Syntax

fine-tune = optimize pretrained parameters on target data

Example

Fine-tune a text classifier on labeled support messages.

Code example

optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)

Diagram

Checkpoint + target data → adapted checkpoint

Key Points

  • Understand the core idea of what is fine-tuning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q46Training

What is freezing layers?

Interview question about what is freezing layers?

Answer

Freezing parameters prevents their gradient updates, reducing trainable parameters and sometimes memory or overfitting. A common strategy is to train a new head before gradually unfreezing the backbone.

Syntax

parameter.requires_grad = False

Example

Freeze a pretrained backbone while training its classifier head.

Code example

for p in model.backbone.parameters(): p.requires_grad = False

Diagram

Frozen backbone → trainable head

Key Points

  • Understand the core idea of what is freezing layers?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q47Optimization

What is a learning-rate scheduler?

Interview question about what is a learning-rate scheduler?

Answer

A scheduler changes learning rate over training. Warmup increases it gradually at the start; cosine or step decay lowers it later. Scheduler timing must match optimizer steps.

Syntax

lr(t)=schedule(t, initial_lr, total_steps)

Example

Use cosine decay after a short warmup.

Code example

scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1000)

Diagram

Warmup → peak → decay

Key Points

  • Understand the core idea of what is a learning-rate scheduler?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q48Optimization

What is gradient clipping?

Interview question about what is gradient clipping?

Answer

Gradient clipping limits gradient magnitude to reduce unstable updates. Norm clipping rescales gradients when their combined norm exceeds a threshold.

Syntax

if ||g|| > τ: g ← g × τ/||g||

Example

Clip gradients to norm 1 before updating weights.

Code example

loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()

Diagram

Gradients → norm check → clip → update

Key Points

  • Understand the core idea of what is gradient clipping?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q49Optimization

What is vanishing gradient?

Interview question about what is vanishing gradient?

Answer

Vanishing gradients become very small as they propagate backward, so early layers learn slowly. Saturating activations and long recurrent chains can contribute; initialization and residual paths may help.

Syntax

early-layer gradient norm ≈ 0

Example

Deep sigmoid networks can pass tiny derivatives backward.

Code example

norms = [p.grad.norm().item() for p in model.parameters() if p.grad is not None]

Diagram

Loss → shrinking gradients → weak early updates

Key Points

  • Understand the core idea of what is vanishing gradient?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q50Optimization

What is exploding gradient?

Interview question about what is exploding gradient?

Answer

Exploding gradients grow excessively and can cause unstable updates or NaNs. Gradient clipping, better initialization, learning-rate adjustment, and normalization may help.

Syntax

||∂L/∂θ|| becomes unusually large

Example

A recurrent model's loss becomes NaN after large updates.

Code example

torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

Diagram

Backward path → growing gradients → unstable update

Key Points

  • Understand the core idea of what is exploding gradient?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q51Optimization

What is Xavier initialization?

Interview question about what is xavier initialization?

Answer

Xavier initialization scales weights using fan-in and fan-out to preserve activation variance approximately. It is often associated with tanh-like activations and linear layers.

Syntax

Var(W) ≈ 2/(fan_in+fan_out)

Example

Initialize a tanh layer with Xavier uniform.

Code example

nn.init.xavier_uniform_(layer.weight)
nn.init.zeros_(layer.bias)

Diagram

Random weights scaled by input/output size

Key Points

  • Understand the core idea of what is xavier initialization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q52Optimization

What is He initialization?

Interview question about what is he initialization?

Answer

He initialization accounts for ReLU-like activations and often uses variance near 2/fan_in. Match the initializer to the activation and architecture.

Syntax

Var(W) ≈ 2/fan_in for ReLU

Example

Initialize a ReLU layer with Kaiming uniform.

Code example

nn.init.kaiming_uniform_(layer.weight, nonlinearity='relu')

Diagram

Fan-in-aware weights → ReLU network

Key Points

  • Understand the core idea of what is he initialization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q53Architectures

What is a residual connection?

Interview question about what is a residual connection?

Answer

A residual connection adds a block's input to its transformed output. It helps information and gradients flow through deep networks; dimensions must align or use a projection.

Syntax

y = F(x) + x

Example

An MLP block learns a residual adjustment.

Code example

def forward(self, x): return x + self.net(x)

Diagram

Input ───────────┐
  └→ F(x) ───────┴→ add

Key Points

  • Understand the core idea of what is a residual connection?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q54Normalization

What is layer normalization?

Interview question about what is layer normalization?

Answer

Layer normalization normalizes features within each example, making it independent of other batch examples. It is widely used in transformers.

Syntax

LayerNorm(x)=γ(x−μ)/√(σ²+ε)+β

Example

Normalize each token's feature vector.

Code example

norm = nn.LayerNorm(768)
y = norm(torch.randn(4,20,768))

Diagram

Features → normalize → scale/shift

Key Points

  • Understand the core idea of what is layer normalization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q55Optimization

What is mixed-precision training?

Interview question about what is mixed-precision training?

Answer

Mixed precision uses lower precision for some operations to improve throughput and reduce memory. FP16 may require loss scaling; BF16 has a wider exponent range but requires hardware support.

Syntax

autocast context + optional gradient scaler

Example

Run matrix operations in BF16 on supported GPUs.

Code example

with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
    logits = model(inputs)

Diagram

FP32 state where needed + lower-precision compute

Key Points

  • Understand the core idea of what is mixed-precision training?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q56Evaluation

What is early stopping?

Interview question about what is early stopping?

Answer

Early stopping stops when a monitored validation metric fails to improve for a patience window. Save and restore the best checkpoint rather than assuming the final epoch is best.

Syntax

stop after patience epochs without improvement

Example

Monitor validation loss and keep the minimum-loss checkpoint.

Code example

if val_loss < best: save_checkpoint(model)

Diagram

Epoch → validation → continue or stop

Key Points

  • Understand the core idea of what is early stopping?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q57Evaluation

What is a confusion matrix?

Interview question about what is a confusion matrix?

Answer

A confusion matrix compares predicted and actual classes and reveals which classes are confused. It supports precision, recall, and F1 calculations.

Syntax

actual classes × predicted classes → counts

Example

Inspect whether a model mistakes foxes for cats.

Code example

cm = confusion_matrix(y_true, y_pred)

Diagram

Actual labels × predicted labels → matrix

Key Points

  • Understand the core idea of what is a confusion matrix?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q58Evaluation

What are precision and recall?

Interview question about what are precision and recall?

Answer

Precision is the fraction of positive predictions that are correct; recall is the fraction of actual positives found. Thresholds and error costs determine the trade-off.

Syntax

precision=TP/(TP+FP); recall=TP/(TP+FN)

Example

Fraud detection may prioritize recall when missed fraud is costly.

Code example

print(precision_score(y_true,y_pred), recall_score(y_true,y_pred))

Diagram

Predictions + truth → TP/FP/FN → metrics

Key Points

  • Understand the core idea of what are precision and recall?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q59Loss functions

What is cross-entropy loss?

Interview question about what is cross-entropy loss?

Answer

Cross-entropy penalizes assigning low probability to the true class. PyTorch CrossEntropyLoss expects raw logits and integer class indices in standard multiclass usage.

Syntax

L = −log p(true class)

Example

A true class probability of 0.9 incurs less loss than 0.1.

Code example

loss = nn.CrossEntropyLoss()(logits, targets)

Diagram

Logits + target → log-softmax → loss

Key Points

  • Understand the core idea of what is cross-entropy loss?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q60Loss functions

What is mean squared error?

Interview question about what is mean squared error?

Answer

MSE averages squared prediction errors. Large errors receive disproportionate weight, so robust alternatives can be preferable when outliers dominate.

Syntax

MSE=(1/N)Σ(ŷᵢ−yᵢ)²

Example

Predict a continuous house price and compute squared error.

Code example

loss = nn.MSELoss()(predictions, targets)

Diagram

Prediction + target → squared errors → average

Key Points

  • Understand the core idea of what is mean squared error?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q61Evaluation

What is class imbalance?

Interview question about what is class imbalance?

Answer

Class imbalance means labels have different frequencies. Accuracy may hide poor minority-class performance; use per-class metrics, suitable splits, and carefully validated weighting or resampling.

Syntax

accuracy alone may mislead

Example

If 99% are negative, an always-negative model scores 99% accuracy.

Code example

print(classification_report(y_true, y_pred, zero_division=0))

Diagram

Skewed classes → majority bias risk

Key Points

  • Understand the core idea of what is class imbalance?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q62Optimization

What is hyperparameter tuning?

Interview question about what is hyperparameter tuning?

Answer

Parameters are learned weights; hyperparameters include learning rate, batch size, depth, and weight decay. Tune on validation data, not the test set.

Syntax

candidate config → train → validation score

Example

Compare several learning rates using a fixed split.

Code example

for lr in [1e-3, 3e-4]: print('candidate', lr)

Diagram

Search → train → validation comparison

Key Points

  • Understand the core idea of what is hyperparameter tuning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q63Evaluation

What is a learning curve?

Interview question about what is a learning curve?

Answer

Learning curves plot metrics against epochs, data size, or compute. Comparing training and validation curves helps diagnose overfitting and underfitting.

Syntax

plot(epoch, train_loss), plot(epoch, val_loss)

Example

Validation loss rising as training loss falls suggests overfitting.

Code example

history = {'train_loss': [], 'val_loss': []}

Diagram

Epoch → train and validation curves

Key Points

  • Understand the core idea of what is a learning curve?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q64Experiment management

What is reproducibility?

Interview question about what is reproducibility?

Answer

Reproducibility requires recording seeds, data versions, configs, code revisions, environments, and metrics. Seeds help but do not guarantee identical results across hardware and nondeterministic kernels.

Syntax

seed + versioned data/code + logged config

Example

Save the random seed and package versions for each run.

Code example

random.seed(42); np.random.seed(42); torch.manual_seed(42)

Diagram

Versioned inputs + config → traceable experiment

Key Points

  • Understand the core idea of what is reproducibility?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q65Data preparation

What is data leakage?

Interview question about what is data leakage?

Answer

Leakage occurs when information unavailable at prediction time influences training or evaluation. Fit preprocessing on training data only, prevent duplicates across splits, and respect time boundaries.

Syntax

split → fit transform on train → transform holdouts

Example

Scaling all data before splitting leaks validation statistics.

Code example

pipe = make_pipeline(StandardScaler(), LogisticRegression())
pipe.fit(X_train, y_train)

Diagram

Split first → train-only fit → holdout transform

Key Points

  • Understand the core idea of what is data leakage?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q66Experiment management

What is model checkpointing?

Interview question about what is model checkpointing?

Answer

A checkpoint stores model weights and may include optimizer, scheduler, epoch, and metadata. Saving full state helps resume training; deployment may need only weights plus versioned architecture and preprocessing.

Syntax

torch.save({'model': model.state_dict()}, path)

Example

Save the best validation checkpoint.

Code example

torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict()}, 'checkpoint.pt')

Diagram

Training state → checkpoint → restore

Key Points

  • Understand the core idea of what is model checkpointing?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q67Performance

What is GPU acceleration?

Interview question about what is gpu acceleration?

Answer

GPUs parallelize matrix operations and convolutions. Speedup depends on batch size, model size, memory transfers, kernels, and hardware; tiny models may not benefit much.

Syntax

device = cuda if available else cpu

Example

Move model and input tensors to the same device.

Code example

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)

Diagram

Tensors → accelerator kernels → outputs

Key Points

  • Understand the core idea of what is gpu acceleration?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q68Deployment

What is inference?

Interview question about what is inference?

Answer

Inference uses a trained model on new inputs. Put modules in evaluation mode and disable gradient tracking; production also needs consistent preprocessing, monitoring, and latency management.

Syntax

model.eval(); with inference_mode(): prediction=model(x)

Example

Serve a batch of incoming records.

Code example

model.eval()
with torch.inference_mode(): prediction = model(batch)

Diagram

Request → preprocessing → model → response

Key Points

  • Understand the core idea of what is inference?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q69Deployment

What is quantization?

Interview question about what is quantization?

Answer

Quantization uses lower-precision weights or activations to reduce memory and potentially latency. Accuracy impact and speedup depend on hardware, operators, and calibration.

Syntax

float model → calibrated lower-precision model

Example

Quantize a CPU classifier and compare accuracy and latency.

Code example

# Select a quantization workflow supported by your PyTorch version/backend

Diagram

Model → quantization → benchmark

Key Points

  • Understand the core idea of what is quantization?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q70Deployment

What is pruning?

Interview question about what is pruning?

Answer

Pruning removes or zeros parameters judged less useful. Unstructured sparsity may not speed inference unless supported by the runtime; structured pruning can reduce dimensions more practically.

Syntax

mask weights or remove channels/heads

Example

Prune a small fraction of weights, fine-tune, then benchmark.

Code example

prune.l1_unstructured(layer, name='weight', amount=0.2)

Diagram

Model → prune → fine-tune → benchmark

Key Points

  • Understand the core idea of what is pruning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version

Advanced Questions

Architecture, optimization, and design trade-offs.

Q71Training

What is knowledge distillation?

Interview question about what is knowledge distillation?

Answer

Distillation trains a smaller student using a larger teacher's outputs, often softened probabilities or intermediate representations. It can reduce deployment cost but requires quality evaluation.

Syntax

L=αL_hard+(1−α)T²KL(p_teacher||p_student)

Example

A compact classifier learns from teacher probabilities.

Code example

teacher_logits = teacher(x).detach()
student_logits = student(x)

Diagram

Teacher + labels → distillation loss → student

Key Points

  • Understand the core idea of what is knowledge distillation?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q72Representation learning

What is contrastive learning?

Interview question about what is contrastive learning?

Answer

Contrastive learning pulls related representations together and pushes unrelated ones apart according to a sampling and similarity strategy. False negatives or unrealistic augmentations can hurt quality.

Syntax

maximize sim(zᵢ,z⁺), separate sim(zᵢ,z⁻)

Example

Two augmented views of the same image form a positive pair.

Code example

scores = z1 @ z2.T / temperature
loss = nn.CrossEntropyLoss()(scores, labels)

Diagram

Examples → embeddings → similarity matrix → loss

Key Points

  • Understand the core idea of what is contrastive learning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q73Representation learning

What is self-supervised learning?

Interview question about what is self-supervised learning?

Answer

Self-supervised learning derives targets from data structure rather than requiring manual labels for every example. Next-token prediction, masked-token prediction, and contrastive learning are common examples.

Syntax

raw data → pretext objective → representation

Example

A language model learns by predicting next tokens from raw text.

Code example

labels = input_ids[:, 1:]

Diagram

Unlabeled data → generated supervision → model

Key Points

  • Understand the core idea of what is self-supervised learning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q74Fundamentals

What is a foundation model?

Interview question about what is a foundation model?

Answer

A foundation model is pretrained on broad data and adapted to many downstream tasks. Broad capability does not guarantee correctness, fairness, privacy, or suitability for a particular deployment.

Syntax

pretraining → adaptation → downstream tasks

Example

A pretrained vision-language model supports image-text retrieval.

Code example

# Load a suitable pretrained checkpoint and evaluate it on the target task

Diagram

Broad data → foundation model → applications

Key Points

  • Understand the core idea of what is a foundation model?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q75Transformers

What is a Vision Transformer?

Interview question about what is a vision transformer?

Answer

A ViT splits an image into patches, embeds them, adds positional information, and processes the patch sequence with transformer blocks. Resolution and patch size determine token count and attention cost.

Syntax

image → patches → embeddings + positions → transformer

Example

A 224×224 image with 16×16 patches produces 196 patch tokens.

Code example

# Use a matching image processor and pretrained ViT checkpoint

Diagram

Image grid → patch tokens → attention → prediction

Key Points

  • Understand the core idea of what is a vision transformer?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q76Generative models

What is a diffusion model?

Interview question about what is a diffusion model?

Answer

A diffusion model learns to reverse a gradual noising process, often by predicting noise at different timesteps. Generation iteratively denoises a noise sample.

Syntax

training: add noise; sampling: denoise iteratively

Example

An image generator transforms random noise into an image.

Code example

predicted_noise = model(noisy_sample, timestep)
loss = nn.MSELoss()(predicted_noise, noise)

Diagram

Clean sample + noise schedule → denoiser → generated sample

Key Points

  • Understand the core idea of what is a diffusion model?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q77Architectures

What is a multimodal model?

Interview question about what is a multimodal model?

Answer

A multimodal model combines two or more data modalities, such as text and images. It may use separate encoders and a fusion mechanism; each modality requires suitable preprocessing and evaluation.

Syntax

encoders → fusion/alignment → prediction

Example

A model answers a question about an image.

Code example

joint = fusion(image_encoder(images), text_encoder(tokens))

Diagram

Image/text → encoders → fusion → output

Key Points

  • Understand the core idea of what is a multimodal model?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q78Applications

What is RAG in a deep-learning application?

Interview question about what is rag in a deep-learning application?

Answer

Retrieval-augmented generation retrieves relevant passages and supplies them to a generative model. It can ground answers in external documents, but retrieval failures and unsupported generation still require evaluation.

Syntax

query → retrieve top-k → context + model → answer

Example

A support assistant retrieves policy passages before responding.

Code example

passages = retriever.search(query, top_k=5)
answer = generator.generate(build_prompt(query, passages))

Diagram

Question → retrieval → context → model → response

Key Points

  • Understand the core idea of what is rag in a deep-learning application?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q79Transformers

What is a padding attention mask?

Interview question about what is a padding attention mask?

Answer

Padding makes variable-length sequences fit a batch. An attention mask identifies real tokens versus padding so the model can ignore padded positions where appropriate. Check each API's convention.

Syntax

attention_mask = 1 for real token, 0 for padding (common)

Example

Tokenize multiple sentences with padding and use generated masks.

Code example

batch = tokenizer(texts, padding=True, return_tensors='pt')

Diagram

Sequences → padding + mask → transformer

Key Points

  • Understand the core idea of what is a padding attention mask?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q80Transformers

What is context window length?

Interview question about what is context window length?

Answer

Context length is the number of tokens processed together. Longer contexts provide more information but increase memory and compute; full self-attention interactions scale quadratically with sequence length.

Syntax

attention interactions ≈ O(n²d)

Example

Doubling token length can roughly quadruple attention score interactions.

Code example

token_count = len(tokenizer(text)['input_ids'])

Diagram

Tokens → bounded context → attention computation

Key Points

  • Understand the core idea of what is context window length?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q81Sequence learning

What is teacher forcing?

Interview question about what is teacher forcing?

Answer

Teacher forcing feeds ground-truth previous target tokens during training. Inference instead feeds generated tokens, creating a train/inference difference.

Syntax

decoder input = target shifted right

Example

For target A B C, input may be start A B while predicting A B C.

Code example

decoder_input = target_ids[:, :-1]
labels = target_ids[:, 1:]

Diagram

Ground-truth prefix → decoder → next-token predictions

Key Points

  • Understand the core idea of what is teacher forcing?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q82Generation

What is beam search?

Interview question about what is beam search?

Answer

Beam search tracks multiple candidate sequences rather than only the locally best next token. It may find a higher model-scoring sequence than greedy decoding, but does not guarantee better human-perceived quality.

Syntax

keep top-k partial sequences by score

Example

Beam width 3 retains three promising continuations.

Code example

output = model.generate(input_ids, num_beams=4, max_new_tokens=40)

Diagram

Expand candidates → score → keep best beams

Key Points

  • Understand the core idea of what is beam search?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q83Generation

What does temperature do in sampling?

Interview question about what does temperature do in sampling?

Answer

Temperature rescales logits before softmax. Lower values sharpen the distribution; higher values flatten it and increase randomness. It does not guarantee factuality.

Syntax

p = softmax(logits / T)

Example

Temperature below 1 favors high-probability tokens more strongly.

Code example

probs = (logits / temperature).softmax(dim=-1)

Diagram

Logits → temperature → probabilities → sample

Key Points

  • Understand the core idea of what does temperature do in sampling?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q84Generation

What are top-k and top-p sampling?

Interview question about what are top-k and top-p sampling?

Answer

Top-k limits choices to the k highest-scoring tokens; top-p keeps the smallest set whose cumulative probability reaches p. Both alter diversity but do not guarantee factuality.

Syntax

top-k: keep k; top-p: cumulative probability ≥ p

Example

Top-k=50 or top-p=0.9 filters candidates before sampling.

Code example

output = model.generate(input_ids, do_sample=True, top_k=50, top_p=0.9)

Diagram

Distribution → candidate filter → sample

Key Points

  • Understand the core idea of what are top-k and top-p sampling?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q85Efficient fine-tuning

What is LoRA?

Interview question about what is lora?

Answer

LoRA freezes base weights and learns low-rank matrices representing a parameter update. It reduces trainable parameter count, though total compute and serving costs remain.

Syntax

W' = W + (α/r)BA

Example

Train adapters on selected attention projections.

Code example

config = LoraConfig(r=8, lora_alpha=16, target_modules=['q_proj','v_proj'])

Diagram

Frozen base + low-rank adapters → adapted model

Key Points

  • Understand the core idea of what is lora?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q86Efficient fine-tuning

What is parameter-efficient fine-tuning?

Interview question about what is parameter-efficient fine-tuning?

Answer

PEFT adapts a pretrained model by training only a small subset of parameters or added modules. Methods include LoRA, adapters, and prompt tuning; full fine-tuning may still help for substantial domain shifts.

Syntax

base model + small trainable components

Example

Use LoRA when full-model training is too expensive.

Code example

model = get_peft_model(base_model, peft_config)

Diagram

Pretrained model → PEFT components → training

Key Points

  • Understand the core idea of what is parameter-efficient fine-tuning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q87Training

What is catastrophic forgetting?

Interview question about what is catastrophic forgetting?

Answer

Catastrophic forgetting occurs when adaptation reduces performance on previously learned tasks or distributions. Representative data, conservative updates, and regression tests can help detect and mitigate it.

Syntax

target-task gain may coincide with old-task regression

Example

A model learns a narrow format but becomes worse at general instructions.

Code example

before = evaluate(model, regression_set)
# Fine-tune, then evaluate again

Diagram

Base model → narrow fine-tuning → regression check

Key Points

  • Understand the core idea of what is catastrophic forgetting?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q88Efficient fine-tuning

What is prompt tuning?

Interview question about what is prompt tuning?

Answer

Prompt tuning learns continuous embedding vectors prepended to inputs while keeping most base-model weights frozen. It differs from manually written text prompts and from LoRA weight updates.

Syntax

input embeddings = [learned soft prompt; token embeddings]

Example

Train virtual prompt vectors for a fixed classification task.

Code example

soft_prompt = nn.Parameter(torch.randn(10, hidden_size))

Diagram

Frozen model + learned virtual tokens → task behavior

Key Points

  • Understand the core idea of what is prompt tuning?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q89Evaluation

What is perplexity?

Interview question about what is perplexity?

Answer

Perplexity is the exponential of average negative log-likelihood over tokens. Lower is better on comparable tokenization and evaluation setups, but it does not directly measure helpfulness or factuality.

Syntax

PPL = exp(mean token negative log-likelihood)

Example

Evaluate on held-out text and exponentiate average token loss.

Code example

perplexity = math.exp(mean_token_nll)

Diagram

Held-out tokens → mean NLL → exponentiate

Key Points

  • Understand the core idea of what is perplexity?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q90Evaluation

What is calibration?

Interview question about what is calibration?

Answer

A classifier is calibrated when predictions at confidence c are correct about c of the time. Accuracy and calibration differ; calibration can be assessed with reliability diagrams and temperature scaling.

Syntax

confidence ≈ 0.8 → empirical accuracy ≈ 0.8

Example

A model's 95% confidence predictions are correct only 75% of the time.

Code example

# Compare confidence bins with empirical accuracy on a holdout set

Diagram

Confidence bins → empirical accuracy comparison

Key Points

  • Understand the core idea of what is calibration?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q91Deployment

What is distribution shift?

Interview question about what is distribution shift?

Answer

Distribution shift means production data or target relationships differ from training data. Covariate shift changes inputs; label shift changes class proportions; concept drift changes the input-target relationship.

Syntax

P_train(x,y) ≠ P_prod(x,y)

Example

A model trained on daylight images degrades on night images.

Code example

# Compare production feature statistics to a versioned training baseline

Diagram

Training distribution → production shift → monitor

Key Points

  • Understand the core idea of what is distribution shift?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q92Deployment

What is model drift monitoring?

Interview question about what is model drift monitoring?

Answer

Monitoring tracks input/output distributions, latency, errors, and performance when labels arrive. Drift alerts prompt investigation but do not alone prove model failure.

Syntax

monitor inputs, outputs, latency, delayed labels

Example

Alert when a feature distribution moves outside an agreed baseline.

Code example

metrics.log('prediction_latency_ms', latency_ms)

Diagram

Requests → telemetry → alerts → review

Key Points

  • Understand the core idea of what is model drift monitoring?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q93Experiment management

What is experiment tracking?

Interview question about what is experiment tracking?

Answer

Experiment tracking records configurations, metrics, artifacts, data versions, and code revisions. It makes model comparisons auditable and supports reproduction.

Syntax

run = config + metrics + artifacts + metadata

Example

Track learning rate, batch size, validation F1, and checkpoint.

Code example

run = {'lr': 3e-4, 'batch_size': 32, 'val_f1': 0.91, 'seed': 42}

Diagram

Config → training → logs → comparison

Key Points

  • Understand the core idea of what is experiment tracking?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q94Scaling

What is distributed data-parallel training?

Interview question about what is distributed data-parallel training?

Answer

Distributed data parallel replicates a model across devices, processes different batches, and synchronizes gradients. Communication overhead can limit scaling.

Syntax

forward/backward → all-reduce → update

Example

Two GPUs process different mini-batches and synchronize gradients.

Code example

# Wrap model with DistributedDataParallel after initializing the process group

Diagram

GPU gradients → all-reduce → synchronized update

Key Points

  • Understand the core idea of what is distributed data-parallel training?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q95Scaling

What is gradient accumulation?

Interview question about what is gradient accumulation?

Answer

Gradient accumulation performs several backward passes before one optimizer update, allowing a larger effective batch than memory permits. Scale losses and step the scheduler at the right cadence.

Syntax

effective batch = micro_batch × accumulation_steps × devices

Example

Accumulate four micro-batches before one update.

Code example

optimizer.zero_grad()
for xb,yb in micro_batches:
    (criterion(model(xb),yb)/4).backward()
optimizer.step()

Diagram

Micro-batch gradients → one optimizer update

Key Points

  • Understand the core idea of what is gradient accumulation?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q96Scaling

What is checkpoint sharding?

Interview question about what is checkpoint sharding?

Answer

Checkpoint sharding splits a large model's parameters across files and uses an index to map names to shards. All files and metadata must be kept together.

Syntax

parameter name → shard index → tensor

Example

A large model stores weights in multiple tensor files.

Code example

model = AutoModel.from_pretrained(model_id)

Diagram

Shards + index → reconstructed model

Key Points

  • Understand the core idea of what is checkpoint sharding?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q97Transformers

What is FlashAttention?

Interview question about what is flashattention?

Answer

FlashAttention uses IO-aware tiling to compute exact attention while reducing memory traffic and avoiding materializing the full attention matrix in high-bandwidth memory. Gains depend on hardware and shapes.

Syntax

Q,K,V → tiled attention kernel → output

Example

Use an optimized attention backend supported by the model and hardware.

Code example

# Benchmark the framework's supported optimized attention backend

Diagram

Tiled attention → lower intermediate-memory traffic

Key Points

  • Understand the core idea of what is flashattention?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q98Generation

What is KV caching?

Interview question about what is kv caching?

Answer

KV caching stores past keys and values so autoregressive generation does not recompute them for every token. It reduces repeated work but uses memory proportional to context, layers, batch, and cache dimensions.

Syntax

new Q attends to cached K/V plus new K/V

Example

Generate many tokens while reusing prior key/value states.

Code example

outputs = model.generate(input_ids, use_cache=True, max_new_tokens=100)

Diagram

Past cache + new token → next token

Key Points

  • Understand the core idea of what is kv caching?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q99Generation

What is speculative decoding?

Interview question about what is speculative decoding?

Answer

Speculative decoding uses a smaller draft model to propose tokens and a larger target model to verify them. Speedup depends on acceptance rate and verification cost.

Syntax

draft proposes → target verifies → accept/correct

Example

A small model proposes several tokens for parallel verification.

Code example

# Configure a runtime with compatible draft and target models

Diagram

Draft proposals → target verification → accepted tokens

Key Points

  • Understand the core idea of what is speculative decoding?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version
Q100Architectures

What is a mixture-of-experts model?

Interview question about what is a mixture-of-experts model?

Answer

An MoE layer routes each token to one or more expert networks. It increases total parameter capacity while activating only part per token, but routing balance and communication are important.

Syntax

output = Σ gate_weight × selected_expert(x)

Example

A token is routed to two of many feed-forward experts.

Code example

scores = router(x)
selected = scores.topk(k=2, dim=-1)

Diagram

Token → router → experts → combine

Key Points

  • Understand the core idea of what is a mixture-of-experts model?
  • Check shapes, data assumptions, and evaluation behavior
  • Validate implementation details against your framework version

Share this question bank

Send this page to someone preparing for an interview.