Novel and Emerging ML Techniques Questions
Stay current with recent advances: transfer learning and fine-tuning, meta-learning, few-shot learning, federated learning, continual learning, adversarial robustness. Understand their applications, benefits, and limitations. Be prepared to discuss how these could solve real problems.
MediumTechnical
136 practiced
In PyTorch, implement a concise function that performs the MAML inner-loop update for a single classification task. Given a base model, a support set (x_s, y_s), a loss function, and an inner learning rate inner_lr, compute the adapted parameters after one gradient step and return the updated parameter dictionary or a cloned model that allows outer-loop gradients to flow through the update.
Sample Answer
Approach: compute loss on support set, compute gradients w.r.t. model parameters (keeping graph for outer gradients), and apply a single SGD-like update to produce adapted parameters. Return a new state dict (or you can load into a cloned model). Use torch.autograd.grad to avoid in-place ops on original params so outer-loop gradients flow.Key points:- Uses torch.autograd.grad with create_graph=True to allow outer-loop differentiation.- Returns an OrderedDict of updated parameter tensors; can be loaded into a cloned model.Time/Space:- Time ~ one forward + backward pass O(#params + compute), Space increases due to graph for higher-order grads.Edge cases:- Some params may not receive grads (e.g., frozen layers) — handled by copying original param.Alternatives:- Use functorch.functional.vmap/jit for batching or optax-like param containers; or perform in-place updates with higher-order-friendly libraries (functorch).
python
import torch
import copy
from collections import OrderedDict
def maml_inner_update(model, x_s, y_s, loss_fn, inner_lr):
"""
Perform one MAML inner-loop update and return an OrderedDict of adapted params.
Gradients are computed with create_graph=True so outer-loop gradients can flow.
"""
# forward
preds = model(x_s)
loss = loss_fn(preds, y_s)
# get parameters as (name, param) list to preserve order
params = OrderedDict(model.named_parameters())
# compute gradients w.r.t. parameters (create_graph=True for higher-order grads)
grads = torch.autograd.grad(loss, params.values(), create_graph=True, allow_unused=True)
adapted = OrderedDict()
for (name, p), g in zip(params.items(), grads):
if g is None:
# if param did not affect loss, keep it unchanged
adapted[name] = p
else:
adapted[name] = p - inner_lr * g
return adapted
# Example to load adapted params into a cloned model:
# cloned = copy.deepcopy(model)
# cloned.load_state_dict(adapted, strict=False) # works if adapted covers same keys
# now use cloned for validation; gradients will flow back through adapted params.MediumTechnical
80 practiced
Design an experiment suite to evaluate the adversarial robustness of a production NLP classifier (for example, intent classification). Specify the attack types you would consider (character-level, synonym substitution, paraphrase-based), how to generate or source test data, evaluation metrics (attack success rate, accuracy drop, confidence calibration), and how to integrate these tests into CI to prevent regressions.
Sample Answer
Clarify goal & constraints: target intent classifier (latency, languages, allowed input channels). Build a layered experiment suite: fast unit tests for CI + heavier nightly/regression tests.Attack types to include:- Character-level: typos, keyboard proximity, homoglyphs, insertion/deletion (generate via fuzzing rules).- Word-level synonym/substitution: synonyms via WordNet, contextual substitutes via masked LM (BERT), lexical paraphrase lists.- Syntax/paraphrase-level: back-translation (EN→DE→EN), neural paraphrasers (T5), controlled template rewrites.- Semantic-preserving adversaries: antonym flips, negation injection, entity swaps to test slot sensitivity.- Gradient-based (white-box) / model-agnostic: use TextAttack/OpenAttack to craft targeted adversaries when access available.Generating/sourcing test data:- Seed from production logs: sample real utterances (anonymized) as canonical inputs.- Augment via deterministic generators (typo rules, synonym lists) and stochastic generators (LM paraphrasing, back-translation).- Curate human-verified adversarial set for high-quality ground truth; use crowdworkers to confirm label preservation.Evaluation metrics:- Attack success rate (ASR): fraction where predicted intent changes while label-preserving.- Accuracy drop relative to clean baseline and per-attack-type.- Confidence calibration: expected calibration error (ECE) and shift in confidence distribution on successful attacks.- Robustness gap per-intent and per-utterance-length; false-positive/negative cost-weighted metrics.- Latency/throughput impact for defenses (if applied).Integration into CI:- Fast tests: synthetic deterministic attacks (typos, simple synonym swaps) run on every PR with strict thresholds (e.g., ASR < 5%).- Nightly/regression: stochastic/back-translation/AutoAttack suites produce comprehensive reports; fail build only on trend regressions or high-severity drops.- Versioned test artifacts: store adversarial sets and baseline model metrics in artifact store; compare new runs to historical baselines and alert on statistically-significant regressions.- Automated triage: flag high-impact failure cases to issue tracker with reproducible inputs and model confidence traces.- Gate policy: block merges on unit-test failures; require mitigation plan when nightly regression exceeds tolerance.Defenses & validation:- Use adversarial training on generated adversaries, input normalization (spell correction, unicode normalization), and confidence thresholding/abstain policies.- Validate defenses by re-running full suite; ensure no overfitting to synthetic patterns by holding out human-verified adversaries.This suite gives quick PR feedback and deeper continuous validation to prevent regressions while surfacing interpretable failure cases for engineering remediation.
HardSystem Design
149 practiced
For a global app with 100M users across regions, design a federated learning orchestration layer that handles heterogeneous device capabilities, legal constraints (data must remain in-region), asynchronous updates, adaptive client sampling, and per-jurisdiction privacy budgets. Explain model versioning, how to simulate large-scale federation in staging, replay for testing, and mechanisms to ensure reproducible rollouts across regions.
Sample Answer
Requirements and constraints:- Functional: per-region training (data never leaves region), support heterogeneous devices, asynchronous updates, adaptive client sampling, per-jurisdiction privacy budgets, reproducible rollouts.- Non-functional: 100M users globally, low coordination overhead, auditable/legal compliance, testability.High-level architecture:- Central Orchestrator (multi-region, control-plane): issues training rounds, holds global metadata, version registry, policies.- Regional Coordinator (control-plane per jurisdiction/region): enforces data-residency, privacy budgets, local client selection, aggregation, and staging/test replay.- Client Runtime SDK (on-device): supports capabilities reporting, partial-update protocols (delta compression), secure enclaves/Tee, local DP mechanisms, model validation, backoff/retry.- Secure Aggregator: per-region cryptographic aggregation (secure sum / secure aggregation) to prevent inspection of individual updates.- Model Store & Versioning: immutable model artifacts (weights, schema, training hyperparams, compiler/opt flags), signed manifests, rollout tags per-region.- Telemetry & Audit Log: immutable event logs (for compliance, replay).Core flows:1. Capability & Policy Discovery: devices periodically report hardware (CPU/GPU/quant), connectivity, battery and region. Regional Coordinator maps device to training profile (full, lite, micro).2. Adaptive Client Sampling: multi-armed bandit controller per region that balances utility, fairness, and privacy budget consumption. Prioritize underrepresented device types and users with fresh data.3. Training Round: Orchestrator schedules rounds by region; Regional Coordinator selects clients asynchronously. Clients pull model vX, train locally respecting per-jurisdiction DP parameters, return encrypted deltas.4. Secure Aggregation & Update: Regional Aggregator performs secure sum and optional clipping/normalization, updates regional model vX+1, records delta metadata. Cross-region federation: where policy allows, meta-aggregation (e.g., model averaging of regional aggregates) occurs in aggregated, privacy-safe way—only when legal.5. Asynchronous Updates: support event-driven partial aggregation—model receives incremental contributions; staleness-aware weighting applied (recency decay, version compatibility).Privacy budgets & legal compliance:- Per-jurisdiction budget ledger maintained by Regional Coordinator. Each client contribution consumes budget according to epsilon used; coordinator enforces admission control: if budget exhausted, disable training or reduce epsilon.- Use local DP on-device + secure aggregation to minimize central exposure.- All artifacts and logs tagged with jurisdiction. No cross-region raw gradients; only allowed aggregated artifacts (and only if legal).Model versioning & reproducible rollouts:- Immutable model manifests: {model_id, version, training_config, compiler_hash, dependencies, region_policy_hash, rollout_strategy}.- Compatibility matrix for client SDKs; semantic versioning for model schema.- Rollout strategies: canary (percent of clients), device-type gated, regional staged rollout. Rollouts driven by deterministic RNG seeded by model_id+region+timestamp so selections are reproducible.- Reproducible weighting: store selection seeds, client lists, and aggregation order in audit logs so exact aggregations can be recomputed.Staging & large-scale simulation:- Synthetic client fleet simulator in cloud that mimics device heterogeneity, network conditions, regional privacy policies, skewed data distributions. Use recorded traces (real-device telemetry anonymized) to seed behavior.- Emulator runs parallel to production: run full federation cycles, stress test orchestrator, and validate DP budgets, staleness handling, and model convergence.- Kubernetes-based scalable worker pools to spin millions of simulated clients; support fault injection (network loss, battery drain).Replay for testing:- Persist complete audit trails: model requests, client responses (encrypted), seeds, and aggregation operations. For replay, re-inject the same inputs into Regional Coordinator and Secure Aggregator using deterministic RNG and fixed clocks; re-run aggregation and verify identical model artifacts.- Provide “replay sandbox” with synthetic keys to decrypt and validate pipeline without touching production keys.Mechanisms to ensure reproducible rollouts across regions:- Deterministic client sampling seeds stored per rollout.- Versioned orchestration code (infrastructure-as-code) pinned per rollout to eliminate behavioral drift.- Idempotent update application with strict ordering via vector clocks or monotonic round numbers.- Cross-region consistency checks: compare convergence metrics and divergence alarms; automatic rollback triggers if region deviates beyond thresholds.Scalability & trade-offs:- Push complexity to region coordinators to satisfy legal constraints; central Orchestrator is metadata-only.- Trade-off between faster cross-region model improvements vs strict data-residency: support higher-level meta-modeling (federated transfer) where allowed.- Secure aggregation and DP reduce signal — mitigate via more participants per round or smarter sampling.Monitoring & ops:- Real-time dashboards: privacy budget burn, client participation, per-region model performance, drift detectors.- Automated safety gates (privacy budget, performance regressions) that block rollouts.This design enforces legal boundaries, adapts to device heterogeneity, supports asynchronous contributions with reproducible, auditable rollouts and a robust staging/replay capability for safe global deployment.
HardTechnical
103 practiced
With a constrained GPU budget, design a prioritized 6-month roadmap to adopt parameter-efficient tuning (adapters/LoRA), mixed-precision training, and dataset distillation to accelerate model updates. For each initiative provide the required infrastructure changes, estimated cost or time savings, expected impact on model quality, and metrics you would track to evaluate success.
Sample Answer
Month 0 — Preparation (2 weeks)- Activities: baseline measurements (training time, GPU-hours, accuracy, latency), pick representative workloads, set success targets.- Infra: logging/experimentation stack (Weights & Biases), quota tracking, small validation cluster (1–2 GPUs).- Metrics: baseline GPU-hours per update, val metrics, iteration time.Priority 1 — Adopt Parameter-Efficient Tuning (Adapters / LoRA) (Months 0.5–3)- Plan: pilot LoRA + adapters on 1–2 common model families (e.g., BERT/transformer decoder) for fine-tuning tasks.- Infra changes: enable mixed checkpointing for partial weights, extend model repo to store sparse/adapter params, update training pipelines to load adapters and apply merge/unmerge. Add versioning for adapter artifacts.- Estimated savings: 5–20× reduction in fine-tuning GPU memory & storage for checkpoints; per-update GPU-hours reduced ~3–5× (smaller batch per GPU possible).- Expected impact on quality: minimal to small degradation (≈0–2% absolute depending on task); sometimes matches full fine-tune.- Metrics: GPU-hours per fine-tune, adapter size (MB), end-task metric delta vs full-finetune, convergence epochs, parameter-efficiency (performance per MB).- Rollout: 2–4 weeks pilot, then expand to 60% of update workflows by month 3.Priority 2 — Mixed-Precision Training (FP16 / BF16) (Months 1–4, overlaps)- Plan: enable AMP in training scripts, validate numeric stability on all target models.- Infra changes: ensure GPUs support FP16/BF16 (A100/T4/V100); upgrade CUDA/cuDNN; add automated loss-scaling and checks; CI tests for NaNs.- Estimated savings: ~1.5–2× speedup and 1.5–2× memory reduction; lower cloud cost proportional to runtime.- Expected impact on quality: negligible if properly tuned; possible rare instabilities.- Metrics: throughput (samples/sec), training time, memory usage, number of instability incidents, final model metric delta.- Rollout: 2–3 weeks for safe models, 6–8 weeks for edge cases with tweaks.Priority 3 — Dataset Distillation / Coresets (Months 3–6)- Plan: construct distilled datasets or task-specific coresets to reduce training data and accelerate updates. Start with expensive re-training tasks (large pretraining is out; focus on fine-tune/continual learning).- Infra changes: add distillation pipelines (distillation training worker), storage for distilled sets, validation harness to ensure coverage.- Estimated savings: 5–10× reduction in data-processed per update → proportional GPU-hour reduction; also faster experiments.- Expected impact on quality: if distilled carefully, small quality drop (0–3%) but faster iteration allows more frequent tuning; guardrails required.- Metrics: dataset size, training time per epoch, epochs to converge, validation performance vs full data, generalization gap, robustness on held-out cases.- Rollout: proof-of-concept 4–6 weeks, then gradual integration.Cross-cutting policies and guardrails- CI checks: automatic comparison to baseline on quality/regression tests before deployment.- Cost tracking: per-run GPU-hours, cost per update; target 50% cumulative GPU-hour reduction by month 6.- Human processes: docs, templates, and rollback for adapter merges; decision gates for quality vs cost trade-offs.Expected 6-month outcomes- Combined effect: ~3–6× faster update cycle, 50%+ reduction in GPU budget for update workflows, maintain production-quality models within a 0–3% task-specific metric window.- Key success metrics: cumulative GPU-hours/month, mean update latency (days), percentage of updates using adapters/LoRA, model metric regression rate, cost savings ($).
MediumTechnical
87 practiced
Implement in Python (PyTorch) a function `prepare_finetune_model(model_name: str, num_classes: int, freeze_until: Optional[str]) -> torch.nn.Module` that loads a pretrained model from torchvision.models (for example resnet50), freezes parameters up to `freeze_until` (layer name or None), replaces the final classifier head to match `num_classes`, and returns a model ready for training. Make sure to handle BatchNorm layers appropriately when freezing.
Sample Answer
Approach: load a pretrained torchvision model by name, walk modules in top-down order and freeze parameters up to (and including) the module named freeze_until, ensure BatchNorm layers in frozen modules are put into eval() and their params have requires_grad=False, replace the final classifier head for common model families (ResNet/RegNet -> .fc, MobileNet/EfficientNet/VGG -> .classifier). Return the model ready for training.Key points:- Freezing uses module-level traversal; parameters in frozen modules get requires_grad=False.- BatchNorm layers in frozen modules are set to eval() to fix running stats (avoids training-time momentum updates) and their affine params are frozen.- Head replacement covers common torchvision patterns (.fc and .classifier); extend for other models as needed.Complexity: O(#parameters) for toggling requires_grad; negligible memory overhead.Edge cases:- freeze_until not found -> raises error.- Different torchvision API versions (weights vs pretrained) may require small changes.- For partial fine-tuning you may prefer to freeze parameters but keep BN in train mode if fine-tuning with small batches — choose based on dataset and batch size.
python
import torch
import torch.nn as nn
import torchvision.models as models
from typing import Optional
def prepare_finetune_model(model_name: str, num_classes: int, freeze_until: Optional[str]) -> torch.nn.Module:
"""
Load a pretrained model from torchvision, freeze parameters up to (and including)
the module named `freeze_until` (if provided), handle BatchNorm correctly, replace
the classifier head to match num_classes, and return the model ready for training.
freeze_until: None -> don't freeze any layers
str -> module name (as in model.named_modules()) up to which to freeze (inclusive)
"""
# load pretrained model
if not hasattr(models, model_name):
raise ValueError(f"Unknown model_name: {model_name}")
# Note: depending on torchvision version, pretrained arg may differ (weights=...). This uses classic API.
model = getattr(models, model_name)(pretrained=True)
# Freeze logic: iterate named_modules top-down, freeze until we hit freeze_until (inclusive).
# If freeze_until is None, we don't freeze any layers.
freeze = False if freeze_until is None else True
stopped = freeze_until is None # if None, we've "already stopped" freezing
for mod_name, module in model.named_modules():
if stopped:
break if False else None # no-op to keep clarity; we use freeze flag below
# We'll manage freezing by toggling when we hit the target name.
# However we need to apply freezing to parameters - we do that by walking parameters of each module.
# (handled below)
if freeze:
# apply freezing to parameters of this module
for p in module.parameters(recurse=False):
p.requires_grad = False
# If module is BatchNorm, set to eval to use running stats and ensure its affine params don't update
if isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
module.eval()
for name, p in module.named_parameters(recurse=False):
p.requires_grad = False
# Check if current module is the stop marker
if mod_name == freeze_until:
stopped = True
freeze = False # stop freezing subsequent modules
# Edge case: if freeze_until was provided but not found, raise to avoid silent mistakes
if freeze_until is not None and not stopped:
raise ValueError(f"freeze_until='{freeze_until}' not found among model.named_modules()")
# Replace classifier head for common model families
# ResNet-like
if hasattr(model, 'fc') and isinstance(model.fc, nn.Module):
in_feats = model.fc.in_features
model.fc = nn.Linear(in_feats, num_classes)
# Models with classifier as Sequential or Linear (MobileNet, EfficientNet, VGG, AlexNet)
elif hasattr(model, 'classifier') and isinstance(model.classifier, (nn.Sequential, nn.Module)):
# Many classifier implementations are either a single Linear or a Sequential ending in Linear
if isinstance(model.classifier, nn.Sequential):
# replace last linear layer
# find last linear layer index
last_lin_idx = None
for i, layer in reversed(list(enumerate(model.classifier))):
if isinstance(layer, nn.Linear):
last_lin_idx = i
break
if last_lin_idx is None:
# fallback: replace entire classifier with a single linear
# try to infer in_features from first linear found in children
in_feats = None
for layer in model.classifier:
if isinstance(layer, nn.Linear):
in_feats = layer.in_features
break
if in_feats is None:
raise RuntimeError("Cannot infer classifier in_features to replace head")
model.classifier = nn.Linear(in_feats, num_classes)
else:
in_feats = model.classifier[last_lin_idx].in_features
model.classifier[last_lin_idx] = nn.Linear(in_feats, num_classes)
else:
# single module, try to replace if linear
if isinstance(model.classifier, nn.Linear):
in_feats = model.classifier.in_features
model.classifier = nn.Linear(in_feats, num_classes)
else:
# replace with a simple linear layer if unsure
raise RuntimeError("Unhandled classifier shape; please adapt replacement logic")
else:
raise RuntimeError("Unhandled model head type; add logic for this architecture")
return modelUnlock Full Question Bank
Get access to hundreds of Novel and Emerging ML Techniques interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.