AI and Machine Learning Background Questions
A synopsis of applied artificial intelligence and machine learning experience including models, frameworks, and pipelines used, datasets and scale, production deployment experience, evaluation metrics, and measurable business outcomes. Candidates should describe specific projects, roles played, research versus production distinctions, and technical choices and trade offs.
HardTechnical
73 practiced
You must deploy a high-performing NLP model to an edge device with 256MB of RAM and CPU-only inference. Propose a concrete compression and deployment strategy combining pruning, quantization, knowledge distillation, and architecture changes. Provide estimated trade-offs in accuracy and latency, a validation plan, and a rollout strategy for edge fleets.
Sample Answer
Approach (high level)- Target: convert a moderately sized transformer (e.g., BERT-base) to a 256MB RAM, CPU-only edge deployable model by combining architecture changes, distillation, pruning, and int8 quantization. Goal: maintain within ~1–4% absolute task accuracy loss vs baseline while achieving 3–10x latency reduction on typical edge CPUs.Concrete compression & deployment steps1. Architecture change (design student): choose a compact student architecture as the baseline for distillation — e.g., 6-layer DistilBERT / MobileBERT-lite with parameter sharing or a Linformer variant to reduce O(n^2) attention to O(n). Expected size: ~10–25 MB float32.2. Knowledge distillation: train student with soft-target + task loss from teacher (BERT-base). Use temperature T=2–4, alpha task/distill = 0.3/0.7. Train until validation loss plateaus; this transfers performance to the smaller architecture.3. Structured pruning (channel / head pruning): apply structured magnitude or importance pruning to remove attention heads and feedforward neurons; target 30–50% parameter reduction. Prefer structured pruning for CPU efficiency.4. Quantization-aware training (QAT): fine-tune the pruned student with QAT to int8 (symmetric per-tensor for weights, per-channel for critical layers). Use fake-quantization during a few epochs to recover accuracy.5. Post-training optimizations: fuse layernorm/linear where supported, convert to ONNX and run an edge runtime (e.g., ONNX Runtime with NNAPI/oneDNN optimizations) or TFLite with XNNPACK.6. Memory engineering: use memory-mapped model segments, lazy load tokenizer, use batch size 1, ensure workspace fits within 256MB (reserve for OS/process). Target final binary <50MB int8 with working set <200MB.Estimated trade-offs- Accuracy: Distillation -> ~0.5–2% drop; pruning additional 0.5–1.5%; QAT negligible or recovers ~0.2–0.5%. Overall expected 1–4% absolute loss depending on task difficulty.- Latency: compact architecture + pruning + int8 typically yields 3–10x lower latency on CPU compared to BERT-base float32. Memory footprint: from ~400+ MB to <200MB runtime.- Determinism: quantization and pruning can slightly change calibration; edge CPU variability causes latency jitter.Validation plan- Offline: evaluate on held-out test sets (task metrics + calibration metrics). Run ablation: teacher vs student vs student+prune vs student+prune+QAT.- On-device functional tests: run unit inference tests and evaluate outputs vs teacher for a sample corpus; measure throughput, p50/p95 latency, peak memory.- Robustness: test adversarial/edge inputs, tokenization edge-cases, different CPU models.- Regression criteria: max allowed task-metric drop (e.g., ≤3%), p95 latency target, memory headroom ≥10%.- CI: integrate quantization calibration, model size, and a smoke-run on representative CPU in CI.Rollout strategy for edge fleets1. Canary (shadow) mode: deploy model to 1% of devices in shadow — run in parallel with current model, log predictions and metrics (no user-facing changes).2. Canary (live): after shadow validates, enable model for 5% of traffic on non-critical user segments; monitor accuracy signals, latency, error rates for 48–72 hours.3. Progressive rollout: 5 → 20 → 50 → 100% with health checks and automated rollback triggers (e.g., >X% accuracy degradation or increased error/timeout rates).4. OTA & safety: sign binaries, use incremental delta updates, ensure rollback endpoint and forced model revert capability.5. Monitoring: collect prediction distribution drift, latency p95, memory OOMs, user-impact metrics. Schedule periodic A/B tests between compressed and baseline models for user quality signals.6. Rollback policy: immediate rollback for critical failures; gradual rollback for minor degradations.Key operational considerations- Keep teacher + baseline reproducible; store calibration tables and seeds.- Maintain instrumentation to compare student vs teacher outputs for ongoing drift detection.- If accuracy loss unacceptable, iterate: reduce pruning, increase student capacity (e.g., 8 layers), or use mixed-precision (if available) instead of pure int8.This concrete plan balances aggressive compression with careful validation and staged rollout to ensure safe, performant NLP inference on CPU-only 256MB edge devices.
MediumTechnical
89 practiced
You have 1,000 labeled images across 10 classes. Describe a transfer learning strategy using a pre-trained convolutional neural network in PyTorch to build a production-ready classifier. Cover which layers to freeze/unfreeze, learning rate choices, data augmentation, regularization, validation strategy, and how to detect overfitting on small datasets.
Sample Answer
Start with a strong pretrained backbone (e.g., ResNet50) and do staged fine-tuning: first train a new classifier head with the backbone frozen, then unfreeze top convolutional blocks and fine-tune with smaller LR.1) Model & freeze/unfreeze (PyTorch)- Load pretrained backbone, replace final FC with a small classifier (e.g., Linear -> BN -> ReLU -> Dropout -> Linear).- Phase 1: freeze backbone (requires_grad=False) and train head.- Phase 2: unfreeze last N layers / layer groups (for ResNet, unfreeze layer4 and the final conv blocks). Optionally fine-tune progressively (unfreeze layer3 next) if data permits.Example:2) Learning rates & optimizers- Phase 1 (head only): LR = 1e-3 with Adam or SGD (momentum 0.9). Weight decay = 1e-4.- Phase 2 (fine-tune): use a smaller LR for backbone (1e-5 — 1e-4) and slightly higher for head (1e-4 — 5e-4). Use discriminative LRs via parameter groups.- Use LR schedulers: OneCycleLR for short runs or ReduceLROnPlateau when monitoring val loss.3) Data augmentation (critical for 1k images)- Strong on-the-fly augmentations: RandomResizedCrop, HorizontalFlip, ColorJitter, RandomRotation, Cutout or RandomErasing.- Use advanced policies like AutoAugment/RandAugment if available.- Keep validation/test augmentation minimal (center crop + normalize).- Consider class-balanced sampling if classes imbalanced.4) Regularization- Dropout (0.3–0.5) in head, weight decay (1e-4), label smoothing (0.1) for classification.- Mixup (alpha ~0.2) and/or CutMix can help generalization on small data.- Early stopping based on validation metric.5) Validation strategy & metric- Use stratified split: train/val/test ~ 80/10/10 or 70/15/15. With very small data, prefer stratified K-fold CV (e.g., 5-fold) to estimate variance, but keep a held-out test set for final evaluation.- Track accuracy, per-class F1, macro-F1, and confusion matrix to detect class-wise failures.- Use calibration metrics (ECE) if probabilities are used downstream.6) Detecting overfitting (especially on small datasets)- Monitor training vs validation loss and metrics each epoch. Overfitting signs: training loss decreasing while validation loss increases and validation accuracy plateaus/degrades.- Watch large gap between train and val accuracy (>5–10%). Inspect per-class metrics to find class-specific overfit.- Use validation learning curves and KD/bootstrapped confidence intervals from cross-validation to measure variance.- Use TTA and ensembling for robustness; if ensembles reduce val variance, model was unstable.7) Production readiness- Save best checkpoints with metric-based checkpointing; include model state, optimizer state, label encoder, and normalization stats.- Export optimized model (TorchScript / ONNX) and include preprocessing pipeline identical to training (resize, normalize, cropping).- Add monitoring: input distribution drift, per-class accuracy, and alerts.- Profiling & quantization: consider TorchScript + quantization (post-training or QAT) if low-latency or edge deployment required.This strategy maximizes generalization on 1k images by relying on pretrained features, heavy augmentation and regularization, staged fine-tuning with conservative LRs, robust validation (stratified or k-fold), and production considerations (export, monitoring, drift detection).
python
import torch.nn as nn, torchvision.models as models
model = models.resnet50(pretrained=True)
for p in model.parameters(): p.requires_grad = False
model.fc = nn.Sequential(
nn.Linear(model.fc.in_features, 256),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(256, 10)
)
# Phase 2: unfreeze layer4
for p in model.layer4.parameters(): p.requires_grad = TrueHardSystem Design
81 practiced
Design a two-tier online fraud detection architecture: a lightweight, very low-latency model for immediate blocking decisions, and a heavier scoring pipeline for detailed risk assessment and later actions. Explain how to orchestrate the two tiers, manage partial/late-arriving features, ensure consistent decisions, and how to update both models without causing inconsistent behavior.
Sample Answer
Requirements & constraints:- Tier1: <50ms decision latency, deterministic blocking (deny/allow), uses small feature set available synchronously.- Tier2: richer scoring (<seconds–minutes), higher compute, provides risk score, alerts, human review, and feed for downstream actions.- Consistency: avoid contradictory actions (e.g., Tier1 allow then Tier2 block without reconciling).- Reliability: handle late/partial features and safe model updates.High-level architecture:- Ingress API / Edge service → Feature store (real-time and offline) + Light Feature Extractor → Tier1 model (fast, stateless, autoscaled) → Decision Router → Async Enrichment pipeline → Tier2 scorer → Action orchestrator / policy engine → Logs/Monitoring.Core components & responsibilities:1. Edge/Ingress: collect request context, perform basic heuristics, and synchronously read fast features (user/session device IP reputation, velocity counters from in-memory store like Redis).2. Real-time feature store: low-latency store (Redis/ScyllaDB) holding features required by Tier1; also write-through events to event stream (Kafka).3. Tier1 model: small, interpretable model (light GBM or distilled NN) deployed as a highly optimized container or WASM on edge; returns immediate action + provenance & confidence.4. Event stream & Enrichment: request + Tier1 output published to Kafka. Enrichment workers join with offline/slow features (transactions, device fingerprinting, ML-derived embeddings) and handle late-arriving data.5. Tier2 scorer: heavier model (ensemble/NN) consumes enriched features, writes final score and recommended action to policy engine.6. Policy engine / Orchestrator: applies business rules to combine Tier1 decision, Tier2 score, and temporal policies (e.g., rollback windows), triggers downstream (block, challenge, notify).7. Audit & Monitoring: logging, drift detection, A/B tests, canary deployments.Orchestration & consistency strategies:- Decision states: tag every event with immutable decision_id, timestamp, and decision version. Store initial Tier1 verdict and later Tier2 verdicts in a decision store.- Policy precedence: define deterministic precedence rules (e.g., Tier1 block is immediate and final for high-confidence fraud; Tier2 can escalate allowed->challenge but cannot retroactively unblock a blocked transaction unless manual review).- Compensating actions: for cases where Tier2 finds higher risk after Tier1 allowed, use compensating controls (revoke session, force logout, retroactive refund hold) and notify downstreams.- Transactional guarantees: use event-driven idempotent updates with Kafka with compacted topics and exactly-once processing where possible.Managing partial/late-arriving features:- Feature freshness levels: tag features as synchronous, nearline, or offline. Tier1 only uses synchronous; Tier2 uses all.- Imputation & uncertainty: Tier1 model trained with realistic missingness and a “missingness” indicator feature; outputs confidence score. If key features are missing and confidence low, route to conservative action (challenge) or fall back to lightweight heuristics.- Late-arrival handling: enrichment jobs reconcile late features and recompute Tier2 scores; store lineage so we can audit differences. Support backfills and re-scoring for windows of interest.Model update & rollout practices to avoid inconsistent behavior:- Co-deploy policy versioning: model version + policy version packaged together. Tier1/Tier2 both reference policy version mapping.- Canary & shadowing: deploy new model versions shadowed in production; compare outputs on live traffic without affecting actions. Use statistical tests for behavior/regression on key metrics.- Gradual rollout: ramp new model percentages (e.g., 1% → 10% → 100%) with automated rollback thresholds on false positive/negative metrics and business KPIs.- Synchronized training & validation: when updating Tier1, ensure Tier2 is aware of changes—retrain Tier2 if Tier1 features or behavior change significantly. Maintain compatibility tests: for each candidate Tier1 model, run end-to-end simulation where Tier2 scoring and policy engine evaluate downstream impacts.- Backwards-compatibility constraints: keep Tier1 feature set stable where possible. If removing features, train models to handle both old/new inputs; use feature flags to gate model behavior.- Safe defaults & kill-switch: emergency kill-switch to revert to previous model versions or deterministic rules.Metrics & monitoring:- Track latency, decision split (allow/block/challenge), false positives/negatives, user friction, financial loss, and model drift.- Set real-time alerts for sudden shifts and automated rollback.Trade-offs:- Simplicity vs accuracy: smaller Tier1 keeps latency but may increase Tier2 rescinds; policy design must balance user experience and fraud loss.- Consistency vs agility: strict precedence prevents oscillation but reduces flexibility; compensate with human review for borderline cases.This design provides low-latency protection at the edge while ensuring deep risk analysis downstream, with clear orchestration, robust handling of late features, and safe model update practices to avoid inconsistent behavior.
HardTechnical
63 practiced
Describe a production-ready pipeline (in Python or with pseudocode) to train and serve time-series forecasting models. Include data ingestion with missing timestamps handling, feature pipelines that avoid leakage (proper cutoff times), backtesting with rolling windows, model retraining strategy, and serving considerations for multiple time resolutions.
Sample Answer
To build a production-ready time-series training + serving pipeline, design components: ingestion, cleaning (fill/align timestamps), feature engineering with explicit cutoff times, rolling-window backtesting, retrain-orchestrator, and serving layer that supports multiple resolutions. Key is preventing leakage by computing features only from data available before prediction cutoff.High-level pseudocode (Python style):Key points:- Always pass an explicit cutoff timestamp to feature functions to avoid leakage.- Resample to consistent grid; choose imputation strategy appropriate to domain.- Rolling backtest simulates production by training on past only and validating on future windows.- Retrain using scheduled + signal-based triggers; use canary and shadow deployments.- Serve multiple resolutions by storing a base-resolution feature store and deriving coarser features deterministically; use online store for low-latency features and batch rebuilds for heavier aggregates.
python
# ingestion: read raw events, upsert into TS store (e.g., parquet in S3 or timeseries DB)
def ingest(stream):
batch = read_stream(stream)
# normalize timestamps, timezone
batch.timestamp = pd.to_datetime(batch.timestamp).dt.tz_convert('UTC')
upsert_to_store(batch)
# align and fill missing timestamps per series
def resample_and_impute(df, freq='1H'):
# df: columns [series_id,timestamp,value,...]
df = df.set_index('timestamp')
df = df.groupby('series_id').apply(lambda g:
g['value'].resample(freq).asfreq()) # create missing rows
# impute with last-known or model-based (no peeking)
df['value'] = df.groupby('series_id')['value'].ffill().fillna(method='bfill')
return df.reset_index()
# feature pipeline that guarantees no leakage: accepts cutoff time
def compute_features(df, cutoff, lags=[1,24,168], agg_windows=[24,168]):
# df filtered to timestamps < cutoff
df_past = df[df.timestamp < cutoff]
feats = []
for lag in lags:
feats.append(df_past.groupby('series_id')['value'].shift(lag).rename(f'lag_{lag}'))
for w in agg_windows:
feats.append(df_past.groupby('series_id')['value'].rolling(window=w).mean().reset_index(level=0, drop=True).rename(f'roll_mean_{w}'))
X = pd.concat(feats, axis=1).loc[df_past.index]
return X
# rolling-window backtest
def rolling_backtest(df, model_fn, start, end, step, horizon):
results=[]
t = start
while t + horizon <= end:
train_cutoff = t
val_cutoff = t + step
X_train = compute_features(df, cutoff=train_cutoff)
y_train = df[(df.timestamp>=train_cutoff - horizon) & (df.timestamp<train_cutoff)]['value'] # aligned target window
model = model_fn().fit(X_train, y_train)
X_val = compute_features(df, cutoff=val_cutoff)
y_val = df[(df.timestamp>=val_cutoff) & (df.timestamp<val_cutoff+horizon)]['value']
preds = model.predict(X_val)
results.append(metric(y_val, preds))
t += step
return aggregate_metrics(results)
# retraining strategy + orchestration
# - schedule daily/weekly retrain via Airflow/Kubernetes cron
# - trigger retrain when: time since last retrain > T OR drift detected (data or performance)
# - keep model registry with versions, validation gate, canary rollout
def orchestrate_retrain():
if time_to_retrain() or drift_detected():
train_full_model()
validate_on_holdout()
push_to_registry_if_ok()
deploy_canary()
monitor_canary_metrics -> promote/rollback
# serving considerations for multiple resolutions
# - maintain precomputed feature store at base resolution (e.g., 1min/1H)
# - on request, upsample/downsample features with deterministic aggregations
# - support batch and realtime: online features (Redis/Feast) + offline recompute
# - avoid leakage by computing prediction time = now_cutoff and only reading features timestamp < nowMediumTechnical
65 practiced
Explain strategies for model versioning and rollback in production environments. Cover artifact storage and immutability, metadata to store (training data checksum, code commit, hyperparameters), compatibility tests before deployment, traffic routing to old/new versions, and considerations for stateful services and caches when rolling back.
Sample Answer
Start with immutable artifact storage and a model registry: store every build (model binary, serialized weights, tokenizer, feature transforms) in an immutable artifact store (S3 with versioned buckets, GCS, or a registry like MLflow/Sagemaker Model Registry). Immutability ensures reproducible rollbacks and audit trails.Essential metadata to record with each artifact:- model_id / version tag- training-data checksum or dataset fingerprint (e.g., hash of dataset or manifest)- code commit hash and container image digest- training hyperparameters and random seed- model metrics and validation/test datasets- feature schema and transform versions- environment spec (OS, libs, accelerator)- lineage & provenance links (experiment IDs, dataset versions)Run compatibility and safety checks before deployment:- Offline unit tests: model input/output shapes, schema checks, numeric stability- Integration tests: run model through full preprocessing and postprocessing pipeline- Regression tests: compare key metrics vs baseline on holdout and edge-case slices- Smoke performance tests: latency, memory, throughput under realistic loads- Explainability / fairness checks where applicableDeployment & traffic routing patterns:- Canary: route small % of production traffic to new version, monitor key metrics and increase gradually- Blue/Green: deploy new version to parallel environment; switch traffic atomically when healthy- Shadowing: send a copy of live traffic to new model for monitoring without impacting responses- Maintain health checks and automated rollback triggers (metric thresholds, error rates)Rollback and stateful considerations:- Stateless models: rollback is usually swapping model artifact or pointing service to previous model version.- Stateful services (maintaining caches, feature stores, or hidden state): ensure state compatibility or provide migration/compensation. If new model mutates state schema, implement backward-compatible migrations or keep versioned state stores.- Caches: invalidate or version cache keys when switching models (include model version in cache keys). For rollbacks, either restore previous cache or accept cold cache warm-up; avoid serving inconsistent cached predictions.- Feature drift & dependent services: coordinate rollback with upstream feature pipelines; ensure feature transformer versions are also rolled back if needed.Operational best practices:- Automate deployments and rollbacks with CI/CD (include tests in pipeline).- Alerting and SLOs tied to model quality metrics, not just infra health.- Maintain audit logs linking production requests to model version and input checksum for debugging.- Periodically rehearse rollback procedures in staging and runbooks.These controls ensure safe, traceable deployments and make rollbacks predictable with minimal user impact.
Unlock Full Question Bank
Get access to hundreds of AI and Machine Learning Background interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.