Tag: NLP

  • MSD0019 On-Device Small LLM Polite

    Design a small LLM that runs entirely on a phone for a privacy-preserving assistant, in the style of Apple Intelligence’s on-device foundation model or Gemini Nano on Pixel. The model must fit in roughly 2-4 GB of RAM, respond in under 300 ms on a mobile NPU, and work with the radio off.

    It also has to stay polite. It should refuse harmful requests, avoid toxic or biased outputs, and hold a respectful tone even when the user is deliberately provoking it. Battery life and offline capability matter as much as raw benchmark quality, and no user text may leave the handset.

    How would you design this system? Cover model compression and quantization for the NPU, the alignment strategy that keeps the model polite at a small scale, the on-device serving path, and how you evaluate safety without sending user data to the cloud.

    Line-art scene: a person types a provoking message into a phone whose screen shows a question mark, with callouts for 2-4 GB RAM, under 300 ms, offline with no network, and battery budget

    The Problem: a few gigabytes of RAM, a fraction of a second, no network, and a user who is testing how rude the assistant will get.

    Answer

    The design is a distilled 3B-parameter model compressed with quantization-aware training to about 2 bits per weight, served on the NPU with per-feature LoRA adapters and a tiny always-resident guard model. Politeness is trained in rather than prompted in: a large aligned teacher supplies refusal and tone supervision, a preference pass sharpens “polite but not preachy”, and safety data stays inside the quantization loss so alignment survives compression. Two decisions are pivotal. First, safety is re-verified after quantization, because low-bit weights erode refusal behavior faster than they erode average benchmark quality. Second, a separate 100M-parameter guard screens the prompt and the streamed output, so a single jailbroken generation is caught by a component that can be patched over the air without retraining the base model.

    (1) Distill + QAT + Adapters: prune and distill a large teacher into ~3B parameters, then quantization-aware train to 2-4 bits and ship 16-bit LoRA adapters per feature (summarize, reply, rewrite).
    (2) Scratch-Trained Small Model + PTQ: train a 1-2B model on curated data and apply post-training 4-bit quantization; simplest pipeline, weakest quality per byte.
    (3) Elastic Nested Model: a MatFormer-style checkpoint whose submodels can be extracted at different sizes, letting the runtime trade quality for RAM under memory pressure.
    (4) On-Device Draft + Private Cloud Escalation: answer locally by default and escalate hard prompts to a privacy-hardened server tier with explicit consent.

    On-device serving path: user prompt enters a prompt guard, then the NPU decode loop running a 2-bit base model with a task LoRA adapter, backed by an adapter store and quantized KV cache, then an output guard, then the reply, all inside a dashed device boundary

    Figure 1: Everything inside the dashed boundary runs on the handset: guard, decode loop, adapters, and cache. Nothing crosses the boundary, so every check has to happen before pixels appear.

    Clarify Before Designing:
    (1) Latency Definition: is 300 ms the time to first token or the full reply? Streaming a 60-token answer at 30 tokens per second takes two seconds no matter how good the prefill is.
    (2) Task Set and Context: which features ship (reply suggestions, summarization, rewriting), and what is the maximum prompt length? Prefill cost and KV cache size follow directly from that number.
    (3) Device Floor: which chip generation is the minimum, and what does its NPU actually execute natively (INT8, INT4, palettized weights, per-channel scales)?
    (4) Escalation Policy: is any server path permitted with consent, or is strict offline operation a product promise we cannot break?
    (5) Safety Bar: which refusal taxonomy applies, and what false-refusal rate on benign-but-edgy prompts is acceptable? Over-refusal is the failure users complain about.
    (6) Telemetry Rules: may we collect differentially private aggregate counters and opt-in donated conversations, or literally nothing?


    Login to view more content
  • DL0203 LLM Bias Detection Mitigation

    How do you detect and mitigate bias in LLM outputs, and what pipeline of classifier scoring, threshold calibration, and mitigation strategies can be applied?

    Three-panel whiteboard card for HelpDesk-7B before launch: a beta report of two matched questions treated differently, a dashboard showing one 0.04 toxicity average and a PASS status, and an unordered list of candidate fixes with open questions.

    The Problem: One week before launch, the HelpDesk-7B support assistant shows a mean toxicity of 0.04 and a PASS on the team’s dashboard, with a single gate threshold of 0.5. Meanwhile beta testers report that matched questions about two groups get different treatment, and dialect-B users say their benign messages keep getting blocked.

    Answer

    Bias is not a single scalar you can read off a model, so detection begins by fixing a measurement protocol rather than by picking a classifier. The standard construction is a counterfactual prompt set in which only a demographic token changes, several sampled generations per prompt under fixed decoding parameters, and a scorer ensemble that turns each generation into numbers (toxicity, regard, sentiment, stereotype agreement, refusal). The quantity that matters is then a gap between groups with a confidence interval, not an absolute score, because every scorer has an offset that cancels when you subtract. Only after the gaps are measured does thresholding enter, and a single global threshold is almost always wrong because the guard classifier has its own group-dependent error rates. Mitigation is a ladder from cheap and reversible to expensive and durable: system-prompt constraints, decode-time filtering with rewrite, preference tuning on paired data, and finally changes to the pretraining or SFT mixture. The hardest part in production is that the detector and the model must be evaluated together, since a biased guard silently converts fairness work into unequal censorship.

    (1) Counterfactual Prompt Design: generate matched pairs where only the group term varies, so any score difference is attributable to that token rather than to topic or length.
    (2) Scorer Ensemble, Not One Classifier: a toxicity head, a regard/sentiment head, a rubric-driven LLM judge, and a refusal detector disagree in useful ways; a single classifier both misses stereotype-without-toxicity and over-flags reclaimed language.
    (3) Gaps With Uncertainty: report \Delta_{ab} with a bootstrap confidence interval per slice, because a 2-point gap on 40 prompts is noise and a 2-point gap on 4,000 prompts is a launch blocker.
    (4) Threshold Calibration Per Slice: choose the operating point from a per-group FPR target on benign text, and record how far apart the group thresholds have to be; that distance is itself a bias metric of the guard.
    (5) Mitigation Ladder: system prompt → decode-time filter and rewrite → counterfactual data augmentation and DPO → data-mixture change, in increasing cost, latency impact, and durability.
    (6) Guard The Guard: toxicity classifiers show measured dialect bias, so evaluate the detector on group-labelled benign text before you trust any gate it powers.

    Left-to-right pipeline: counterfactual prompt pairs feed the LLM under test with eight samples per prompt at fixed decoding, which fans out to three scorers (toxicity and regard classifier, stereotype LLM judge with rubric, refusal and sentiment detector), which feed per-group aggregation of gaps with bootstrap confidence intervals, then a threshold gate calibrated per group at five percent false-flag rate, which routes to allow, rewrite and re-sample, or refuse and log slice; a bottom loop sends aggregated gaps into an offline mitigation box covering counterfactual data augmentation, DPO on paired preferences, activation steering, and a tighter system prompt, which feeds back into the model

    Figure 1: The measurement half of the pipeline is online and the mitigation half is offline. The gate on the right acts on a single generation, while the aggregation block is the only place where a bias claim can legitimately be made, because bias lives in a distributional gap and not in any individual score.

    Two implementation details decide whether the numbers mean anything. First, decoding must be frozen across the counterfactual arms: temperature, top-p, seed policy, and sample count identical, otherwise you are measuring sampling variance. Second, refusals must be scored separately. A model that answers a question about one group and declines the matched question about another has a large refusal-rate gap while showing a near-zero toxicity gap, and a pipeline that only tracks toxicity will report the model as clean. On the mitigation side, the same discipline applies in reverse: any intervention must be re-measured on the identical prompt set plus a general-capability suite, because prompt-level and decode-time fixes routinely buy a lower gap at the price of higher refusal on benign requests, which is a regression that no bias dashboard shows.

    Mathematical Formulation:
    s = f_{\phi}(x, y) \in [0, 1]
    \Delta_{ab} = \mathbb{E}[s \mid g = a] - \mathbb{E}[s \mid g = b]
    \mathrm{FPR}_g(\tau) = P(s > \tau \mid g, \mathrm{benign})
    \tau_g = \min \{ \tau : \mathrm{FPR}_g(\tau) \leq \alpha \}
    \mathrm{ECE} = \sum_{b=1}^{B} \frac{n_b}{N} |\bar{s}_b - \bar{y}_b|

    Where:

    • s is the scorer output for prompt x and generation y, produced by a guard classifier or judge with parameters \phi that are separate from the model under test.
    • g is the group or slice label attached to the prompt (demographic term, dialect, language), and a, b are the two arms of a counterfactual pair.
    • \Delta_{ab} is the group gap, the primary detection statistic; it is reported with a bootstrap interval over prompts, not over samples, since samples within a prompt are correlated.
    • \tau is the gate threshold and \alpha the tolerated false-flag rate on benign text, so \tau_g is the smallest threshold meeting that budget within group g.
    • b \in \{1, \ldots, B\} indexes confidence bins with n_b items out of N; \bar{s}_b is the mean score and \bar{y}_b the empirical label rate, so ECE measures whether a score of 0.7 actually means 70% harmful.

    Worked Calibration Example (5,000 benign sentences per group):
    \mathrm{FPR}_a(0.50) = 115 / 5000 = 0.023
    \mathrm{FPR}_b(0.50) = 455 / 5000 = 0.091
    \tau_a = 0.40
    \tau_b = 0.58

    The same threshold of 0.50 therefore flags benign text from group b roughly four times as often, and equalizing the false-flag rate at \alpha = 0.05 requires thresholds 0.18 apart. That spread is the diagnostic: it says the guard classifier, not the generator, is the largest bias source in the stack, and the correct response is usually to fix the classifier’s training data rather than to ship group-conditional thresholds.

    Line chart of false-flag rate on benign text versus gate threshold for two groups, both decreasing curves with group B consistently above group A; a vertical dashed line at threshold 0.5 meets the curves at 2.3 percent and 9.1 percent, a horizontal line marks the 5 percent target, and two circular markers show the per-group thresholds 0.40 and 0.58 that achieve 5 percent each

    Figure 2: A single operating point produces two different error rates. Reading the gate at fixed threshold hides the disparity, while reading it at fixed false-flag rate exposes it as a horizontal distance between the two curves, which is the quantity to drive toward zero when you retrain the guard.

    PropertyPrompt / system levelDecode-time filter and rewriteTraining-time (CDA, DPO)
    Where it actsInstruction and few-shot context, no weight changeGuard score on the sampled output, then re-sample or refuseWeights, via augmented pairs or preference optimization
    Cost to shipHours, revertible with a config pushOne extra forward pass per output, plus rewrite latency on flagsDays of data work and a full eval cycle per iteration
    DurabilityLow, defeated by paraphrase and long context driftMedium, bounded by the guard’s own recall and calibrationHigh, the behaviour itself moves rather than being masked
    Dominant failure modeOver-refusal on benign group-related questionsInherits the classifier’s dialect bias, so filtering is unequalCapability regression and reward hacking of the preference signal
    What to measure afterRefusal-rate gap on benign prompts per slicePer-group FPR at fixed threshold, plus added p95 latencyCounterfactual gap, general benchmarks, and win rate versus baseline

    Login to view more content
  • DL0185 CycleGAN Cycle Consistency Loss

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0091 Naive Bayes Types

    What are the different types of Naive Bayes classifiers (Gaussian, Multinomial, Bernoulli), and when is each appropriate for tasks like Microsoft’s spam filtering or medical diagnosis?

    A three-panel question card: a raw spam email in an inbox, a patient chart with continuous lab values and an unknown diagnosis, and three unlabeled candidate models, Gaussian, Multinomial and Bernoulli Naive Bayes, each marked with a question mark.

    The Problem: Two classification jobs land on your desk: a spam filter trained on raw email text, and a diagnosis model trained on continuous patient lab values. Which of the three Naive Bayes variants fits each task, and why?

    Answer

    The three main variants of Naive Bayes differ in the distribution they assume for each feature given the class, and the choice is driven by the feature type. Gaussian Naive Bayes assumes each continuous feature follows a normal distribution per class, estimated by the class-conditional mean and variance; it suits real-valued features like medical lab values or sensor readings. Multinomial Naive Bayes models integer feature counts drawn from a multinomial distribution, and in practice TF-IDF weights are often substituted even though they are not counts; it is the standard for text classification, used in Microsoft’s spam filtering training module and production review-spam detection processing 85,000 reviews per day. Bernoulli Naive Bayes models binary presence/absence indicators with a Bernoulli distribution; it suits boolean features like “contains word X” or “has flag Y” and explicitly accounts for the absence of a feature, which Multinomial NB does not.

    (1) Gaussian NB (Continuous): estimates \mu_{yj} and \sigma_{yj}^2 per class per feature; best for real-valued features like blood pressure, age, or sensor readings; assumes normality, so skewed or multi-modal features need transformation or kernel density estimation.
    (2) Multinomial NB (Count Data): estimates P(w_j \mid y) = (N_{yj} + \alpha) / (N_y + \alpha d); the standard for text classification on word counts, and commonly run on TF-IDF weights as a practical approximation; Microsoft’s training module uses it for email spam filtering, and a production system classifies 85,000 reviews/day at AUC above 0.99.
    (3) Bernoulli NB (Binary Presence): estimates P(x_j = 1 \mid y) and explicitly models P(x_j = 0 \mid y); best for short documents or boolean feature sets where absence is informative; scikit-learn ships it alongside categorical and complement variants, and the R naivebayes package adds a Poisson variant for count features.

    Three panels: Gaussian NB shows bell curves per class for a continuous feature; Multinomial NB shows a bar chart of word count probabilities per class; Bernoulli NB shows a binary presence/absence table with P(x=1|y) and P(x=0|y)

    Figure 1: The three Naive Bayes variants: Gaussian models continuous features as per-class normal distributions, Multinomial models count data as a multinomial over a vocabulary, and Bernoulli models binary presence/absence with explicit absence probabilities.

    The choice between Multinomial and Bernoulli for text depends on document length and whether absence carries information. Multinomial NB uses word frequencies, so a word appearing three times contributes three times the evidence; Bernoulli NB uses only presence, so “free” appearing once or ten times contributes the same amount, but the absence of “free” also contributes evidence. For long documents where frequency matters (emails, articles), Multinomial is standard. For short documents where presence is the signal (search queries, short reviews), Bernoulli can match or beat Multinomial. A common production pattern is TF-IDF weighting with Multinomial NB, as in the Banking77 support ticket router that classifies 13,000 banking queries into 77 intents in under 1 ms per ticket. For mixed feature types (continuous plus categorical plus binary), scikit-learn does not natively combine variants, so practitioners either discretize continuous features or use the R naivebayes package which supports mixed distributions including kernel density estimation.

    Mathematical Formulation:
    P(x_j \mid y) = \frac{1}{\sqrt{2\pi\sigma_{yj}^2}} \exp\!\left(-\frac{(x_j - \mu_{yj})^2}{2\sigma_{yj}^2}\right)
    P(x_j \mid y) = \frac{N_{yj} + \alpha}{N_y + \alpha\, d}
    P(x_j \mid y) = \theta_{yj}^{x_j}(1 - \theta_{yj})^{1 - x_j}

    Where:

    • The first equation is Gaussian NB: \mu_{yj} and \sigma_{yj}^2 are the mean and variance of feature j in class y, estimated from training data.
    • The second equation is Multinomial NB: N_{yj} is the count of feature j in class y, N_y is the total count, \alpha is Laplace smoothing, and d is the vocabulary size.
    • The third equation is Bernoulli NB: \theta_{yj} = P(x_j = 1 \mid y) is the probability that feature j is present in class y; the term (1 - \theta_{yj})^{1 - x_j} explicitly models the absence of the feature.
    VariantFeature TypeDistributionBest For
    Gaussian NBContinuous (real-valued)Normal per classMedical diagnosis, sensor data, Iris dataset
    Multinomial NBCounts or TF-IDFMultinomialEmail spam, review classification, ticket routing
    Bernoulli NBBinary presence/absenceBernoulliShort text, boolean features, spam with word presence

    Login to view more content
  • MSD0017 Meeting Summarization

    Design the system behind Zoom AI Companion’s meeting summary: after a 45-minute video meeting, every participant receives a recap, the decisions made, and their action items within a minute or two. The pipeline must handle cross-talk, accents, and bad microphones across ten speakers, and a hallucinated action item is worse than none at all.

    How would you design this system? Cover transcription, speaker attribution, the summarization stack, quality control, privacy, and cost at platform scale.

    Line-art scene: a two-by-two video call grid, a clock showing forty-five minutes elapsed, an empty notepad, and a question mark asking what was actually decided

    The Problem: forty-five minutes of overlapping speech from ten microphones must become a recap, a decision list, and attributed action items, within minutes, and one invented task destroys trust. Design the pipeline that was actually listening.

    Answer

    The design is a staged pipeline with a federated summarization stack, the approach Zoom publishes for AI Companion: streaming ASR turns audio into words, speaker diarization attributes them to people, a post-processing stage restores punctuation and domain terms, and the summarization stage drafts on a small in-house LLM, scores the draft with a learned quality model (Zoom’s Z-Scorer), and escalates to a stronger external LLM only when the score is low. The two pivotal decisions are separating “who spoke” from “what was said” (diarization plus ASR reconciled with the meeting roster, not one giant model asked to guess names) and never paying frontier-model prices for meetings a small model summarizes fine (Zoom reports comparable quality at roughly 6% of GPT-4 cost).

    (1) ASR Frontend: streaming encoder-decoder (Whisper-class) with custom vocabulary biasing for product and people names; about 95% word accuracy on real meetings.
    (2) Speaker Diarization: embedding-based turn detection (pyannote-style) reconciled with the participant roster and per-channel audio when available, so “Speaker 2” becomes “Ada”.
    (3) Structured Summarization: chained tasks with schema-checked JSON output: chapter segmentation, recap, decisions, action items with owners.
    (4) Federated Quality Control: small model drafts, a learned scorer predicts summary quality, low scores escalate to stronger LLMs, and a committee-of-LLMs cross-check suppresses hallucinated action items.
    (5) Privacy by Inheritance: summaries inherit the meeting’s access control and retention; a self-hosted-only model path serves regulated customers.

    Meeting summarization pipeline: meeting audio flows through ASR, then diarization, then an attributed transcript, then a summarization stage producing recap decisions and action items, through a quality scorer, to delivery; a dashed escalation path runs from the scorer back to a stronger LLM

    Figure 1: The pipeline: hear the words, attribute them, then summarize with schema-checked structure; the scorer, not blind trust, decides when a stronger model is worth paying for.

    Clarify Before Designing:
    (1) Live versus Post: in-meeting “catch me up” queries (seconds, incremental) or post-meeting delivery only (minutes, batch)?
    (2) Language Scope: English only, or 30-plus languages via translation assists or multilingual models?
    (3) Identity Source: is a participant roster, per-channel audio, or voice enrollment available, or must speakers stay anonymous labels?
    (4) Worst Error: which failure is most expensive here: hallucinated action items, missed decisions, or wrong attribution?
    (5) Scale and Budget: meetings per day, average length, and the cost ceiling per meeting-minute?


    Login to view more content
  • MSD0015 LLM Request Routing

    Design the routing layer for an AI assistant that chooses, per request, between a small cheap model and a large expensive one. ChatGPT’s GPT-5 does exactly this with a real-time router that picks between its fast and reasoning variants, and research frameworks like RouteLLM show a trained router can cut serving cost by over 80% while holding about 95% of the strong model’s quality.

    How would you design this system? Cover what the router sees and how it is trained, how answer quality is guarded, the cost accounting, and how the system adapts as models are added, upgraded, or deprecated.

    Line-art scene: a stream of mixed user queries arriving at a toll gate that must choose between a cheap road and an expensive road, with a running cost meter and a question mark

    The Problem: most requests are easy, a few are hard, and sending everything to the biggest model burns money on “hello”. Design the gate that sends each request down the cheapest road that still answers it well.

    Answer

    The design is a trained per-request router: a tiny scorer reads the request and predicts the probability that the strong model’s answer beats the weak one’s, then sends the request to the cheapest model expected to clear the quality bar. This is routing, not cascading, so each request normally pays for exactly one model. The two pivotal decisions are to train the router on human preference data (which model’s answer people actually preferred, as in Chatbot Arena battles) rather than hand-built rules, and to expose an explicit cost-quality operating threshold as a product knob, with an escalation fallback so a routing mistake costs extra compute, not a bad answer.

    (1) Difficulty Signals: query embedding and length, task type, tool needs, and conversation state; the router is BERT-class or smaller, ~1/1000 the cost of a strong call.
    (2) Preference-Trained Router: learn P(strong model wins | query) from human preference battles, augmented with LLM-judged comparisons; route strong when P passes the threshold.
    (3) Explicit Operating Point: the threshold is chosen on the measured cost-quality curve and recalibrated as the traffic mix drifts.
    (4) Guarded Fallback: if the small model or a verifier flags low confidence, escalate to the large model; routing errors become cost, not bad answers.
    (5) Model Registry & Shadowing: candidates live behind a versioned registry; new models are shadow-scored on live traffic before the router is retrained or recalibrated.

    LLM routing pipeline: a request enters the router, which scores win probability and dispatches to the small or large model; a dashed escalation path runs from the small model through a confidence check to the large model, and user feedback loops back into router training

    Figure 1: The routing path: one cheap score per request, one paid model call, and an escalation hatch when the cheap path doubts itself.

    Clarify Before Designing:
    (1) Candidate Set: two models or many; closed APIs, self-hosted weights, or both; is the real split fast-versus-reasoning rather than small-versus-large?
    (2) Decision Granularity: per request, per message in a conversation, or pinned per session for style consistency?
    (3) Quality Bar: which evaluation defines “good enough” (human preference, task success), and how much loss versus the always-strong policy is tolerable?
    (4) Router Budget: how much latency and cost may the router itself add per request?
    (5) Traffic Shape: what fraction of traffic is trivial chat versus hard reasoning today, and how fast does that mix drift?


    Login to view more content
  • MSD0013 Machine Translation at Scale

    Design a machine translation system for a product like Google Translate: text translation between 100+ language pairs, from high-resource pairs like English-Spanish down to low-resource languages with little parallel data, served interactively at web scale where users expect answers in a fraction of a second.

    How would you design this system? Cover the model architecture, how you get training data for low-resource languages, the serving design, and how you measure translation quality.

    Line-art scene: a grid of language nodes with dense cross edges illustrating the quadratic language-pair explosion, one document flowing in and translated copies flowing out, and a question mark over how to cover low-resource pairs

    The Problem: 100 languages mean roughly 10,000 directed pairs, most with almost no parallel data, and users still expect every pair to answer in milliseconds. Design one system that covers them all.

    Answer

    The design is a single massively multilingual encoder-decoder model trained on mined bitext plus back-translated monolingual text, with a target-language token steering generation (the NLLB recipe), behind a dual-track serving layer: a fast NMT track for short, latency-critical, terminology-sensitive text, and a fine-tuned translation LLM for long, nuanced, document-level input, which is exactly the split Google shipped in its Cloud Translation API (2024) and DeepL shipped as its next-gen model. The two pivotal decisions are the multilingual pooling (high-resource pairs teach low-resource ones through a shared representation, enabling zero-shot pairs) and the honest admission that one model family does not win everywhere: NMT still wins on latency, cost, and determinism, the LLM wins on context and fluency.

    (1) One Multilingual Model: shared encoder-decoder with a target-language token; transfer from high-resource pairs gives zero-shot coverage of unseen pairs instead of 10,000 separate models.
    (2) Data Flywheel: mine bitext from web crawls with multilingual sentence embeddings (LASER), then back-translate monolingual text to synthesize pairs for low-resource languages.
    (3) Dual-Track Serving: NMT for short/interactive/terminology-critical requests, translation LLM for long-form and idiomatic text; a router picks per request.
    (4) Quality Measurement: automatic metrics (COMET, BLEU) for regression, human MQM error marking for truth, A/B tests for product impact, all reported per language pair.
    (5) Low-Resource Strategy: zero-shot transfer first, then few-example adaptive conditioning (Google’s Adaptive Translation shows as few as 5, and up to 30k, example pairs can steer output at inference time).

    Translation architecture: source text enters a router that sends short interactive text to a fast NMT track and long nuanced text to a translation LLM track, both share multilingual training on mined bitext and back-translation, and outputs pass terminology constraints before serving

    Figure 1: Dual-track serving over one multilingual training base: the router sends short, latency-critical text to NMT and long, context-heavy text to the translation LLM; terminology constraints apply on both tracks.

    Clarify Before Designing:
    (1) Scope: text only, or also speech and image translation; and which language pairs at launch?
    (2) Latency Budget: interactive typing (sub-300 ms) versus document translation (seconds) imply different model families.
    (3) Quality Bar: gist-level understanding for users, or publication-grade output with human post-editing?
    (4) Terminology: must product names, legal terms, or brand glossaries be honored exactly?
    (5) Customization: do enterprise customers need domain adaptation (medical, legal) with their own example pairs?


    Login to view more content
  • MSD0011 LLM Evaluation Pipeline

    Your team ships an LLM-powered product: a customer-support copilot built on a foundation model API, similar in spirit to how GitHub evaluates models for Copilot before each release. The model version, prompts, retrieval index, and tools all change every few weeks, and every change can silently alter answer quality.

    Design an evaluation pipeline that runs before each release. What do you test, how do you score open-ended outputs, and how do you decide whether the new version is safe to ship?

    Line-art scene: a release train carrying a new model version and new prompts toward a production gate, a clipboard with quality metrics, and a question mark over whether the new version regressed

    The Problem: the system under test is stochastic, so a green build means nothing without a repeatable quality signal. Design the gate between “we changed the prompt” and “customers see it.”

    Answer

    The design is a CI pipeline for a stochastic system: a curated golden suite mined from real production failures, a grader ladder (deterministic checks where possible, an LLM judge calibrated against human labels where necessary, human audits on top), and a release gate that compares the candidate against the current version on quality metrics plus guardrails (safety, latency, cost). GitHub runs more than 4,000 such offline tests in CI before any Copilot model change; Anthropic’s guidance is to start with 20 to 50 tasks drawn from real failures and grow from there. The pipeline ends in a canary and A/B test, and production monitoring feeds new failures back into the suite, so the eval set is a living artifact.

    (1) Cases From Reality: the golden suite is mined from production logs, bug reports, and support tickets, not invented at a desk; 20-50 real tasks beat 500 synthetic ones.
    (2) Grader Ladder: deterministic checks first, an LLM judge (calibrated to human labels, pairwise where possible) second, human audits as the calibration anchor.
    (3) Capability vs Regression Suites: capability evals start at a low pass rate and measure progress; regression evals sit near 100% and block backsliding; saturated capability cases graduate into the regression suite.
    (4) Release Gate With Guardrails: the candidate must beat or tie the incumbent on quality with statistical significance, and must not breach guardrails on safety, latency, and cost.
    (5) Flywheel: production failures are mined, de-identified, and converted into new eval cases every release cycle.

    Release evaluation pipeline: a candidate version flows through the golden suite, deterministic checks and an LLM judge with human calibration, a release gate comparing deltas and guardrails, then canary and A/B rollout, with a loop from production logs back into the golden suite

    Figure 1: The pre-release path: golden suite, grader ladder, gate, then canary. The loop back from production logs is what keeps the suite honest as user behavior shifts.

    Clarify Before Designing:
    (1) Product Surface: single-turn answers, multi-turn chat, or an agent with tool calls; the grader design differs sharply.
    (2) What Changes per Release: model version, prompts, retrieval data, tools; each change type needs its own regression coverage.
    (3) Failure Cost: what is the worst plausible wrong answer (refund mistakes, medical tone, leaked PII) and who is accountable for it?
    (4) Human Label Budget: how many expert labels per cycle can we afford, since they anchor the judge’s calibration?
    (5) Release Cadence: weekly prompt tweaks and quarterly model upgrades imply different gate depths.


    Login to view more content
  • MSD0010 Grammar Checking Writing Assistant

    

    You are building a writing-assistance product like Grammarly. As a user types in a browser extension, email client, or mobile keyboard, the system underlines mistakes and offers corrections in near real time: spelling, punctuation, subject-verb agreement, tense, and for premium tiers, style and clarity rewrites.

    How would you design this system? Cover the model architecture, the latency budget, the training data, and how you evaluate suggestion quality.

    Line-art scene: a document page with several sentences, wavy underlines beneath a misspelled word and a grammar error, a blinking caret mid-sentence, a stopwatch annotated with a 100 ms budget, and a question mark over which model answers fast enough

    The Problem: suggestions must arrive faster than the next keystroke, and a wrong correction costs more trust than a missed error. Design the system behind the wavy underline.

    Answer

    The design is a model ladder behind a per-sentence router: cheap deterministic rules and dictionaries catch spelling and punctuation on-device, an edit-tagging Transformer (one parallel pass over the tokens emitting KEEP, DELETE, INSERT, REPLACE tags) handles most grammatical error correction in the cloud, a seq2seq model takes the sentences that need reordering, and an LLM serves style and clarity rewrites only on demand. The two pivotal decisions are routing each sentence to the cheapest model that can fix it (latency is a product feature), and tuning every error type to a precision-first operating point because false corrections erode trust faster than misses.

    (1) Error Taxonomy Drives Architecture: mechanical errors (spelling, punctuation, agreement) and open-ended style rewrites are different problems and deserve different models.
    (2) Model Ladder With Routing: rules → edit-tagger → seq2seq GEC → LLM, cheapest first; the router reads error type, confidence, and latency budget.
    (3) Precision-First Operating Points: per-error-type thresholds tuned on F0.5, since a wrong correction damages trust more than a miss.
    (4) Latency Engineering: score only the current sentence, cache unchanged text, and keep the inline path under 100 ms end to end.
    (5) Personalization & Dialect: locale (US/UK), register (casual vs formal), and per-user dismiss history modulate which suggestions fire.

    Real-time suggestion pipeline: keystrokes enter a sentence buffer with cache, a router sends the sentence to spell and rules, an edit-tagging model, a seq2seq corrector, or an async LLM, and a suggestion merger renders underlines in the editor

    Figure 1: The inline path: each finished sentence is routed to the cheapest sufficient model, and a merger dedupes overlapping suggestions before rendering underlines. Unchanged text is served from cache.

    Clarify Before Designing:
    (1) Scope: which languages and locales, and is style or clarity rewriting in scope or only mechanical correctness?
    (2) Latency Budget: how many milliseconds for inline suggestions, and is there an async path for long-form checks?
    (3) Deployment: what runs on-device versus in the cloud, given browser-extension and mobile constraints?
    (4) Privacy: may user text leave the device, and are there regulated contexts (legal, medical) to special-case?
    (5) Personalization: can we learn from per-user accept and dismiss behavior, and where may that profile live?


    Login to view more content
  • MSD0004 Long Document Attention Scalability

    

    The standard Transformer’s self-attention mechanism has a computational and memory complexity of  O(N^2) , where  N is the sequence length. For long document classification (e.g., thousands of tokens), this quadratic scaling becomes prohibitive.

    Describe one or more attention modifications you would design or choose to enable efficient and effective long document classification.

    Problem framing diagram: a full N by N attention matrix labeled O of N squared memory flows into a question mark, with the target sub-quadratic attention at equal classification accuracy

    The Problem: full self-attention costs O(N^2) in compute and memory. Redesign attention so a several-thousand-token document stays affordable without giving up classification accuracy.

    Answer

    To handle long documents, the quadratic complexity of full self-attention (O(N^2)) must be reduced. The two primary directions are Sparse Attention (Longformer, BigBird), which constrains each token to a relevant subset (a local window plus a few global tokens), and Hierarchical Attention (HATN), which applies attention within segments first and then across segment representations. Both preserve classification quality while cutting cost from O(N^2) toward linear; linearized and recurrent variants (Performer, Linformer, Transformer-XL) attack the same wall from other angles.

    (1) Sparse Attention (Mechanism): Replace the full attention matrix with a sparse design: local window attention for nearby context plus global tokens (e.g., [CLS]) that exchange information with all tokens (Longformer, BigBird).
    (2) Hierarchical Attention (Structure): Split the document into segments; apply token-level attention within each segment, then a document-level attention across segment representations (HATN, LNLF-BERT).
    (3) Linearized / Recurrent Variants: Kernel approximations (Performer, Linformer) reach true linear complexity; Transformer-XL / Compressive Transformer carry a recurrent memory across segments.

    Two attention matrices side by side in grayscale: full attention with every cell filled, and sliding window attention with only a diagonal band of width five filled

    Figure 1: Full attention (left) fills the whole N \times N matrix; sliding-window attention (right) keeps only a diagonal band: each token attends to its neighbors, and cost drops from O(N^2) to O(N \cdot w).

    Clarify Before Designing:
    (1) Document Length: typical and maximum token count: 2k, 8k, 32k?
    (2) Starting Point: adapt a pretrained BERT-style encoder, or train from scratch?
    (3) Binding Constraint: memory at training, or latency at inference?
    (4) Interaction Pattern: does classification need global token interactions (a [CLS] readout), and how long-range are the dependencies?
    (5) Budget For Change: may we modify the architecture, or only fine-tune an off-the-shelf long model?


    Login to view more content