Core ML and LLM Concepts for Production Systems
Machine LearningModel answerLast updated
Explain key machine learning and large language model concepts including metrics, model types, benchmarking, inference optimization, and deployment considerations.
You are preparing for a technical AI engineering interview. Provide clear explanations for the following concepts, emphasizing how they apply to real-world systems:
-
Define the F1 score. When should you prefer it over accuracy as an evaluation metric?
-
What distinguishes classification from regression in terms of goals, outputs, and how you measure success?
-
Describe your approach to creating a fair benchmark for comparing machine learning or LLM-based systems.
-
Identify typical performance bottlenecks in model inference pipelines and explain strategies to improve latency and throughput.
-
Outline the key considerations for deploying an AI agent system to production.
-
For contemporary LLM applications, explain:
- The Transformer architecture (high-level overview)
- Context engineering
- Retrieval-augmented generation (RAG)
- Grounding
- Guardrails
Include concrete examples and discuss trade-offs where relevant.
Hints
Hint 1
For classification metrics, consider what happens when one class heavily outnumbers another—what does a naive baseline achieve?
Hint 2
When benchmarking systems, think about what variables you need to control and what could leak information between training and evaluation.
Hint 3
Inference optimization depends on the bottleneck: is the system compute-bound, memory-bound, or I/O-bound? Different bottlenecks need different solutions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This question assesses breadth across ML fundamentals and modern LLM practices. Strong answers demonstrate both conceptual clarity and awareness of production challenges. Aim for concise definitions followed by practical implications.
1. F1 Score vs. Accuracy
Core definition: The F1 score combines precision and recall using their harmonic mean.
- Precision = TP / (TP + FP) — of all positive predictions, how many were correct?
- Recall = TP / (TP + FN) — of all actual positives, how many did we find?
- F1 = 2 × (Precision × Recall) / (Precision + Recall)
The harmonic mean heavily penalizes imbalance. If precision is 90% but recall is 10%, F1 drops to 0.18, not 50%.
When F1 is essential: Class imbalance where the minority class matters.
Example: In fraud detection with 0.5% fraud rate, a model predicting "not fraud" for everything achieves 99.5% accuracy but 0% recall, yielding F1 = 0. F1 forces the model to actually detect fraud.
Practical considerations:
- Threshold sensitivity: F1 varies with the classification threshold. Report precision-recall curves or PR-AUC to evaluate across all thresholds, then select an operating point based on business constraints.
- Unequal costs: Standard F1 weighs precision and recall equally. If false negatives cost significantly more than false positives (or vice versa), use F-beta scores (β > 1 emphasizes recall) or directly optimize expected business cost.
- Multi-class scenarios: Choose between macro-F1 (average per-class F1, highlights poor performance on rare classes) and micro-F1 (aggregate all predictions, dominated by frequent classes).
- Missing information: F1 ignores true negatives entirely. For problems where specificity matters, supplement with additional metrics like Matthews Correlation Coefficient.
2. Classification vs. Regression
Fundamental distinction:
| Aspect | Classification | Regression |
|---|---|---|
| Output type | Discrete categories (often as probabilities) | Continuous numeric values |
| Loss function | Cross-entropy (log loss) | MSE, MAE, Huber loss |
| Metrics | Precision/recall/F1, ROC-AUC, log loss, calibration error | RMSE, MAE, MAPE, R² |
Key insights:
- Loss functions encode assumptions about errors: MSE estimates conditional mean and severely penalizes outliers; MAE estimates median and treats all errors equally; Huber loss offers a middle ground.
- Probability calibration matters: Classification models output scores, not just labels. When downstream systems use these probabilities (e.g., routing low-confidence predictions to human review), calibration is critical. Evaluate using Expected Calibration Error or Brier score.
- Problem framing flexibility: Many problems can be formulated either way. Predicting "revenue next quarter" (regression) versus "will revenue exceed $1M" (classification) depends on the decision being automated. Binary actions often favor classification.
3. Fair Benchmarking
Fair benchmarks isolate the variable being tested while controlling all others.
Data integrity:
- Use genuinely held-out test data that no candidate model was tuned on
- For time-series or user data, split by time or entity to prevent leakage
- With LLMs, verify that evaluation data wasn't in training sets (benchmark contamination is common)
- Construct private eval sets from real production cases
Controlled comparison:
- Include simple baselines (logistic regression for ML, BM25 for retrieval, current production system)
- Ensure identical conditions: same prompts, sampling parameters (temperature, top-p), retrieval corpus, hardware configuration
- Match batch sizes when comparing latency
Statistical validity:
- Run multiple random seeds or draw multiple samples
- Report confidence intervals (bootstrap over evaluation examples)
- Understand that small improvements on small datasets are often noise
Comprehensive metrics:
- Report quality, latency (p50, p95, p99), cost per request, and failure rate together
- A 2% quality improvement that triples cost may not be viable
LLM evaluation challenges:
- LLM-as-judge exhibits position bias, length bias, and self-preference
- Mitigate by randomizing answer order, using pairwise comparisons with rubrics, and validating agreement against human labels (compute Cohen's kappa)
Offline vs. online validation:
- Offline metrics gate releases and enable rapid iteration
- A/B tests measuring business outcomes (conversion rate, user satisfaction) provide final validation
4. Inference Optimization
Common bottlenecks:
- Data processing overhead: Tokenization, feature retrieval, and output parsing can dominate for small models
- Network and serialization: Cross-service calls and large payloads add latency
- Prompt processing (prefill): Compute-bound, scales linearly with prompt length
- Token generation (decode): Memory-bandwidth-bound—each token requires reading all weights and the key-value cache
- KV cache capacity: Limits concurrent requests on fixed GPU memory
- Underutilized batching: Leaves compute idle
Optimization strategies:
| Goal | Techniques |
|---|---|
| Higher throughput | Continuous batching (dynamic batching of incoming requests); PagedAttention to reduce memory fragmentation; tensor parallelism for models too large for single GPUs |
| Lower latency | Token streaming (reduce time-to-first-token); speculative decoding (small draft model proposes tokens, large model verifies); prompt compression; output length limits |
| Both | Quantization (FP16, INT8, INT4); model distillation; FlashAttention; prompt caching for repeated system messages; semantic caching of responses; model routing (easy queries to small models) |
Critical trade-off: Batch size directly affects throughput (larger is better) and latency (smaller is better). Tune batch size to meet p95 latency SLOs while maximizing throughput.
Process: Always profile before optimizing. Measure time-to-first-token, tokens-per-second, and queueing time separately to identify the actual bottleneck. Validate quality after any quantization or distillation.
5. Productionizing AI Agents
An agent orchestrates LLM calls with tool execution in a loop. Production deployment requires:
Reliability and safety:
- Define tool interfaces with strict schemas (JSON Schema) and validate inputs
- Enforce execution limits: maximum steps, wall-clock timeout, token budget, loop detection
- Implement least-privilege access—agents inherit user permissions
- Require human confirmation for irreversible actions (financial transactions, external communications)
Security:
- Sandbox code execution environments
- Treat tool outputs and retrieved documents as untrusted (potential injection vectors)
- Validate and sanitize all data crossing trust boundaries
State management:
- Persist conversation and workflow state for recovery after failures
- Use asynchronous task queues for slow-running tools
- Implement checkpointing for long-running multi-step tasks
Observability:
- Trace every interaction: prompts sent, tools called, latency, token usage
- Track aggregate metrics: task completion rate, tool error rate, human escalation rate
- Log enough detail for debugging without exposing sensitive data
Testing and deployment:
- Build scenario-based evaluation suites covering common and edge cases
- Version control prompts and models together
- Deploy via progressive rollout (canary → staged → full)
Degradation strategy:
- Provide fallbacks: simpler deterministic workflows, smaller models, or human handoff
- Fail gracefully rather than silently producing wrong results
Key trade-off: More agent autonomy increases capability but reduces reliability and testability. Use the minimum autonomy required for the task.
6. Modern LLM Concepts
Transformer Architecture
Transformers process sequences in parallel using self-attention:
- Input encoding: Tokens are converted to embeddings and enriched with positional information (e.g., rotary embeddings)
- Self-attention: Each token attends to all other tokens, computing weighted combinations based on learned relevance. Multi-head attention allows the model to focus on different aspects simultaneously
- Feed-forward layers: Applied independently to each token position, providing non-linear transformations
- Layer stacking: Deep networks (dozens of layers) enable hierarchical representation learning
- Decoding: For generation, the model autoregressively predicts the next token given all previous tokens
Key advantage: parallelizable training (unlike RNNs) while capturing long-range dependencies.
Context Engineering
Crafting effective prompts to guide model behavior:
- System messages: Set role, tone, constraints, and output format
- Few-shot examples: Demonstrate desired input-output patterns
- Chain-of-thought: Request step-by-step reasoning for complex tasks
- Structured output: Specify JSON schemas or templated formats
- Constraint specification: State what not to do, length limits, required elements
Effective context engineering reduces need for fine-tuning and enables rapid iteration.
Retrieval-Augmented Generation (RAG)
Combining retrieval with generation to ground responses in external knowledge:
- User query is embedded and used to retrieve relevant documents from a vector store or search system
- Retrieved content is injected into the prompt as context
- LLM generates response based on both query and retrieved information
Benefits: Access to current information, reduced hallucination, attribution to sources, easier knowledge updates without retraining.
Challenges: Retrieval quality directly impacts answer quality; context window limits; ensuring retrieved content is relevant and trustworthy.
Grounding
Ensuring model outputs are factually anchored to verifiable sources rather than generated from pure parametric knowledge. Techniques include:
- Providing citations to source documents
- Real-time web search integration
- Restricting answers to explicitly provided context
- Confidence calibration and uncertainty expression
Grounding reduces hallucination risk and enables verification.
Guardrails
Safety and policy enforcement mechanisms:
- Input validation: Detect prompt injection, jailbreak attempts, toxic content
- Output filtering: Block harmful, biased, or policy-violating responses
- Semantic guardrails: Ensure responses stay within allowed topics and don't contradict policies
- Structural guardrails: Enforce output format, length, and content requirements
- Monitoring: Log and alert on guardrail violations
Implementation: Rules-based filters, classifier models, LLM-based validation, or hybrid approaches. Trade-off between safety and false positive rate (overly aggressive filtering frustrates users).
Answer structure: Strong candidates define each concept precisely, then immediately connect it to production decisions and trade-offs. Depth on 2–3 topics is better than surface coverage of all six.