LLM Fine-Tuning and Alignment Questions
Adapting foundation models to specific tasks and desired behavior. Covers transfer learning and using pretrained models, full and parameter-efficient fine-tuning, instruction tuning, and alignment methods such as RLHF and preference optimization. Focuses on when and how to customize a base model rather than prompt it, and the data and compute tradeoffs involved.
You must align a model for a safety-critical domain like clinical triage. Explain when RLHF is appropriate and when explicit rule-based constraints or human-in-the-loop workflows are mandatory. Outline validation, regulatory, and clinical review steps required before deployment.
Sample Answer
Direct answer: RLHF is appropriate for a safety-critical domain like clinical triage only while the model remains purely assistive, shaping tone, prioritization, and conversational safety with a human making the final decision, while any decision that could directly change patient care requires explicit rule-based hard constraints and mandatory human-in-the-loop review, RLHF alone is never sufficient for those decisions regardless of how well-trained the reward model is.
Structured elaboration:
- Where RLHF is appropriate: shaping the model's conversational behavior, reducing hallucinations, calibrating how it communicates trade-offs, and encoding a general preference for conservative recommendations, all valuable and appropriate uses of RLHF as long as the model's role stays assistive (a human clinician makes and owns the actual decision) rather than semi-automated or fully automated action-taking.
- Where explicit rule-based constraints and human-in-the-loop are mandatory, not optional: any decision that could directly affect patient care (admission or discharge decisions, medication dosing) needs hard, deterministic safety constraints that cannot be overridden by the RL-trained policy's learned preferences, for example a hard rule that the system can never recommend discharge given specific red-flag vital signs, no reward model, however well-calibrated, should be trusted as the sole safeguard for a constraint like that. Human-in-the-loop review is similarly mandatory for low-confidence or out-of-distribution inputs, rare or pediatric cases the training data likely under-represents, and any case touching a legal or ethical boundary.
- Validation, regulatory, and clinical review needed before deployment: a formal risk analysis mapping specific failure modes to mitigations; subgroup-level offline evaluation (not just an aggregate metric) across age, sex, comorbidity, and other clinically relevant segments, since a model that looks good on average can still fail a specific vulnerable subgroup; explicit safety tests confirming the rule-based hard stops cannot be bypassed by any policy behavior; clinician-centered usability testing (not just accuracy, but whether a real clinician can correctly interpret and act on the system's output under real time pressure); a prospective, shadow-mode clinical validation before the system ever influences a real decision; and a formal regulatory pathway (mapping the product to the appropriate medical-device regulatory category) with a complete technical file and clinical evaluation report, since a system influencing clinical decisions in most jurisdictions cannot ship without this regardless of how strong its offline metrics look.
- Ongoing controls after deployment: staged, monitored rollout with a rollback plan, real-time monitoring for adverse events and calibration drift, a working feedback loop that routes newly-flagged difficult cases to human review and back into the training pipeline, and periodic revalidation as the model, the data, or the clinical environment changes.
Worked example: A concrete layered design: the RLHF-tuned assistive model may recommend a conservative next step for a patient presenting with ambiguous symptoms, phrased helpfully and calibrated by the reward model's learned preferences, but a hard, deterministic rule engine sitting alongside (not learned, and not overridable by the RL policy) independently checks the case against known red-flag vital-sign thresholds and mandates escalation to a human clinician whenever those thresholds are met, regardless of what the RLHF-trained model's own recommendation was, this is the concrete mechanism that keeps RLHF's role assistive rather than decision-making for the cases that actually matter most.
Trade-offs and pitfalls: The most dangerous mistake in this domain is trusting a well-calibrated reward model as a sufficient safety mechanism on its own for decisions that materially affect patient care, a reward model can be well-calibrated on average while still failing on a rare, high-stakes case exactly the kind of case a hard rule-based constraint is specifically there to catch regardless of what the learned model does. A second pitfall is treating the regulatory and clinical-validation process as a final gate to pass through once, rather than an ongoing discipline, post-market monitoring and periodic revalidation are not optional follow-ups, they are how a system that was safe at launch stays safe as real-world data and clinical practice both continue to shift.
Compare and contrast pretraining, supervised fine-tuning, and in-context learning (few-shot prompting). For an AI Engineer deciding between these options for a new classification product, list the engineering trade-offs: compute, latency, maintainability, update frequency, and expected performance.
Sample Answer
Direct answer: Pretraining builds general language capability from large unlabeled text, supervised fine-tuning adapts a pretrained model using labeled examples, and in-context learning (few-shot prompting) uses a frozen model at inference time with examples placed directly in the prompt; for a production classification product, supervised fine-tuning is usually the right default.
Structured elaboration:
- Compute: continued pretraining is by far the most expensive (potentially weeks across many accelerators); supervised fine-tuning is moderate (GPU-hours to a few days depending on model size); in-context learning needs no training compute at all, but shifts cost to inference, since every request now carries a longer prompt through a large frozen model.
- Latency: fine-tuned and pretrained models have similar inference latency to the base model (and can be distilled smaller); in-context learning's per-query latency is typically higher and less predictable, since prompt length grows with the number of examples included.
- Maintainability: fine-tuning gives you explicit, versioned checkpoints and a well-understood retraining cycle; in-context learning has no model artifact to manage at all, which sounds simpler, but shifts the maintenance burden onto prompt engineering and guardrails, which are brittle to prompt drift and harder to test rigorously than a versioned model checkpoint.
- Update frequency: continued pretraining only makes sense for infrequent, large shifts (a new domain or language); fine-tuning supports a medium cadence, periodic retraining as labeled data accumulates; in-context learning can be updated instantly by editing the prompt, with no retraining at all.
- Expected performance for a classification product specifically: with a steady stream of labeled data, supervised fine-tuning reaches the highest accuracy most cost-effectively; in-context learning gives a reasonable zero/few-shot baseline but typically falls short of a properly fine-tuned classifier's accuracy, and is best reserved for cases where labels are scarce or iteration speed matters more than peak accuracy.
Worked example: A support-ticket classifier that needs to hit a strict latency budget and a high accuracy bar, with a steady stream of a few thousand new labeled tickets per month, is the textbook case for supervised fine-tuning: the labeled data exists and keeps growing, latency needs to be predictable, and periodic retraining is a manageable, well-understood engineering process. If instead the team only has 30 labeled examples and needs a demo working by tomorrow, in-context few-shot prompting is the pragmatic choice, accepting the higher per-query cost and lower expected accuracy in exchange for zero training time.
Trade-offs and pitfalls: Reaching for continued pretraining to solve what is really a fine-tuning problem wastes enormous compute for a shift that a much cheaper fine-tuning run would have handled; conversely, sticking with in-context learning past the prototype stage for a high-volume production classifier usually loses on both cost (every request pays for a long prompt through a large model) and accuracy compared with a properly fine-tuned smaller model. Continued pretraining is worth its cost specifically when the domain's language is substantially different from the base model's pretraining distribution, not merely when the labeled dataset is small.
Propose a scalable approach to attribute a harmful model response to training data sources or model internals. What tooling and experiments would you use to trace the cause, what remediation would you propose once a source is identified, and how would you measure remediation effectiveness at scale?
Sample Answer
Direct answer: Attributing a harmful model response to specific training data or model internals requires a combination of influence estimation, embedding-based retrieval, and targeted ablations, since no single method is reliable enough on its own, and remediation should proceed from the identified source through data, model, and deployment-level fixes with measured effectiveness at each stage.
Structured elaboration:
- Attribution tooling: influence functions (or representer-point approximations, using Hessian-vector-product approximations to make this tractable for large models) estimate how much a specific training example likely contributed to a given output; embedding-based retrieval encodes the harmful output and all candidate training passages and retrieves the nearest neighbors, which often directly surfaces a verbatim or paraphrased source; data-cartography scoring (classifying training examples by how confidently and consistently the model learned them) helps prioritize noisy or memorized examples among the influence-flagged candidates; and layer-wise probing (intervening on specific layers' activations to see whether the behavior persists) helps localize WHERE in the model the harmful association is actually stored.
- Causal validation, not just correlational scoring: a leave-one-source-out ablation, removing all examples from a candidate source and re-training or continuing training, then measuring whether the harmful behavior actually changes, is the strongest evidence a candidate source is the real cause, since influence functions and embedding retrieval are both fundamentally correlational and can point at a plausible-looking but wrong candidate; a checkpoint ablation (tracing exactly when the harmful behavior first appears across training checkpoints) further localizes WHEN in training the association was learned.
- Remediation options across three levels: data-level (removing or redacting the identified harmful source, or reweighting rather than outright deleting it if some utility from that source is worth preserving, plus adding targeted counterexamples), model-level (a quick, low-risk targeted LoRA-style patch to override the specific offending pattern, versus a slower, more thorough re-fine-tune with clarified reward modeling if the issue is more systemic, plus techniques like differential privacy or mixup if the root cause is genuine memorization), and deployment-level (a runtime retrieval filter or classifier reranker that blocks the specific provenance-triggering pattern as an immediate mitigation while the underlying training fix is prepared).
- Measuring remediation effectiveness: track the harm rate on a red-team prompt suite before and after the fix, confirm the top-k influence mass attributable to the identified source has genuinely dropped (not just that the specific example is gone), and check retrieval overlap (whether harmful outputs' nearest-neighbor retrievals still point at the removed or redacted documents); alongside this, explicitly check for collateral damage on ordinary utility metrics and across different user cohorts, since a fix that reduces harm but silently breaks unrelated behavior is not actually a net improvement.
Worked example: A concrete disambiguation between two plausible candidate sources: if embedding-based retrieval surfaces two different training-data sources as similarly close neighbors to a harmful output, a leave-one-source-out ablation, removing each candidate source independently and re-checking whether the harmful behavior actually disappears, tells you which one (if either) is the genuine causal source, rather than relying on retrieval similarity alone, which can be misleading when two unrelated sources happen to share superficial embedding-space proximity to the harmful output.
Trade-offs and pitfalls: Influence functions are useful for triaging a large candidate pool down to a manageable size but are known to be noisy at scale, treating an influence-function ranking as final proof of causation, rather than validating the top candidates with an actual ablation, risks acting on the wrong source entirely. A second pitfall is applying a quick model-level patch (a targeted LoRA fix) as if it were a complete solution, a fast patch is valuable for immediate risk reduction but should be paired with the slower data-level fix and a full re-evaluation, since a patch that merely suppresses the symptom in the specific tested cases can leave the same underlying issue reachable through a slightly different prompt.
Write a Python function to compute Kendall's Tau for a set of predicted preference scores versus ground-truth pairwise labels. Input: list of tuples (score_a, score_b, true_preference) where true_preference is 1 if a>b else 0. Output: numeric Kendall's Tau. Explain how you handle ties in scores or labels.
Sample Answer
Direct answer: Kendall's Tau for reward-model evaluation compares, across many pairs, whether the model's PREDICTED preference (from its scores) agrees with the TRUE preference label, and reduces to (concordant pairs minus discordant pairs) divided by the total number of pairs.
Structured elaboration: For each pair, the predicted preference is derived from comparing score_a and score_b (a is predicted-preferred if score_a > score_b); if that predicted preference matches the true_preference label, the pair is concordant, if it disagrees, it is discordant. Ties in the predicted scores (score_a exactly equal to score_b) are neither concordant nor discordant, they still count in the denominator (this is one defensible convention among a few for handling ties in Tau; the specific convention should be stated explicitly, since Tau has more than one standard variant).
Worked example (executed):
def kendalls_tau(pairs):
"""pairs: list of (score_a, score_b, true_preference), true_preference=1 if a>b else 0."""
n = len(pairs)
if n == 0:
return 0.0
concordant = discordant = tied = 0
for score_a, score_b, true_pref in pairs:
predicted_pref = 1 if score_a > score_b else (0 if score_a < score_b else None)
if predicted_pref is None:
tied += 1
continue
if predicted_pref == true_pref:
concordant += 1
else:
discordant += 1
return (concordant - discordant) / n
I verified this against three cases: all predictions agreeing with ground truth gives tau exactly 1.0; all predictions disagreeing gives tau exactly -1.0; and a mixed case with 2 concordant pairs, 1 discordant pair, and 1 predicted-score tie out of 4 total pairs gives (2−1)/4=0.25, matching the function's output exactly.
Trade-offs and pitfalls: Silently dropping tied pairs from BOTH the numerator and the denominator (rather than keeping them in the denominator as this implementation does) produces a different numeric convention and would not be comparable to a Tau computed the way scikit-learn or scipy define it by default, so the tie-handling convention should always be documented alongside any reported Tau value. A second consideration: Kendall's Tau treats every pair equally regardless of how large or small the true or predicted score gap is, so a reward model that gets every pair's ORDERING right but is badly miscalibrated in magnitude would still score a perfect Tau of 1.0, this metric measures ranking agreement, not calibration, and should be paired with a calibration check (like the reward-model calibration techniques discussed elsewhere in this pipeline) rather than used alone.
Explain how to integrate RLHF training and deployment into an ML CI/CD pipeline: reproducible training runs, automated evaluation gates (offline plus human review), canary and shadow deployments for RL-trained policies, model versioning, and safe rollback when production metrics regress. What lineage and logging metadata would you record (dataset versions, prompt templates, annotator IDs, seeds, model checkpoints, and for production interactions: prompts, model outputs, log-probs, timestamps, and judgments) to support audits, reproducibility, and rollback?
Sample Answer
Direct answer: Integrating RLHF into a CI/CD pipeline needs immutable, hash-versioned datasets and containerized, seeded training runs for true reproducibility, automated offline evaluation gates backed by human review for borderline cases, a staged shadow-then-canary rollout with automated rollback tied to pre-defined safety and quality thresholds, and an explicit, comprehensive lineage and logging schema covering both training-time and production-time artifacts.
Structured elaboration:
- Reproducibility: every training run should record the exact code commit, container image, random seeds, hyperparameters, and dataset hash to an experiment tracker and artifact store, with software dependencies pinned, so any run can genuinely be reproduced later, not just approximately re-run; produced artifacts (policy weights, reward model, tokenizer/config, and the exact evaluation seeds used) should be signed and versioned with full lineage metadata.
- Lineage and logging metadata: for every training run, record the dataset version as a content hash (not just a filename), the exact version of the prompt template used to construct both training and evaluation examples, the annotator ID (or a stable anonymized annotator identifier) behind every human-labeled example so a labeling-quality issue can be traced back to its source, the random seed, and the resulting model checkpoint's own version identifier, all written to the same experiment-tracking and artifact store described above; separately, for every PRODUCTION interaction, log the exact prompt sent, the model's output, the per-token or per-sequence log-probabilities the policy assigned (useful later for offline analysis, bootstrapping a reward model, or debugging a distribution shift), a precise timestamp, and any downstream judgment recorded on that interaction (a human reviewer's label, an automated safety-classifier verdict, or a user feedback signal); this production log, not just the training-run metadata, is what actually lets an audit or an incident investigation reconstruct exactly what the model saw, said, and was judged on at a specific point in time.
- Automated evaluation gates: offline checks span basic regression tests (API shape, deterministic sanity checks) through behavioral evaluation (simulated scenarios, adversarial test cases, safety-constraint checks, and distributional-shift tests), with explicit pass/fail thresholds on core metrics and proper statistical-significance checks, not a single point-estimate comparison; when a run's metrics land near a threshold or trigger a heuristic flag (unusual uncertainty, novel behavior patterns), route it to human review rather than either auto-passing or auto-failing.
- Staged rollout: a SHADOW deployment first, routing a copy of real traffic to the new policy without ever serving its responses, purely to compare decisions and latency against the current baseline; then a CANARY rollout gradually shifting a small, increasing percentage of live traffic (for example 1%, then 5%, then 25%, then 50%) behind a feature flag or traffic-routing layer, with continuous monitoring throughout.
- Rollback and safety: pre-define explicit SLO and drift thresholds; if the canary's core metrics degrade beyond those thresholds, or a safety violation occurs, for a sustained window, trigger an automated rollback to the last known-good model version via the model registry's version pointer, keeping the previous model warm (not cold-started) so the rollback itself does not introduce a latency spike; capture the incident's full trace, drawing on exactly the production-interaction logs above, for a post-rollback forensic replay.
Worked example: A concrete gate sequence for one training run: the run completes and produces a candidate policy; automated offline evaluation runs the full regression and behavioral suite, if every metric clears its threshold with statistical confidence, the candidate proceeds automatically to shadow deployment; if one metric lands within a defined "uncertain zone" near its threshold, a human reviewer examines a sample of the flagged trajectories (drawing on the logged prompts, outputs, and log-probs) before the candidate is allowed to proceed; only after a clean shadow-deployment comparison does the candidate begin the staged canary rollout, with the very first automated rollback trigger armed from the moment canary traffic starts, not added later once the rollout looks stable.
Trade-offs and pitfalls: Skipping the shadow-deployment stage to save time is a common shortcut that removes the cheapest, lowest-risk opportunity to catch a problem (since shadow traffic never actually affects a real user) before any live traffic is exposed to the new policy. A second common pitfall is defining rollback thresholds loosely enough that a real regression persists for an extended window before triggering an automatic rollback, the threshold and the required sustained-duration window both need to be tuned deliberately against how much exposure is tolerable, not left at a default that was never revisited after the first incident. A third pitfall is logging only training-run metadata and skipping the production-interaction log (prompts, outputs, log-probs, timestamps, judgments), without that log a post-incident audit cannot actually reconstruct what a specific user saw or how a specific response was judged, it can only reconstruct how the model was trained.
Unlock Full Question Bank
Get access to all LLM Fine-Tuning and Alignment interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.