Multimodal ML Systems: Deployment, Retrieval, and Core Concepts
Machine LearningModel answerLast updated
Design and optimize a constrained multimodal serving system, build fast video retrieval, and explain dropout, normalization, overfitting, and RL-based LLM alignment.
Multimodal ML Systems: Deployment, Retrieval, and Core Concepts
You are being evaluated for a machine learning role at a large consumer technology company. The panel covers both practical system design and theoretical foundations. Answer all six parts; for each one, reason through trade-offs rather than just listing options.
Part 1 — Constrained Multimodal Serving
You must ship a production multimodal model (e.g., text + image, text + video, or speech + text) within hard limits on GPU memory, inference latency, and per-request cost. The current system is too slow and too expensive at scale.
Describe how you would reduce memory, latency, and cost while keeping quality within an acceptable range. Cover:
- Model-level techniques (quantization, distillation, pruning, input simplification)
- Serving-level techniques (batching, caching, kernel optimizations, tiered serving)
- Modality-specific considerations
- The trade-offs and failure modes of each approach
Part 2 — Large-Scale Video Retrieval
You have a corpus of millions of videos. Each video already has a text caption and one or more precomputed embedding vectors. You need to build a retrieval system that handles user queries with low latency and high recall.
Explain your full design, including:
- Offline preprocessing and index construction
- ANN index choice and configuration
- How you would combine lexical and dense retrieval (hybrid search)
- Reranking strategy
- How you handle new videos and deletions (freshness)
- The metrics you would track, both offline and online
Part 3 — Overfitting
Define overfitting precisely. How do you detect it during training? Walk through the most effective mitigation strategies for deep learning, ordered by impact.
Part 4 — Dropout and Inverted Dropout
Explain the intuition behind dropout as a regularizer. Then derive why inverted dropout keeps expected activations consistent between training and inference. When is dropout ineffective or actively harmful?
Part 5 — Normalization Layers
Compare BatchNorm, LayerNorm, GroupNorm, InstanceNorm, and RMSNorm across three dimensions: what statistics they normalize over, how training-time and inference-time behaviors differ, and why certain choices are preferred in transformers or small-batch settings.
Part 6 — Reinforcement Learning for LLM Alignment
Explain how reinforcement learning is used in post-training large language models — specifically the RLHF pipeline. Cover:
- The role of supervised fine-tuning as a starting point
- How a reward model is trained from human preferences
- How the policy is optimized (PPO), including the role of KL regularization
- Common failure modes
- How you would evaluate the resulting model
- How DPO differs from PPO-based RLHF and when you would prefer it
Hints
Hint 1
For Part 1, the biggest memory wins in vision-language models often come from reducing the number of visual tokens (via pooling or a resampler), not just from weight quantization — think about where the tokens actually come from and how many you really need.
Hint 2
For Part 2, think in two stages: a fast approximate recall stage (ANN + BM25) and a slower precision stage (cross-encoder reranking). Hybrid fusion with Reciprocal Rank Fusion is a practical default — know why it works without requiring score calibration.
Hint 3
For Part 6, the KL penalty is doing two distinct jobs at once — keeping the policy close to the SFT reference and preventing reward hacking. Understanding that dual role helps you explain both why it is necessary and what happens when it is set too low or too high.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1 — Constrained Multimodal Serving
Clarify before optimizing. Pin down target hardware (e.g., 24 GB L4 vs. 80 GB H100), p95 latency SLO, QPS, input sizes (resolution, video length), and an eval set with a quality floor. Without these, optimization is guesswork.
Profile first. In vision-language models, cost is usually dominated by (1) vision token count — a single image at high resolution can produce 576–2,000+ tokens — (2) KV cache size during decode, and (3) autoregressive decoding itself. Fix the actual bottleneck.
Model-level techniques
- Quantization. Weight-only INT8 or INT4 (GPTQ/AWQ) halves or quarters weight memory. FP8 on Hopper GPUs also accelerates compute. KV-cache quantization helps for long contexts. Risk: accuracy degrades on OCR and fine-grained grounding. Always re-run modality-specific evals. Keep the vision encoder and projector at higher precision if they are sensitivity-prone.
- Input and token reduction. This is usually the largest practical lever. Lower image resolution, tile only when necessary, compress visual tokens through a Q-Former or resampler (down to ~64 tokens), sample video frames sparsely via shot detection. Fewer tokens shrinks memory and speeds up attention quadratically.
- Distillation. Train a smaller backbone on teacher logits and hidden states. Highest quality-per-parameter win, but requires training compute and paired data.
- Pruning. Structured pruning (heads, layers, channels) yields real throughput gains. Unstructured sparsity rarely helps without 2:4 sparse tensor cores.
Serving-level techniques
- Continuous batching (as in vLLM) fills decode slots dynamically — essential for GPU utilization.
- Efficient kernels. FlashAttention, fused layernorm, PagedAttention, and TensorRT-LLM compilation.
- Embedding caching. Cache vision encoder outputs keyed by a content hash. Repeated media skips the encoder entirely. Add prefix caching for shared system prompts.
- Speculative decoding reduces decode latency with a small draft model.
- Tiered serving (cascade). A lightweight model handles easy requests; uncertain ones route to the full model. Saves cost in exchange for a small degradation from routing errors.
- Disaggregation. Run the encoder on cheaper GPUs (e.g., T4), decode on memory-rich ones (A100/H100).
The right answer always ends with measurement: each change is gated on quality delta, p95 latency, and cost per 1k requests.
Part 2 — Large-Scale Video Retrieval
Offline preprocessing. L2-normalize all embeddings so cosine similarity reduces to a dot product. Videos with multiple embeddings (per clip) can be indexed individually and aggregated at query time via max-sim, or mean-pooled into one vector (faster, lower recall). Clean captions, build a BM25 inverted index, and attach metadata (language, upload timestamp, safety flags).
ANN index choice.
- HNSW: high recall and low query latency, but memory-heavy (~1.5–2× raw vector size). Good for hundreds of millions of vectors where memory is available.
- IVF-PQ: compresses vectors to ~32–64 bytes each; scales to billions. Tune
nprobeto trade recall for latency. Re-score the top candidates with full-precision vectors to recover PQ recall loss.
Shard by ID hash; fan out queries to all shards and merge results.
Hybrid retrieval. Lexical search (BM25) catches exact entity names, hashtags, and rare tokens. Dense search captures paraphrases and visual semantics. Run both, take the top few hundred candidates from each, and fuse via Reciprocal Rank Fusion: score = Σ 1/(k + rank_i). RRF works without calibrated scores across the two systems, which is its main practical advantage.
Reranking. Apply a cross-encoder or lightweight multimodal reranker to the top 100–200 candidates. Blend in engagement and freshness features. Keep total reranking latency under ~30 ms.
Freshness. New videos land in a small real-time flat or HNSW buffer queried in parallel with the main index. Deletions are handled via tombstones. Periodically merge the buffer into the main index. Trade-off: rebuild cost vs. staleness vs. index quality degradation from incremental inserts.
Metrics. Offline: Recall@k, nDCG@k, MRR, and ANN recall vs. exact kNN (isolates index loss from model quality). Serving: p50/p99 query latency, QPS per node, memory per vector. Online: CTR, watch time, A/B experiment lift.
Part 3 — Overfitting
Definition. Overfitting occurs when a model fits idiosyncrasies or noise in the training distribution, causing training loss to decrease while validation loss plateaus or increases. Generalization error grows even as empirical risk shrinks.
Detection. Training–validation loss divergence; validation metric degrading over epochs; high variance across cross-validation folds; performance drop on held-out or out-of-distribution slices.
Mitigations (roughly by impact):
- More or higher-quality data; data augmentation (crops, mixup, CutMix for vision; SpecAugment for audio)
- Early stopping on validation loss
- Weight decay (L2 via AdamW)
- Dropout and stochastic depth
- Label smoothing
- Capacity reduction — or pretrained backbone with parameter-efficient fine-tuning (LoRA, layer freezing)
- Ensembling
Common mistake: using the test set to make regularization decisions. That is overfitting at the hyperparameter level and invalidates the test set.
Part 4 — Dropout and Inverted Dropout
Intuition. At each training step, each unit is zeroed with probability q. This prevents co-adaptation — units cannot rely on specific partners being present — and forces the network to learn redundant representations. It is equivalent to training an exponential number of subnetworks sharing weights and averaging their predictions at test time.
Inverted dropout derivation. With keep probability p = 1 − q:
y = (m ⊙ x) / p, where m_i ~ Bernoulli(p)
Taking expectations:
E[y_i] = (p · x_i) / p = x_i
The expected output equals the input, so the scale seen during training matches inference exactly. At test time, dropout is simply the identity — no rescaling is needed. Without the 1/p factor, test activations would be p times smaller than training activations, breaking layers downstream.
When dropout hurts or is ineffective:
- Large-scale pretraining or data-abundant regimes — most big LLMs use little to no dropout
- Immediately before BatchNorm — the variance shift between train and test corrupts BN's running statistics
- Convolutional feature maps — spatial correlation means element-wise dropout barely regularizes; use DropBlock or spatial dropout
- Regression or RL heads that require calibrated output variance
- Very small models — lost capacity outweighs regularization benefit
Part 5 — Normalization Layers
| Layer | Normalizes over | Training vs. inference |
|---|---|---|
| BatchNorm | Batch × spatial dimensions, per channel | Uses batch stats at train time; switches to running mean/var at inference |
| LayerNorm | All features for a single sample | Identical behavior at train and inference (no running stats) |
| GroupNorm | Subset of channels per sample | Identical at train and inference |
| InstanceNorm | Spatial dimensions per sample per channel | Identical at train and inference |
| RMSNorm | RMS of all features per sample (no mean centering) | Identical at train and inference; cheaper than LayerNorm |
Key trade-offs.
- BatchNorm fails at small batch sizes because batch statistics become noisy; it also complicates distributed training and makes inference behavior depend on batch size during training.
- LayerNorm works per-sample and is batch-size-agnostic, making it the default for transformers, RNNs, and any variable-length sequence setting.
- GroupNorm is a practical middle ground for vision models where the batch is small (e.g., object detection with 2-image batches) but spatial dimensions are large.
- InstanceNorm is common in style transfer, where per-sample style statistics are the signal, not noise.
- RMSNorm drops mean subtraction, reducing compute by ~30% with negligible quality loss. It is the default in Llama-family and many recent LLMs.
Part 6 — RL for LLM Alignment (RLHF)
Pipeline overview.
- Supervised fine-tuning (SFT). Start from a pretrained base model and fine-tune on high-quality demonstration data. This gives the policy a sensible starting distribution that RL can refine.
- Reward model training. Collect human preference pairs (response A preferred over response B). Train a reward model (usually the SFT model with a scalar head) using a Bradley-Terry ranking loss. The reward model learns to score responses.
- Policy optimization via PPO. Use the reward model as an environment signal. The policy (SFT model with updated weights) generates responses; the reward model scores them. PPO clips the policy gradient update to prevent large destabilizing steps.
KL regularization. The optimization objective is:
maximize E[r(x, y)] − β · KL(π_θ || π_SFT)
The KL term serves two purposes: it keeps the policy close to the SFT reference (maintaining language fluency and instruction-following ability) and discourages reward hacking by penalizing large deviations. β is a critical hyperparameter — too low and the model hacks the reward model; too high and the policy barely moves from SFT.
Common failure modes.
- Reward hacking / overoptimization. The policy finds inputs the reward model scores highly but humans would not, e.g., verbose but shallow responses.
- Reward model distributional shift. The reward model was trained on SFT outputs, but the policy drifts far from that distribution, making reward scores unreliable.
- Mode collapse. The policy converges to a narrow response style.
- KL instability. Poorly tuned β causes either collapse or no alignment.
Evaluation. Win rate vs. the SFT baseline judged by humans or a strong LLM judge; task-specific benchmarks (e.g., MT-Bench, AlpacaEval); safety and refusal rate on red-team prompts; regression on factuality and coding evals to detect over-alignment.
DPO vs. PPO. Direct Preference Optimization (DPO) reframes the RLHF objective as a supervised classification loss directly on preference pairs, eliminating the reward model and the online RL loop. It is simpler to implement, more stable, and cheaper — no rollout sampling or PPO clipping needed. The trade-off is that DPO is offline: it cannot improve beyond the quality of the collected preference data. PPO can explore and improve on its own generations, which matters when the preference distribution is sparse or the task requires multi-step reasoning. In practice, DPO is the default for fine-tuning from a strong SFT base; PPO is preferred when the task has a verifiable ground truth (e.g., math) or when iterative online data collection is feasible.