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.
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.
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.
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