Skip to main content

LLMs and foundation models (training side)

Named in 79% of 2253 senior postings · 43 review cards

How large language and multimodal models are made and changed: the pretraining objective and its data, fine-tuning and parameter-efficient methods, post-training with preferences and reinforcement learning, distillation, synthetic data, tokenization, vision-language models, reasoning at inference time, interpretability, code models, scaling behaviour and continual learning. 68% of postings name LLMs or foundation models in general. The training-side skills are concentrated in research engineer and model-team roles: post-training is named in 29% of research engineer postings, multimodal models in 33%, and fine-tuning in 19% of all postings. It is tested in ML depth and research rounds, in coding rounds (a LoRA layer, a preference loss, a BPE step) and in design rounds about adapting a model to a domain.

ML depth or research roundCoding (LoRA layer, loss functions, tokenizer)ML system design (adapting or post-training a model)Paper discussionProject deep diveReview these cards →

What the postings ask for

Share of postings that name each skill, overall and by track.

Skill All postings MLE AI eng Research eng Cards
LLMs / foundation models (general) 68% 62% 73% 74% 5
Fine-tuning (SFT, LoRA, PEFT) 19% 24% 13% 25% 5
Multimodal / vision-language models 18% 24% 9% 33% 4
Post-training (RLHF, preference tuning, RL fine-tuning) 12% 12% 8% 29% 6
Model architecture and scaling research 12% 13% 6% 30% 3
Distillation and model compression 6% 9% 4% 9% 2
Interpretability and explainability 6% 6% 4% 12% 3
Synthetic data and data generation pipelines 5% 6% 2% 13% 3
Pretraining at scale 5% 5% 3% 14% 3
Reasoning, planning and long-horizon behaviour of models 4% 3% 2% 14% 2
Code generation models 4% 2% 5% 4% 2
Continual learning, memory and personalization of models 2% 2% 1% 2% 3
Tokenization and data preprocessing for LMs 1% 1% 0% 2% 2

In the postings’ words

Strong Python engineering skills and experience shipping an LLM application that uses tools.

Okta · Principal Software Engineer, Applied AI

Overall understanding of the field of generative AI; knowledge of, or interest in, fine-tuning and using language models for applications.

Mistral AI · Research Engineer, GPU Performance

Hands-on experience with vision-language models, including building the training data and evaluations that measurably improve visual grounding and reasoning quality.

Nvidia · Senior Deep Learning Engineer, Cosmo 3D Spatial

  1. Define training/evaluation pipelines, datasets, and metrics from the ground up or from open source; map model behavior to user needs and design requirements.

Midjourney · Senior Machine Learning Engineer (Clinical Team)

Passion for staying abreast of the latest AI research and AI systems, and judiciously apply novel techniques in production

Capital One · Senior Staff AI Engineer - Agentic AI Platform (Remote Eligible)

Model Specialization & Adaptation: Deep expertise in fine-tuning, distillation, transfer learning, and PEFT/LoRA, as well as designing OpenAI-compatible interfaces over specialized models.

Cisco · Machine Learning Engineering Technical Leader - CX AI

Establish guardrails, explainability, and responsible AI standards.

Yahoo · Senior Staff AI/ML Engineer / Architect - Yahoo Mail

The senior bar

What separates a senior answer from a mid-level one in this area.

  • Chooses among prompting, retrieval, fine-tuning and training by what the failure actually is (missing knowledge, wrong behaviour, cost), and states the evaluation that would show the choice was right.
  • Writes the objectives from memory (next-token loss, LoRA update, preference losses, distillation, contrastive loss) and explains each term’s purpose and failure mode.
  • Treats data as the main lever, with a concrete view on formatting, masking, deduplication, contamination and the mix that prevents forgetting.
  • Knows what optimising a learned reward or judge does to a model and builds the checks that catch over-optimisation.
  • Reasons about compute with arithmetic, from tokens and parameters to GPU-days, and about what small-scale results do and do not predict at larger scale.
  • Separates what is established from what is contested or changing quickly, and says which is which.

Skills, checklists and questions

Tick an item when you can explain it without notes; ticks are saved in this browser. Open a question to see the answer.

LLMs / foundation models (general) 68% of postings

  • Write the next-token objective and relate loss, perplexity and bits per token
  • Compare encoder-only, decoder-only and encoder-decoder models and say when each is still the right choice
  • Explain hallucination from the training objective and the incentives of post-training and evaluation
  • Decide between prompting, retrieval, fine-tuning and training a model for a given failure
  • Weigh an open-weights model against a hosted API for a product
coreconceptMLE AI REasked at Google, Amazon How is a decoder-only language model trained, and how does that differ from how it is used at inference? Define perplexity while you are at it.

Training. The model defines a distribution over the next token given the previous ones, and is trained by maximum likelihood on text:

\[\mathcal L(\theta) = -\frac{1}{T} \sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t}).\]

A causal attention mask lets one forward pass compute the prediction at every position at once, each conditioned on the true previous tokens (teacher forcing). A sequence of \(T\) tokens therefore yields \(T\) training signals for the cost of one pass, which is why pretraining is efficient.

Inference. Generation is sequential: sample or pick a token from \(p_\theta(\cdot \mid x_{<t})\), append it, and repeat. The model now conditions on its own outputs, a distribution it never saw in training, so early errors can compound. Each new token needs a forward pass (made cheap by caching keys and values), so cost grows with output length.

Perplexity is the exponential of the average loss, \(\mathrm{PPL} = e^{\mathcal L}\): the effective number of equally likely choices per token. Loss divided by \(\ln 2\) is bits per token, which makes the link to compression explicit.

Things to say about it:

  • It is comparable only between models with the same tokenizer and the same evaluation text. A tokenizer with shorter tokens gets lower per-token loss for the same quality.
  • It measures fit to the text distribution, not usefulness. A model can improve perplexity while getting worse at following instructions, and post-training often raises perplexity on raw text.
  • It is still the cleanest signal during pretraining, and held-out loss against training loss shows memorisation.

Nothing in the objective mentions truth, helpfulness or instructions. Those behaviours come from the data and from post-training.

Follow-ups

  • Why can you not compare the perplexity of two models with different tokenizers?
  • What is exposure bias, and why does it matter less for large models than the argument suggests?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Google, Machine Learning Engineer, Aug 2026: Interpret perplexity for an autoregressive language model (PracHub)
  • Amazon, Software Engineer, Sep 2026: How a decoder-only transformer produces next-token probabilities and how an inference engine serves it efficiently (PracHub)
coretrade-offMLE AI REasked at Amazon Compare encoder-only, decoder-only and encoder-decoder transformers. Decoder-only models dominate; when would you still choose one of the others?
Family Attention Trained with Natural use
Encoder-only (BERT family) Bidirectional: every token sees the whole input Masked-token prediction, or contrastive objectives for embeddings Understanding tasks: classification, tagging, retrieval embeddings, reranking
Decoder-only (GPT family) Causal: each token sees only the past Next-token prediction Generation, and with prompting almost any task
Encoder-decoder (T5 family) Bidirectional encoder; causal decoder with cross-attention to the encoder Sequence-to-sequence objectives, such as span corruption Transduction: translation, summarisation, speech recognition

Why decoder-only won for general models. One objective that uses every token of any text, one stack that is simple to scale, a single interface (text in, text out) that unifies tasks, and prefix caching at inference. In-context learning made task-specific heads unnecessary.

When to choose an encoder.

  • High-volume classification, retrieval or reranking with tight latency and cost. An encoder with a few hundred million parameters, fine-tuned, processes an input in one pass with no generation loop, and is orders of magnitude cheaper per item than prompting a large generative model.
  • Embeddings. Bidirectional context gives better representations per parameter, although decoder-based embedding models with modified attention or pooling are now competitive at larger sizes.
  • Token-level tasks (entity tagging, span extraction) where an output per input token is wanted.

When to choose an encoder-decoder. The input is long and fixed and the output is short, or the input is a different modality: the encoder runs once, and the decoder attends to it. Speech recognition and many translation systems use this shape.

The practical pattern in products is a cascade: a small encoder model handles the bulk of traffic and routes hard cases to a large generative model, often trained on labels that the large model produced.

Follow-ups

  • Why is a bidirectional encoder a poor generator?
  • You need to classify 100 million documents a day. Sketch the model choice and the cost argument.

Reported in interviews (candidate reports on third-party sites, not verified)

  • Amazon, Software Engineer, Jul 2025: Attention and transformers, including BERT versus GPT (PracHub)
seniorconceptMLE AI REasked at OpenAI, Anthropic Why do language models hallucinate? Answer from the training side: what in the objective, the data and the evaluation produces confident false statements?

Several causes stack.

  • The pretraining objective rewards plausibility. The model learns which continuations are likely in text. For a fact it has seen often, the likely continuation is the true one. For a rare fact (an obscure person’s birthday, a citation), many continuations are about equally plausible in form, and the model produces one of them. Fluent, well-formed and wrong is exactly what a good density model outputs when it lacks the specific knowledge.
  • The data rarely demonstrates abstention. Written text mostly contains assertions; authors who do not know something tend not to write about it. So “I don’t know” is an unlikely continuation by default.
  • Knowledge is not separated from guessing internally in a way the output must respect. The same generation mechanism serves both. Models do carry signals about their own uncertainty, but nothing forces the text to reflect them.
  • Post-training incentives. If raters or reward models prefer complete, confident answers, and evaluations score a correct guess above an abstention and a wrong guess no worse than one, then training and model selection both push toward guessing.
  • Conditioning errors. A question with a false premise, a long context with conflicting passages, or the model’s own earlier mistake pulls the continuation along.
  • Decoding. Sampling adds variance, but greedy decoding does not remove the problem.

What follows for mitigation:

  • Provide the knowledge at inference (retrieval, tools) and train the model to rely on and cite it.
  • Train and evaluate abstention explicitly: reward “I don’t know” on unanswerable items and penalise confident errors more than abstentions.
  • Verify outputs against sources, or with a second pass, where the cost of an error is high.

A measured view to state: hallucination rates fall with model scale and with grounding, but the incentive problem means it does not vanish by scale alone.

Follow-ups

  • How would you build an evaluation that does not reward guessing?
  • Why does retrieval reduce hallucination but not eliminate it?

Reported in interviews (candidate reports on third-party sites, not verified)

  • OpenAI, Machine Learning Engineer, Dec 2025: Fallback for an assistant that cannot answer reliably (PracHub)
  • OpenAI, Product Manager, Apr 2026: What an LLM hallucination is, its types and causes (PracHub)
  • OpenAI / Anthropic, Machine Learning Engineer, undated: Handle hallucinations in a generative model deployed to users (Aced (formerly Exponent))
  • OpenAI / Anthropic, Machine Learning Engineer, undated: Define hallucinations in LLMs (Aced (formerly Exponent))
coretrade-offMLE AI REasked at Anthropic, OpenAI, Google A model does not perform well enough on your task. How do you decide between better prompting, retrieval, fine-tuning and training your own model?

Diagnose the failure first; each tool fixes a different one.

Failure Tool
The model can do it but was not told clearly what is wanted Prompting: instructions, examples, output format, decomposition
The model lacks facts that are private, recent or too many to memorise Retrieval or tools: put the facts in the context at request time
The model knows enough but behaves wrongly or inconsistently: style, format, a narrow skill, a domain’s conventions Fine-tuning
The task is fine but cost or latency is too high Fine-tune or distil a smaller model on the large model’s outputs
The domain is far from anything in the model’s training data (a new modality, a specialised notation) Continued pretraining, or training a model

Order of attempts. Cheapest and most reversible first:

  1. Build an evaluation set and measure the baseline. Without it nothing else can be judged.
  2. Prompting, including few-shot examples. Hours of work, no infrastructure.
  3. Retrieval, if error analysis shows missing knowledge.
  4. Fine-tuning, if errors remain that examples could teach and you have, or can create, hundreds to thousands of good examples.
  5. Training from scratch almost never; it needs a reason that survives the question “why not adapt an existing model?”.

What fine-tuning costs beyond compute. A training set to build and maintain, an evaluation and regression process, a model to host or a provider’s tuning service to depend on, and repeated work whenever the base model is upgraded. It also does not reliably add facts: a tuned model still hallucinates details it saw a few times, so knowledge belongs in retrieval.

Combinations are normal. Retrieval for knowledge plus a fine-tune for format and tone; a prompt-engineered large model generating data to tune a small one.

The senior signal is error analysis: reading 50 failures and sorting them by cause before choosing.

Follow-ups

  • You have 200 labelled examples. Is that enough to fine-tune, and how would you find out?
  • Why is fine-tuning a poor way to add new facts?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Anthropic, Product Manager, Apr 2026: Choose between prompting, retrieval and fine-tuning to specialise a model (PracHub)
  • OpenAI / Anthropic, Machine Learning Engineer, undated: Adapt a generative model to perform well in a specific domain (Aced (formerly Exponent))
  • Google, Product Manager, Oct 2026: When an LLM feature should use prompting or fine-tuning instead of retrieval (PracHub)
seniortrade-offMLE AI Open-weights model that you host, or a proprietary model behind an API? How do you decide for a product?

Decide per workload, on quality, control, cost and risk.

Quality on your task. Measure candidates on your own evaluation set. The strongest proprietary models usually lead on hard reasoning and long agentic tasks; for narrower tasks (extraction, classification, routine generation) a smaller open model, especially fine-tuned, is often equal.

Control.

  • Customisation. Open weights allow any fine-tuning, quantization, constrained decoding or change to the serving stack. APIs offer what the provider exposes.
  • Stability. A hosted model can be updated or retired on the provider’s schedule; weights you hold do not change. Pinning versions mitigates but does not remove this.
  • Data. Self-hosting keeps data inside your environment, which some customers and regulations require. Providers offer contractual and regional controls that satisfy many but not all cases.

Cost.

  • API: pay per token, no fixed cost, scales to zero. Best for low or spiky volume.
  • Self-hosted: you pay for GPUs whether used or not, plus engineers to run them. It wins at high, steady utilisation, or when a small model replaces a large one. Compare cost per task at your real utilisation, including on-call and upgrades.

Latency. Self-hosting allows co-location, dedicated capacity and a small specialised model; APIs add network time and shared-capacity variance but need no tuning.

Risk. Provider dependency and outages against operational burden; licence terms of open models, which vary and may restrict commercial use; security review either way.

Common outcome. Both. A proprietary frontier model for the hardest steps and for generating training data, open or small models for high-volume narrow steps, behind one internal interface so that each call site can be re-routed when prices or models change. Re-evaluate on a schedule, because the trade moves every few months.

Follow-ups

  • At what request volume does hosting a small open model become cheaper than an API for your use case?
  • What would you put in the abstraction layer between your product and the model?

Fine-tuning (SFT, LoRA, PEFT) 19% of postings

  • Write the LoRA update, count its parameters and explain the initialisation and scaling
  • Implement a LoRA linear layer with merging
  • Compare full fine-tuning, adapters and prompt tuning by cost, quality and serving
  • Format chat data with the model’s template and mask the loss to the response tokens
  • Diagnose a fine-tune that overfits, forgets or degrades general behaviour
coreconceptMLE AI RE Explain LoRA. What is the update, how many parameters does it train, and why are the initialisation and the scaling chosen the way they are?

LoRA freezes the pretrained weight matrix \(W \in \mathbb R^{d \times k}\) and learns a low-rank correction:

\[W' = W + \frac{\alpha}{r}\, B A, \qquad B \in \mathbb R^{d \times r},\ A \in \mathbb R^{r \times k},\ r \ll \min(d, k).\]

Only \(A\) and \(B\) are trained.

Parameter count. \(r(d + k)\) per adapted matrix instead of \(dk\). For \(d = k = 4096\) and \(r = 8\): 65 536 against 16.8 million, about 0.4%. Because the base weights receive no gradient, there is no optimizer state for them, which is where the memory saving in training comes from.

Initialisation. \(A\) is random and \(B\) is zero, so \(BA = 0\) at the start and training begins exactly from the pretrained model.

Scaling. The factor \(\alpha / r\) keeps the size of the update roughly comparable when the rank is changed, so that the learning rate need not be retuned for every \(r\). A variant scales by \(\alpha / \sqrt r\), which behaves better at high rank.

Why low rank is enough. The hypothesis, supported empirically, is that the weight change needed to adapt a pretrained model to a task has low intrinsic rank.

Properties in use.

  • No inference overhead. \(BA\) can be merged into \(W\) after training.
  • Cheap to store and swap. An adapter is megabytes; many can share one base model in serving.
  • Choices. Which matrices to adapt (attention projections at minimum; all linear layers usually works better), the rank (4 to 64 is typical; higher for tasks far from the base model), \(\alpha\), and dropout on the adapter input.
  • QLoRA. The frozen base is loaded in 4-bit precision and the adapters are trained in higher precision on top, which lets large models be tuned on a single GPU.

Limits. For tasks needing large changes to the model (a new language, a big shift in behaviour, large data) full fine-tuning can still be better, and LoRA is more sensitive to the learning rate than its simplicity suggests.

Follow-ups

  • Why initialise B to zero and not both matrices randomly?
  • How would you serve 500 different LoRA adapters efficiently?
seniorcodingMLE RE Implement a LoRA wrapper for a linear layer in PyTorch, including merging the adapter into the base weight.
import math
import torch
import torch.nn as nn

class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int = 8, alpha: float = 16.0,
                 dropout: float = 0.0):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad_(False)                  # freeze W and bias
        self.A = nn.Parameter(torch.empty(r, base.in_features))
        self.B = nn.Parameter(torch.zeros(base.out_features, r))
        nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
        self.scale = alpha / r
        self.drop = nn.Dropout(dropout)
        self.merged = False

    def forward(self, x):
        out = self.base(x)
        if not self.merged:
            out = out + self.scale * (self.drop(x) @ self.A.T @ self.B.T)
        return out

    @torch.no_grad()
    def merge(self):
        if not self.merged:
            self.base.weight += self.scale * (self.B @ self.A)
            self.merged = True

What an interviewer checks:

  • Shapes. x @ A.T maps [..., in] to [..., r], then @ B.T to [..., out]. The product B @ A has the shape of base.weight, [out, in].
  • Zero start. B is zero, so the wrapped layer initially computes exactly what the base layer does.
  • Freezing. Only A and B require gradients; pass only those to the optimizer, and verify the count of trainable parameters.
  • Compute the low-rank path as two small products, never by forming the full B @ A in the forward pass.
  • Dropout applies to the adapter path only, and must be inactive when merged.
  • Merging removes the extra latency. After merging into a quantised or half-precision base, check outputs, since the small update can be lost to rounding.

To apply it to a model, walk the modules and replace the chosen nn.Linear layers (for example the attention projections) with the wrapper. Save only the adapter’s state, and record the base model’s exact identifier with it, because an adapter is meaningless on a different base.

Follow-ups

  • How would you unmerge the adapter?
  • What changes for a convolution or an embedding layer?
seniortrade-offMLE AI RE Compare full fine-tuning, LoRA-style adapters and prompt or prefix tuning. How do you choose?
Method Trains Training cost Serving Quality
Full fine-tuning All weights Highest: gradients and optimizer state for everything; needs the most memory One full model copy per task Highest ceiling, especially with much data or a large shift from the base
Adapters (LoRA and variants) Small low-rank matrices, typically well under 1% of parameters Low memory for optimizer state; the forward and backward pass through the frozen model is still paid Merge for zero overhead, or keep separate and share one base among many adapters Close to full fine-tuning on most tasks
Prompt or prefix tuning A few learned vectors prepended to the input or to each layer Lowest parameter count No weight changes; consumes context positions Usually below adapters; sensitive to initialisation and harder to optimise

Choose full fine-tuning when you have a lot of data, the target differs greatly from the base (a new language, a new modality, a large behavioural change), you serve a single model anyway, and you can afford the compute. It is also the norm for small models, where the cost is trivial.

Choose adapters when compute or memory is limited, you need many task- or customer-specific variants on one base, you want to limit drift from the base model, or you iterate often. This is the default for adapting large open models.

Prompt tuning is rarely the best choice now, except where the model’s weights cannot be touched but embeddings can.

Points that cut across the table:

  • Forgetting. Full fine-tuning on narrow data damages general abilities more readily; adapters constrain the change, though they do not eliminate forgetting.
  • Hyperparameters. Adapters want a higher learning rate than full fine-tuning (often around \(10^{-4}\) against \(10^{-5}\)), and rank and target modules matter.
  • Operations. Every method ties you to a specific base checkpoint. When the base is upgraded, all tuned variants must be retrained and re-evaluated, so keep the data and the pipeline, not only the weights.
  • Hosted fine-tuning services make the choice for you; evaluate the result as you would any model.

Whatever the method, the data and the evaluation decide the outcome more than the choice of method does.

Follow-ups

  • Why does LoRA reduce optimizer memory but not the cost of the forward pass?
  • Your base model is replaced by a newer version. What do you have to redo?
coredebuggingMLE AI RE You fine-tune a chat model on conversation data. Training loss falls nicely, but at inference the model rambles, never stops, or answers worse than before tuning. What are the likely data-formatting causes?

Most failures of supervised fine-tuning are formatting errors between how the data was rendered for training and what the model sees at inference.

1. Chat template mismatch. Each chat model was trained with a specific template: role markers, turn separators and special tokens. Training with one rendering and serving with another puts the model off-distribution. Use the tokenizer’s own chat template for both, and print a fully rendered example, with special tokens visible, from each path.

2. Missing end-of-turn token in the targets. If the response’s end token is not included in the labels, the model never learns to stop and runs on until the length limit. Check that the last supervised token of each response is the end-of-turn or end-of-sequence token, and that generation is configured to stop on it.

3. Loss on the wrong tokens. The loss should cover only the assistant’s tokens. Training on the system prompt and user turns teaches the model to imitate users and wastes capacity. Set the labels of all other positions to the ignore index, and verify the mask on a sample by decoding only the supervised tokens.

4. Special tokens as plain text. Role markers typed as strings may be split into ordinary sub-tokens instead of the single special token id. Compare token ids, not strings.

5. Duplicate or missing beginning-of-sequence token, when both the template and the tokenizer add one.

6. Truncation. Long examples cut at the maximum length lose the response or its ending. Count how many examples are truncated and where.

7. Padding. Pad tokens must be masked in attention and in the loss. For batched generation with a decoder-only model, pad on the left, or the model continues from pad tokens.

8. Data content. Responses in the data that are themselves long or unfinished, or a system prompt in training that is absent at inference.

The habit that prevents all of these: before any long run, overfit a handful of examples and generate from them through the real inference path.

Follow-ups

  • How do you verify that the loss mask covers exactly the assistant tokens?
  • Why must padding be on the left for batched generation?
seniordebuggingMLE AI RE After fine-tuning, your model is better on the target task’s test set but users report it has become worse at other things. How do you diagnose and fix it?

Two different problems hide behind this report, and the evaluation must separate them.

1. Forgetting. Training on narrow data moved the weights away from what supported general abilities: other languages, reasoning, instruction-following outside the tuned format, refusals and safety behaviour.

2. Overfitting to the format of the data. The model learned surface features of the training set: a fixed response length, a tone, always producing a certain structure, always answering instead of asking for clarification. It then applies them everywhere.

Diagnose.

  • Run a retention suite on the base and tuned model: general benchmarks, a sample of real traffic outside the target task, safety checks. Compare by category.
  • Compare outputs side by side on prompts unrelated to the task. Format overfitting is visible at a glance.
  • Check the target test set for leakage or near-duplicates of training data; an inflated task metric may be part of the story.
  • Plot retention metrics against training steps from saved checkpoints. Forgetting usually grows with steps, and an earlier checkpoint may give most of the task gain at little cost.

Fix, least invasive first.

  • Train less: fewer epochs, lower learning rate, early stopping on a combined criterion.
  • Mix in general data: a share of diverse instruction data, or outputs of the base model on general prompts, so that the model keeps rehearsing its old behaviour.
  • Constrain the update: adapters with modest rank instead of full fine-tuning, or weight averaging between the base and tuned weights.
  • Diversify the task data: vary formats, lengths and phrasings, and include examples where the right behaviour is to decline or ask.
  • Route instead of merge: keep the tuned model for the task and the base model for everything else.

Process change. Make the retention suite a release gate alongside the task metric, so that the trade is seen before users see it.

Follow-ups

  • What goes into a retention suite for a customer-support fine-tune?
  • How does mixing in the base model’s own outputs help?

Multimodal / vision-language models 18% of postings

  • Write the symmetric contrastive loss of CLIP and say what the model does and does not learn
  • Describe a vision-language model as encoder, projector and language model, with its training stages
  • Compare continuous embeddings with discrete tokens for non-text modalities
  • Diagnose a vision-language model that answers from language priors instead of the image
coreconceptMLE RE Explain how CLIP is trained. Write the loss, and say what such a model is good at and where it fails.

CLIP trains an image encoder and a text encoder so that matching image-caption pairs are close in a shared embedding space and non-matching pairs are far apart.

Loss. For a batch of \(N\) pairs, compute L2-normalised embeddings \(u_i\) (image) and \(v_i\) (text) and the matrix of scaled cosine similarities \(s_{ij} = u_i^\top v_j / \tau\), with a learned temperature \(\tau\). Each image should pick out its own caption among the \(N\) in the batch, and each caption its own image:

\[\mathcal L = \frac{1}{2N} \sum_{i=1}^{N} \left[ -\log \frac{e^{s_{ii}}}{\sum_j e^{s_{ij}}} \;-\; \log \frac{e^{s_{ii}}}{\sum_j e^{s_{ji}}} \right].\]

logits = logit_scale * image_emb @ text_emb.T          # [N, N], embeddings normalised
labels = torch.arange(len(logits), device=logits.device)
loss = (F.cross_entropy(logits, labels) + F.cross_entropy(logits.T, labels)) / 2

The other items in the batch are the negatives, so the batch size sets how hard the task is, which is why these models are trained with very large batches. A sigmoid variant scores each pair independently and removes the dependence on a batch-wide softmax.

What it is good at.

  • Zero-shot classification: embed the class names as text (“a photo of a dog”) and pick the nearest to the image embedding.
  • Retrieval in both directions, and as a general visual backbone whose features align with language, which is why it became the standard vision encoder for vision-language models.
  • Robustness to distribution shift compared with models trained on fixed label sets.

Where it fails.

  • Composition. It behaves much like a bag of concepts: “a red cube on a blue sphere” and the reverse get similar embeddings. Counting, spatial relations and attribute binding are weak.
  • Fine detail and text in images, limited by input resolution and by a single global embedding.
  • False negatives. Two captions in a batch may both fit an image, but one is treated as wrong.
  • Data bias. It inherits the biases and noise of web image-text pairs.
  • Prompt sensitivity in zero-shot use; templates and ensembling of prompts matter.

Follow-ups

  • Why does the batch size matter so much for contrastive training?
  • What does the learned temperature do, and what happens if it is fixed too high?
seniorconceptMLE AI REasked at TikTok, Apple How does a vision-language model feed an image to a language model? Describe the architecture, the cost in tokens, and the usual training stages.

Architecture. The common design has three parts.

  1. A vision encoder, usually a vision transformer pretrained contrastively, splits the image into patches and outputs one embedding per patch.
  2. A projector maps those embeddings into the language model’s input embedding space. It is a small MLP in the simplest designs, or a resampler with cross-attention that compresses many patch embeddings into a fixed, smaller number.
  3. The language model receives the projected image embeddings as if they were token embeddings, interleaved with the text tokens, and generates text as usual.

The language model never sees pixels. It sees a sequence of vectors that occupy positions in its context.

Token cost. The number of image tokens is the number of patches. With 14-pixel patches at 336 by 336 resolution that is \(24 \times 24 = 576\) tokens per image. Higher resolution is usually handled by tiling the image into several crops plus a low-resolution overview, which multiplies the count, so a detailed document page can cost thousands of tokens. Resolution is therefore a direct trade between visual detail and context, latency and price. Resamplers and token pooling exist to cut that cost.

Training stages in the widely used recipe:

  1. Alignment. Freeze the vision encoder and the language model and train only the projector on image-caption pairs, so that image embeddings land where the language model can read them.
  2. Instruction tuning. Train the projector and the language model (fully or with adapters), sometimes the vision encoder too, on visual question answering, document, chart and grounding data in conversational form.

Larger systems train all parts jointly on interleaved image-text data from the start.

Design consequences.

  • Abilities are capped by what the vision encoder preserves. A contrastively trained encoder keeps semantics and loses fine spatial detail, which limits counting, small text and localisation.
  • Many images or video frames exhaust the context quickly; frame sampling and per-frame token compression are required.
  • The language model’s priors are strong, so the model can answer plausibly without using the image at all.

Follow-ups

  • How many tokens does a 1344 by 1344 image cost with tiling, and what does that do to latency?
  • Why freeze the language model in the first stage?

Reported in interviews (candidate reports on third-party sites, not verified)

  • TikTok, Machine Learning Engineer, Dec 2025: End-to-end deep dive on a vision-language model project (PracHub)
  • Apple, Machine Learning Engineer, Nov 2025: Vision encoders and the bottleneck into a language model (PracHub)
seniortrade-offMLE RE To bring images or audio into a transformer, you can use continuous embeddings from an encoder or discrete tokens from a learned codebook. Compare the two.

Continuous embeddings. An encoder maps the input to a sequence of real-valued vectors, which a projector feeds into the model.

  • Preserve information well, with no quantisation loss.
  • Natural for understanding: the model reads them and outputs text.
  • Not directly usable as an output: the language model’s head predicts a distribution over a finite vocabulary, and a continuous vector has no such distribution. Generating the modality needs something extra, such as a regression or diffusion head, or a separate generator conditioned on the model’s output.

Discrete tokens. A tokenizer for the modality (a vector-quantised autoencoder for images, a neural audio codec with residual quantisation for sound) maps the input to indices in a learned codebook, and a decoder maps indices back to pixels or waveform.

  • The modality becomes “just more tokens”. One autoregressive model with one cross-entropy loss can read and write text, image and audio tokens, in any interleaving.
  • Quantisation loses detail. Reconstruction quality is bounded by the tokenizer, and fine textures, small text or audio fidelity suffer unless many tokens are used.
  • Sequences are long: hundreds to thousands of tokens per image, and tens to hundreds per second of audio, often several parallel codebook streams.
  • Codebooks are hard to train: some entries may go unused.

How systems combine them.

  • Understanding-only models: continuous embeddings in, text out.
  • Generation: discrete tokens predicted autoregressively, or a diffusion or flow model operating in a continuous latent space, conditioned on text or on the language model’s hidden states.
  • Unified models often read with continuous features, which are better for perception, and write with discrete tokens or a diffusion head, which are better for generation.

Deciding. If the product only needs to interpret the modality, use continuous embeddings from a strong pretrained encoder. If it must generate it with tight coupling to language, such as speech-to-speech with low latency or interleaved image and text, discrete tokens or a jointly trained continuous head are needed, and the tokenizer’s rate and quality become the central design choice.

Follow-ups

  • Why can a language model head not output a continuous embedding directly?
  • What sets the token rate of an audio codec, and why does it matter for a voice model?
seniordebuggingMLE AI RE Your vision-language model describes objects that are not in the image and answers some questions the same way whatever image is shown. How do you diagnose and reduce this?

The model is leaning on its language prior. The language model is far stronger than the visual pathway, and for many questions a plausible answer exists without looking: “what colour is the banana?”, or a kitchen scene that “should” contain a fridge.

Diagnose.

  • Blind baseline. Run the evaluation with the image removed or replaced by a blank or random image. The score that survives is what language alone achieves, and the gap to the real score is what vision contributes.
  • Counterfactual images. Edit an image so the usual answer is wrong (a blue banana) or pair each question with two images that require different answers. Consistency on such pairs measures grounding.
  • Existence probes. Ask about objects that are absent but typical for the scene, and measure the rate of false “yes” answers.
  • Attention to image tokens. Where the model allows it, check how much the answer changes when image tokens are perturbed.
  • Slice by what is asked. Counting, spatial relations, small text and fine detail fail for a different reason: the vision encoder or the resolution loses the information.

Reduce.

  • Resolution and encoder. If the detail is not in the visual tokens, no training of the language model will recover it. Raise the resolution, tile, or use an encoder that preserves spatial detail.
  • Training data. Add examples where the prior is wrong: counterfactual and negative examples, questions about absent objects with “no” as the answer, and unanswerable questions with abstention as the target. Balance the data so that the answer cannot be guessed from the question.
  • Training recipe. Make sure the projector and language model were trained enough on grounded tasks, and that long, fluent captions do not dominate the data, since they reward plausible elaboration.
  • Inference. Ask for the evidence, such as the region or the text that was read, before the answer; lower the temperature; shorten descriptions, since hallucination rises with length.
  • Evaluation. Keep the blind baseline and the counterfactual pairs as permanent metrics.

For document and chart tasks, compare with a pipeline that extracts text first; if it wins, resolution is the bottleneck.

Follow-ups

  • The blind baseline scores 60% on your benchmark. What does that say about the benchmark?
  • Why do longer captions contain more hallucinated objects?

Post-training (RLHF, preference tuning, RL fine-tuning) 12% of postings

  • Describe the RLHF pipeline and the role of the reward model and the KL penalty
  • Derive the DPO loss from the KL-regularised objective and implement it
  • Explain policy-gradient fine-tuning with a verifiable reward and a group baseline
  • Name the failure modes of optimising a learned reward and how to detect them
  • Describe how intended model behaviour is specified, trained and evaluated
seniorconceptMLE REasked at Google, Meta Walk through reinforcement learning from human feedback as originally practised. What are the stages, what is each loss, and what is the KL term for?

Stage 1: supervised fine-tuning. Train the pretrained model on demonstrations of the desired behaviour (prompt and good response) with the usual next-token loss. This gives a policy \(\pi_{\text{ref}}\) that follows instructions.

Stage 2: reward model. Collect comparisons: for a prompt \(x\), humans say which of two responses is better. Train a model \(r_\phi(x, y)\) that outputs a scalar, with the pairwise (Bradley-Terry) loss

\[\mathcal L(\phi) = -\,\mathbb E\big[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\big],\]

where \(y_w\) is the preferred response. Comparisons are used because people are more consistent at ranking than at absolute scoring.

Stage 3: RL against the reward model. Treat generating a response as an episode: the policy samples a response, the reward model scores it, and the policy is updated with a policy-gradient method (PPO in the original recipe) to maximise

\[\mathbb E_{x,\ y \sim \pi_\theta}\big[r_\phi(x, y)\big] \;-\; \beta\, \mathrm{KL}\big(\pi_\theta(\cdot \mid x)\,\|\,\pi_{\text{ref}}(\cdot \mid x)\big).\]

What the KL term is for. The reward model is accurate only near the distribution of responses it was trained on. Unconstrained, the policy finds outputs that score highly for the wrong reasons, and drifts into degenerate text. The penalty keeps the policy close to the reference model, where the reward model can be trusted and where language quality is preserved. \(\beta\) sets the trade between reward and drift.

Why RL at all, instead of more supervised data? Demonstrations show one good answer; preferences can rank outputs the model itself produces, including on prompts where no one wrote a reference, and the optimisation targets the judged quality directly.

Weaknesses. The reward model is a bottleneck and a target for exploitation; rater disagreement and bias are learned; on-policy RL on long sequences is expensive and unstable. These motivated simpler preference-optimisation methods that skip the explicit reward model and the sampling loop.

Follow-ups

  • What does the policy do if the KL coefficient is set to zero?
  • Why are pairwise comparisons preferred over 1-to-5 ratings?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Google, Machine Learning Engineer, Aug 2026: Compare supervised, reward-based, preference-based and group-relative post-training (PracHub)
  • Meta, Machine Learning Engineer, Sep 2025: Asynchronous RLHF-style post-training system for a production chat model (PracHub)
seniorderivationMLE REasked at TikTok Derive the DPO loss. How does it turn preference data into a supervised objective without a reward model?

Start from the RLHF objective for a fixed reward \(r\):

\[\max_\pi\ \mathbb E_{y \sim \pi(\cdot \mid x)}\big[r(x, y)\big] - \beta\, \mathrm{KL}\big(\pi(\cdot \mid x) \,\|\, \pi_{\text{ref}}(\cdot \mid x)\big).\]

Its optimum has a closed form:

\[\pi^*(y \mid x) = \frac{1}{Z(x)}\, \pi_{\text{ref}}(y \mid x)\, \exp\!\big(r(x, y) / \beta\big).\]

Invert it to express the reward through the optimal policy:

\[r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x).\]

Substitute into the preference model. Under Bradley-Terry, the probability that \(y_w\) is preferred to \(y_l\) is \(\sigma\big(r(x, y_w) - r(x, y_l)\big)\). The intractable \(\log Z(x)\) depends only on \(x\) and cancels in the difference. Parameterising the policy as \(\pi_\theta\) and maximising the likelihood of the observed preferences gives

\[\mathcal L_{\text{DPO}}(\theta) = -\,\mathbb E\left[\log \sigma\!\left(\beta \left[\log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\right]\right)\right].\]

Reading it. The policy is its own implicit reward model: the log-ratio to the reference plays the role of the reward. The loss raises the likelihood of the preferred response relative to the reference and lowers that of the rejected one, and the reference model in the ratio is what is left of the KL constraint.

What you gain. No reward model, no sampling during training, no RL machinery: a classification-style loss over fixed pairs, with two forward passes of the policy and two of the frozen reference per example.

What you lose or must watch.

  • It is offline. The model learns only from the pairs given; it never explores its own outputs, so the data must cover the behaviour you care about. Pairs generated by the current model are most useful.
  • The loss can be reduced by lowering the rejected response’s likelihood without raising the preferred one’s, so monitor both log-probabilities.
  • \(\beta\) controls how far the policy may move; too small and it drifts into degenerate text.
  • Noisy or inconsistent preferences are fitted as confidently as clean ones.

Follow-ups

  • Why does the partition function cancel?
  • Both log-probabilities are falling during training but the loss improves. Is that a problem?

Reported in interviews (candidate reports on third-party sites, not verified)

  • TikTok, Software Engineer, Dec 2025: Explain DPO and construct its training data (PracHub)
seniorcodingMLE RE Implement the DPO loss in PyTorch, including how you compute the log-probability of a response under a causal language model.
import torch
import torch.nn.functional as F

def response_logp(model, input_ids, attention_mask, response_mask):
    """input_ids: [B, T] prompt followed by response.
    response_mask: [B, T], 1 on response tokens. Returns [B] summed log-prob."""
    logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
    logp = F.log_softmax(logits[:, :-1].float(), dim=-1)     # predicts token t+1
    tgt = input_ids[:, 1:]
    tok_logp = logp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1)
    return (tok_logp * response_mask[:, 1:]).sum(-1)

def dpo_loss(policy, ref, chosen, rejected, beta=0.1):
    """chosen / rejected: dicts with input_ids, attention_mask, response_mask."""
    pi_w = response_logp(policy, **chosen)
    pi_l = response_logp(policy, **rejected)
    with torch.no_grad():
        ref_w = response_logp(ref, **chosen)
        ref_l = response_logp(ref, **rejected)
    margin = (pi_w - ref_w) - (pi_l - ref_l)
    loss = -F.logsigmoid(beta * margin).mean()
    return loss, {"margin": margin.mean(), "pi_w": pi_w.mean(), "pi_l": pi_l.mean()}

What an interviewer checks:

  • The shift. Logits at position \(t\) predict token \(t + 1\), so drop the last logit and the first label, and shift the mask the same way.
  • Mask to the response. Only response tokens count; the prompt is conditioning. The mask also removes padding.
  • Sum, not mean, over tokens. The derivation is about the log-probability of the whole response. Averaging per token changes the objective and its length behaviour.
  • The reference is frozen and evaluated without gradients. Its log-probabilities can be precomputed once for a fixed dataset.
  • Numerics. Use logsigmoid, and compute the log-softmax in full precision when the model runs in half precision.
  • Logging. Track the chosen and rejected log-probabilities separately, and the share of pairs with positive margin. A falling loss with both log-probabilities falling means the model is degrading its outputs.

Memory: a naive step holds four forward passes. Concatenate chosen and rejected into one batch per model, and cache the reference values.

Follow-ups

  • What breaks if you average the log-probability over tokens instead of summing?
  • How would you precompute the reference terms, and when does that become invalid?
seniortrade-offMLE REasked at Anthropic, Google, Amazon When would you fine-tune a language model with reinforcement learning on a task reward, instead of supervised fine-tuning or preference optimisation? How do policy-gradient methods with a group baseline work?

Choose by the signal you have.

  • Demonstrations of good outputs: supervised fine-tuning. Simple and stable, but the model can at best imitate the demonstrations.
  • Comparisons between outputs: preference optimisation such as DPO. Offline and cheap, limited to the pairs collected.
  • A reward you can compute on any output: reinforcement learning. Examples are unit tests that pass or fail, a checkable final answer, a task completed in an environment, or a trusted grader. RL lets the model improve on its own samples, so it can exceed the demonstration data and learn multi-step strategies no one wrote down.

RL is worth its cost when such a reward exists, when it is hard to exploit, and when supervised data has stopped improving the model.

How it works for text. A response (or a multi-step trajectory) is an episode; its tokens are actions; the reward arrives at the end. The policy gradient weights each sampled response’s log-probability by its advantage.

Group baseline. Training a value network for long token sequences is difficult. Instead, sample a group of \(G\) responses for the same prompt, score them, and normalise within the group:

\[A_i = \frac{r_i - \operatorname{mean}(r_1, \dots, r_G)}{\operatorname{std}(r_1, \dots, r_G)}.\]

Responses better than their siblings are reinforced, worse ones suppressed. The prompt’s difficulty cancels, and no critic is needed. The update is then a clipped, PPO-style objective on the token log-probability ratios, usually with a KL term toward a reference model. GRPO is the best-known method of this shape.

What goes wrong.

  • If all samples for a prompt get the same reward, the advantage is zero and nothing is learned. The task distribution must be at the edge of the model’s ability.
  • Reward exploitation: the model finds outputs that satisfy the checker without solving the task.
  • Collapse of diversity and drift in language quality without the KL term or a mix of supervised data.
  • Cost: many samples per prompt, each of which may need an environment to score it.

Monitor reward, the fraction of solved prompts, KL to the reference, output length and a held-out evaluation that the reward cannot see.

Follow-ups

  • Every sample in a group scores zero. What does the model learn, and what do you change?
  • Why is a learned critic hard for long token sequences?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Anthropic, Software Engineer, Feb 2026: Find the bugs in a simplified GRPO training step and explain the importance ratios (PracHub)
  • Google, Machine Learning Engineer, Aug 2026: Compare supervised, reward-based, preference-based and group-relative post-training (PracHub)
  • Amazon, Machine Learning Engineer, Jan 2026: GRPO computations in NumPy: group-relative advantages and shaped rewards (PracHub)
  • Amazon, Applied Scientist, Jun 2026: Critic-free RL for a reasoning model: parallelism and reward design (PracHub)
seniordebuggingMLE REasked at Google During RL or preference tuning against a learned reward model or an LLM judge, the reward keeps rising but human raters say the outputs are getting worse. What is happening and what do you do?

This is over-optimisation of a proxy. The reward model is an approximation fitted on a limited distribution of outputs. The policy is an optimiser that searches for whatever raises the score, and it moves into regions where the approximation is wrong.

Typical exploits.

  • Length and style. Longer, more detailed-looking, more confident or more flattering answers score higher, regardless of correctness.
  • Surface markers. Formatting, hedging phrases, lists, apologies, or keywords the reward model associates with quality.
  • Agreeing with the user over being right.
  • Repetition or degenerate text that happens to score well far from the training distribution.
  • Gaming a judge model’s known preferences, including text addressed to the judge.

Confirm.

  • Plot human-rated quality on a fixed sample against training steps, next to the reward. The point where they separate is where to stop.
  • Compare output statistics over training: length, vocabulary diversity, frequency of particular phrases.
  • Score outputs with a second, independent judge that was not used in training.
  • Track the KL divergence from the reference policy; a large value means the policy has left the region where the reward model was fitted.

Fix.

  • Constrain the policy: a larger KL coefficient, fewer steps, early stopping at the divergence point.
  • Improve the reward: collect human labels on the current policy’s outputs and retrain the reward model, iterating. Use an ensemble and optimise a conservative statistic. Normalise or penalise length explicitly.
  • Combine signals: verifiable checks where they exist, and a mix of supervised data to anchor language quality.
  • Keep a held-out human evaluation and an independent automatic judge as release gates that the optimisation never touches.

The general principle: once a measure is optimised directly, it needs an independent measure to check it.

Follow-ups

  • How would you detect a length bias in a reward model before training against it?
  • Why does retraining the reward model on the current policy’s outputs help?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Google, Machine Learning Engineer, Aug 2026: Reward hacking in LLM post-training and how to detect and prevent it (PracHub)
staffdesignMLE REasked at Anthropic How is the intended behaviour of an assistant model (what it helps with, what it refuses, its tone and honesty) specified and trained in? Describe the loop from specification to evaluation.

Behaviour is shaped in layers, and the hard part is keeping them consistent.

1. A written specification. A document stating what the model should do: priorities when goals conflict (for example safety, then honesty, then helpfulness), what content is declined and why, how to handle uncertainty, tone, and how instructions from the system prompt, the user and tool outputs rank. Published examples include model specs and constitutions. Its value is that people labelling data, writing evaluations and reviewing failures work from the same text.

2. Data that demonstrates it. Supervised examples and preference comparisons constructed or labelled according to the specification, covering clear cases and, deliberately, borderline ones. Much of this data is now generated and graded by models following the specification, with human review of samples and of disagreements.

3. Training. Supervised fine-tuning, preference optimisation and RL against graders derived from the specification. Reasons and principles in the data generalise better than bare rules, which the model applies too broadly or too narrowly.

4. Run-time layers. The system prompt adjusts behaviour within what training allows; classifiers and filters around the model catch what training missed. Training gives robust defaults; prompts give flexibility; filters give a backstop.

5. Evaluation. Suites for each behaviour, measured in both directions: harmful compliance and over-refusal of benign requests, since pushing one down raises the other. Add adversarial testing, consistency across paraphrases, and checks that general capability did not regress.

6. Iteration. Failures found in evaluation or production are traced to a gap in the specification, in the data or in training, and fixed at that layer.

Trade-offs to name. Rules against judgement; refusal rate against helpfulness; robustness to adversarial prompts against steerability by legitimate operators; and the limits of verification, because behaviour on a test suite does not prove behaviour everywhere.

Be clear about which parts you have worked on directly and which you know from published accounts.

Follow-ups

  • How do you measure over-refusal?
  • Why might training on explanations generalise better than training on rules?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Anthropic, Machine Learning Engineer, undated: Align a model with intended objectives and prevent harmful behaviour (Aced (formerly Exponent))
  • Anthropic, Machine Learning Engineer, undated: Prevent a generative model from producing harmful content (Aced (formerly Exponent))

Model architecture and scaling research 12% of postings

  • State what scaling laws say about loss as a function of parameters, data and compute
  • Design a fair small-scale comparison for an architecture change
  • Explain mixture-of-experts layers and their trade-offs
seniorconceptMLE REasked at Meta What do scaling laws for language models say, and how do practitioners use them?

The empirical finding. For transformer language models, test loss falls smoothly and predictably as a power law in each of three quantities, when the other two are not the bottleneck: the number of parameters \(N\), the number of training tokens \(D\), and the training compute \(C\). Schematically, \(L(N) \approx L_\infty + (N_0 / N)^{\alpha}\), with similar forms for data and compute. The trends hold over many orders of magnitude and are fairly insensitive to architectural details within the transformer family.

Compute-optimal allocation. For a fixed compute budget \(C \approx 6ND\), how should it be split between model size and data? An early analysis favoured growing the model much faster than the data. A later one, with learning-rate schedules matched to each run length, found that parameters and tokens should grow roughly in proportion, at about 20 tokens per parameter for the models studied, which implied that many large models of the time had been under-trained.

How they are used.

  • Planning. Fit the curve on small and medium runs and extrapolate the loss of a larger run before paying for it. A run that lands off the curve signals a bug or a bottleneck.
  • Comparing ideas. An architectural or data change is worth adopting if it shifts the curve (better loss at equal compute across scales), not if it wins at one small size.
  • Budgeting. Choosing \(N\) and \(D\) for a compute budget, and deciding whether more data or a larger model is the better purchase.

Caveats.

  • The laws describe pretraining loss. The relation between loss and downstream ability is monotone but not linear; some abilities appear abruptly.
  • Exponents and the optimal ratio depend on data quality, tokenizer and architecture. Treat published constants as specific to their setup.
  • Training cost is not the only cost. A model served at high volume should be smaller and trained longer than the compute-optimal point, because inference cost scales with \(N\). Many current small models are trained far beyond 20 tokens per parameter for this reason.
  • Extrapolation far beyond the fitted range is a forecast, not a law.
  • Data is finite: at some point high-quality tokens, not compute, are the constraint.

Follow-ups

  • Why would you deliberately train a model that is smaller than compute-optimal?
  • A new architecture beats the baseline at 50 million parameters. What else do you need to see?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Meta, Machine Learning Engineer, Jun 2026: Fundamentals: optimisers, scaling laws and clustering (PracHub)
staffdesignRE MLE You have an idea for an architectural change to a transformer and a small compute budget. How do you test it so that the result means something at larger scale?

Most architecture ideas that win at small scale do not survive scaling or fair tuning. The experimental design has to be built around that fact.

1. A strong, tuned baseline. Use a well-known baseline implementation and tune its learning rate, warm-up and regularisation at each scale you test. A common cause of false positives is a new method that was tuned against a baseline that was not.

2. Equalise what matters. Compare at equal parameters, equal training compute and equal wall-clock on the same hardware, and report all three. A change that adds parameters or FLOPs must beat a baseline enlarged by the same amount. Keep data, tokenizer, context length and evaluation identical.

3. Tune both arms equally. Give each the same hyperparameter search budget. The optimal learning rate often shifts with an architectural change; comparing at one shared learning rate can favour either side arbitrarily.

4. Several scales. Run at least three model sizes spanning an order of magnitude or more and look at the trend. A gain that is constant or growing with scale is promising. A gain that shrinks is the usual fate: many tricks are compensations for small models or short training.

5. Noise. Run several seeds at the small scales to learn the run-to-run variance, and compare differences with it.

6. Look beyond the final loss. Training curves (does it only converge faster?), stability across learning rates, throughput and memory, behaviour at longer context, and downstream evaluations. A change that improves loss per step but slows each step may lose at equal wall-clock.

7. Ablate. If the idea has several parts, remove each to find which carries the effect. Often it is one small part, or an incidental change such as initialisation.

8. Check the implementation. Unit-test the new component, verify it reduces to the baseline when switched off, and overfit a tiny dataset.

9. Decide in advance what result would count as success and what would end the project, to resist reading noise as signal.

Report negative results and the conditions honestly. For a reader deciding whether to spend a large run on the idea, the scaling trend and the fairness of the baseline are the whole question.

Follow-ups

  • Your method adds 5% parameters and improves loss by 1%. How do you make the comparison fair?
  • Why can sharing one learning rate between baseline and variant mislead in either direction?
seniorconceptMLE REasked at Meta What is a mixture-of-experts transformer layer? What does it buy, and what does it make harder in training and serving?

The layer. In a standard transformer block every token passes through the same feed-forward network. A mixture-of-experts (MoE) layer replaces it with \(E\) feed-forward “experts” and a small router. For each token the router scores the experts, the top \(k\) (often 1 to 8 of dozens or more) are evaluated, and their outputs are combined with the router’s weights. Attention layers stay shared.

What it buys. Parameters and compute are decoupled. The model has \(E\) experts’ worth of feed-forward parameters, but each token pays for only \(k\) of them. At a fixed compute per token, the model has far more capacity than a dense one, and at equal quality it needs fewer FLOPs per token.

What it makes harder in training.

  • Load balance. Without pressure, the router sends most tokens to a few experts and the rest are never trained. An auxiliary balancing loss, noise in routing or capacity limits per expert are used.
  • Discrete routing. The top-k choice is not differentiable; the router learns only through the experts it selected, which adds instability.
  • Uneven batches per expert. Each expert sees a variable number of tokens per step, which complicates batching and, in distributed training, means tokens must be sent to the devices holding their experts. Communication and stragglers become design problems.
  • More hyperparameters: number of experts, k, where to place MoE layers, the balancing coefficient.

What it makes harder in serving.

  • Memory. All experts must be loaded even though each token uses few, so the memory footprint is that of the full parameter count. The savings are in compute, not in memory.
  • Batching efficiency. Tokens in a batch go to different experts, so each expert processes a small, irregular sub-batch. Throughput gains are smaller than the FLOP count suggests unless the implementation groups tokens by expert well.
  • Quantization and fine-tuning interact with routing: an adapter or a domain shift can change which experts are used.

Interpretation. Experts rarely correspond to human-recognisable topics; routing tends to follow token-level and syntactic patterns.

When to consider it. Large models where training and inference compute, not memory, is the constraint. For small models and memory-limited deployment, a dense model is usually simpler and as good.

Follow-ups

  • Why does an MoE model not save memory at inference?
  • What happens if the load-balancing loss is too strong?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Meta, Machine Learning Engineer, Sep 2025: Large-scale mixture-of-experts pretraining pipeline (PracHub)

Distillation and model compression 6% of postings

  • Write the distillation loss with temperature and explain the factor of temperature squared
  • Choose between logit-level and sequence-level distillation for a language model
corecodingMLE RE Write the knowledge distillation loss with temperature in PyTorch and explain each part. Why is the soft term multiplied by the temperature squared?

A small student is trained to match a large teacher’s output distribution as well as the labels:

\[\mathcal L = \alpha\, \mathrm{CE}\big(y, \sigma(z_s)\big) + (1 - \alpha)\, T^2\, \mathrm{KL}\big(\sigma(z_t / T)\,\|\,\sigma(z_s / T)\big),\]

with student logits \(z_s\), teacher logits \(z_t\), softmax \(\sigma\) and temperature \(T\).

import torch.nn.functional as F

def distillation_loss(student_logits, teacher_logits, labels, T=2.0, alpha=0.5):
    hard = F.cross_entropy(student_logits, labels)
    soft = F.kl_div(
        F.log_softmax(student_logits / T, dim=-1),     # log q
        F.softmax(teacher_logits.detach() / T, dim=-1),  # p
        reduction="batchmean") * (T * T)
    return alpha * hard + (1 - alpha) * soft

Why soft targets help. The teacher’s distribution says more than the label: which wrong classes are nearly right and by how much. That is many more bits of supervision per example, and it acts as a regulariser.

Temperature. Dividing logits by \(T > 1\) flattens the distribution, so the small probabilities of non-target classes, where this extra information lives, contribute to the loss. Typical values are 1 to 5.

The factor \(T^2\). The gradient of the soft term with respect to the student’s logits scales as \(1/T^2\): one factor of \(1/T\) from the scaled logits, and another because the softened distributions differ less. Multiplying by \(T^2\) keeps the soft term’s gradient magnitude comparable to the hard term’s when \(T\) changes, so that \(\alpha\) keeps its meaning.

Pitfalls.

  • F.kl_div expects log-probabilities as its first argument and probabilities as its second; swapping them or passing raw logits fails silently.
  • reduction="batchmean" gives the true KL per example; the default averages over classes as well.
  • Detach the teacher and run it in evaluation mode.
  • For sequence models, apply the loss per token and mask padding.

Beyond logits, students can also match intermediate features or attention maps, which needs a projection when dimensions differ.

Follow-ups

  • Show where the factor of one over temperature squared comes from.
  • When does a student trained with distillation outperform one trained on labels alone, and why?
seniortrade-offMLE AI RE You want a small, cheap model that performs like a large one on your task. Compare distilling from logits with training on the large model’s generated outputs. What decides the quality of the result?

Logit-level distillation. The student is trained to match the teacher’s next-token distribution at every position, on some corpus.

  • Needs access to the teacher’s full output distributions, so the teacher must be a model you run. Vocabularies must match or be mapped.
  • Rich signal per token; efficient in data.
  • Storing teacher distributions for a large vocabulary is expensive; in practice the teacher runs alongside the student or only the top-k probabilities are kept.

Sequence-level distillation. The teacher generates responses to a set of prompts, and the student is fine-tuned on them with the ordinary next-token loss.

  • Works with any teacher, including one behind an API, subject to its terms of use, which may forbid this.
  • The student sees only one sample from the teacher’s distribution per prompt, so it is less informative per example, but it is simple and scales with generation budget.
  • The teacher can be prompted elaborately, with reasoning, retrieval, several attempts and self-checks, and only the final answer kept. The student learns to produce in one cheap pass what took the teacher an expensive pipeline. This is the main reason the approach is so widely used.

What decides quality.

  • The prompts. The student is good where the distillation inputs cover. Use real task inputs, not only synthetic ones, and match production’s distribution of difficulty.
  • Filtering. Teacher outputs contain errors; keep only those that pass verification (tests, a judge, agreement across samples). A student trained on unfiltered outputs inherits and amplifies mistakes.
  • Student capacity. A narrow task distils into a small model well. A broad capability does not compress without loss, and the gap shows up on hard and rare inputs.
  • Starting point. Begin from a pretrained small model, not from scratch.
  • Evaluation. Compare student and teacher on held-out real inputs, by slice, and measure the cost and latency actually achieved.

A typical production result: a model ten or more times cheaper that matches the teacher on the bulk of traffic, with a router sending the hard remainder to the large model.

Follow-ups

  • Why can a student trained on filtered teacher outputs end up better than the raw teacher on the task?
  • How do you decide which requests still go to the large model?

Interpretability and explainability 6% of postings

  • Distinguish attribution, probing and mechanistic methods by the question each answers
  • Explain superposition and what a sparse autoencoder is trained to do
  • Use Shapley-value explanations for a tabular model and state their limits
coreconceptMLE AI RE Give an overview of interpretability methods for neural networks. What question does each family answer, and how far can each be trusted?

Four families, each answering a different question.

1. Attribution: which inputs mattered for this output? Gradient-based saliency, integrated gradients, attention visualisation, occlusion, and Shapley-value methods. They produce a score per input feature or token. Cheap and widely used, but different methods often disagree, some are insensitive to the model’s weights, and attention weights are not explanations. Check them with perturbation: removing the highly attributed inputs should change the output.

2. Probing: is this information present in the representations? Train a simple classifier on a layer’s activations to predict a property (part of speech, the truth of a statement, the position of an object). High accuracy shows the information is decodable. It does not show that the model uses it, and a powerful probe can learn the task itself, so control tasks and simple probes are needed.

3. Causal interventions: does this component cause the behaviour? Ablate or patch activations: run the model on one input, replace an internal activation with the one from a different input, and see whether the output changes accordingly. Steering adds a direction to activations to change behaviour. These tests give evidence of mechanism, because they manipulate the computation rather than observe it.

4. Mechanistic interpretability: what algorithm do the weights implement? Decompose activations into interpretable features, with sparse autoencoders and related methods, and trace circuits of features and attention heads that compute a behaviour. The most ambitious family, and the least complete: results cover selected behaviours, and the decompositions leave part of the computation unexplained.

Behavioural explanation stands beside these: asking the model to explain itself. It is easy and useful to users, and it is not a reliable account of the internal computation.

How to use them.

  • Debugging a model or dataset: attribution and example-based methods to find spurious features, verified by intervention.
  • Auditing for a property: probing plus causal tests.
  • Research on model internals and safety: features and circuits.

The trust rule: an interpretation is a hypothesis about the model, and it should make a prediction that an intervention can confirm or refute.

Follow-ups

  • Why is a high-accuracy probe not evidence that the model uses the feature?
  • How would you check that a saliency map is faithful to the model?
seniorconceptRE What is superposition, and what is a sparse autoencoder trained to do in interpretability research? What are the method’s limits?

The problem. Individual neurons in a network usually respond to several unrelated things, so reading neurons one at a time does not reveal clean concepts.

Superposition is the leading explanation. A model benefits from representing many more features than it has dimensions. If features are sparse, meaning few are active at once, the model can assign them directions that are almost, but not exactly, orthogonal, and tolerate the small interference. Features are then directions in activation space that do not line up with neurons.

Sparse autoencoders (SAEs). To recover those directions, train an autoencoder on a layer’s activations \(x \in \mathbb R^d\) with a hidden layer much wider than \(d\) and a sparsity pressure:

\[f = \operatorname{ReLU}\big(W_e (x - b_d) + b_e\big), \qquad \hat x = W_d f + b_d,\]

\[\mathcal L = \lVert x - \hat x \rVert_2^2 + \lambda \lVert f \rVert_1.\]

Each activation is reconstructed as a sparse combination of a large dictionary of directions, the columns of \(W_d\). The hope is that each dictionary element is one feature the model uses. Variants replace the L1 penalty with a top-k or gated activation to control sparsity directly.

How it is evaluated.

  • Reconstruction: error, and how much the model’s loss worsens when \(\hat x\) replaces \(x\) in the forward pass.
  • Sparsity: average number of active features per input.
  • Interpretability: whether the inputs that activate a feature share a meaning people or models can describe, and whether intervening on the feature changes the model’s behaviour as that meaning predicts.

What it is used for. Finding features for specific concepts, steering or ablating them, and tracing circuits in terms of features instead of neurons.

Limits.

  • Reconstruction is imperfect, and the unexplained residual may contain what matters.
  • The features depend on the dictionary size and the training run: larger dictionaries split a feature into finer ones, so there is no single canonical set.
  • An interpretable feature is not proven to be the unit the model computes with; causal tests are still required.
  • Training dictionaries for every layer of a large model is expensive.
  • It is an active research area, and claims about what has been understood should be stated with their scope.

Follow-ups

  • Why does sparsity of features make superposition possible?
  • How would you test that a feature labelled with a concept really represents that concept?
coretrade-offMLE AIasked at TikTok A regulator or a customer asks why your model made a particular decision. What can Shapley-value explanations tell them, where do they mislead, and what are the alternatives?

What SHAP gives. For one prediction, each feature receives an attribution \(\phi_i\), its average marginal contribution to the output over all orders in which features could be added, such that

\[f(x) = \mathbb E[f(X)] + \sum_i \phi_i.\]

The attributions add up exactly to the difference between this prediction and the average prediction. For tree ensembles they can be computed exactly and quickly; for other models they are approximated by sampling. Averaging absolute values over a dataset gives a global importance ranking.

Where they mislead.

  • They explain the model, not the world. A large attribution means the model relies on the feature, not that the feature causes the outcome. Presenting it as causal advice (“raise your income and you will be approved”) is wrong unless the model is causal.
  • Correlated features. Computing a marginal contribution requires evaluating the model with some features “absent”, which is done by substituting values from a background distribution. With correlated features this evaluates combinations that never occur, and credit is split among correlated features in ways that depend on the method.
  • The baseline matters. Attributions are relative to the background data chosen.
  • Stability. Sampling-based estimates vary between runs, and similar inputs can get different explanations.
  • Proxies. A protected attribute can act through correlated features without appearing itself.

Alternatives and complements.

  • An interpretable model. Linear models, scorecards, shallow trees, or boosted models with monotonic constraints. Where decisions must be explained and contested, a slightly less accurate model that can be read directly is often the right choice.
  • Counterfactual explanations. The smallest change to the input that flips the decision, restricted to features the person can change. This is what people want to know.
  • Global views. Partial dependence and accumulated local effects for how a feature moves the prediction; permutation importance for reliance.
  • Example-based. Similar past cases and their outcomes.

In a regulated setting. Find out what the rule requires, such as specific reasons for an adverse decision; validate explanations for stability and for consistency with monotonic expectations; document the method and its limits; and test for disparate impact separately, since an explanation does not establish fairness.

Follow-ups

  • Two features are almost perfectly correlated. How will their attributions behave?
  • Why might you choose a monotonic boosted model over a more accurate unconstrained one?

Reported in interviews (candidate reports on third-party sites, not verified)

  • TikTok, Data Scientist, Oct 2025: SHAP versus variance inflation under collinearity (PracHub)

Synthetic data and data generation pipelines 5% of postings

  • Design a generate, filter and verify pipeline and say what makes its output trustworthy
  • Explain the risks of training on model outputs and how to measure diversity and quality
  • Design a data flywheel from production traffic with a labelling and evaluation loop
seniordesignMLE AI RE Design a pipeline that uses a strong model to generate training data for a task where you have only a few hundred real examples. What makes the output trustworthy?

The pipeline is generate, filter, verify and mix, and most of the value is in the last three.

1. Specify the target distribution. From the real examples and from production inputs, list the dimensions that vary: topics, difficulty, length, language, format, edge cases, the share of inputs that should be refused or escalated. Generation is then steered to cover that grid, instead of asking a model for “more examples”, which returns the same few modes.

2. Generate inputs with controlled diversity. Condition each call on sampled attributes, a persona or a seed example; vary the prompt templates; use real unlabelled inputs wherever they exist, because real inputs with synthetic labels beat fully synthetic pairs.

3. Generate outputs with as much help as the generator can get. Reasoning before the answer, retrieval of source material, several attempts. The expensive process is distilled into the label.

4. Filter.

  • Deduplicate exactly and by embedding similarity.
  • Validate format and constraints in code.
  • Verify correctness with something independent of the generator: execution of code against tests, a checkable answer, grounding in a source document, agreement among several samples, or a separate judge model with a rubric. Discard what fails.

5. Audit by hand. Read a random sample from every batch and estimate the label error rate. A pipeline nobody reads will drift.

6. Mix and train. Combine with the real examples, weighted up. Train, then evaluate only on real, held-out data that the generator never saw.

What makes it trustworthy.

  • Verification that is independent of the generating model.
  • A measured error rate from human audit.
  • Coverage checked against the target grid and against real input statistics.
  • An ablation: does adding the synthetic data improve the metric on real data, and by how much per thousand examples?
  • Lineage: generator model and version, prompts and filters stored with the dataset.

Check the generating model’s terms of use before training another model on its outputs.

Follow-ups

  • Asking for 10 000 examples returns near-duplicates. How do you force diversity?
  • Why must the evaluation set be real data?
seniorconceptMLE RE What are the risks of training models on model-generated data, and how do you measure whether a synthetic dataset is good?

Risks.

  • Loss of diversity. A model’s samples over-represent its high-probability modes and under-represent the tails. Training on them narrows the distribution further. Repeated over generations, with each model trained on the previous one’s output and no fresh real data, the tails disappear; this is what the “model collapse” results describe. Mixing in real data at every generation largely prevents it.
  • Error and bias amplification. The generator’s systematic mistakes, stylistic habits and social biases become training signal, and the student reproduces them with more confidence.
  • Style over substance. The student learns the generator’s surface style, such as length, phrasing and structure, which can be mistaken for quality.
  • No new information. Synthetic data rearranges what the generator knows. It adds knowledge only when something external enters: real inputs, retrieved documents, an execution environment, a verifier, or human review.
  • Evaluation contamination. If synthetic data resembles the benchmark or was produced by the same model that judges the result, scores inflate.
  • Feedback through the web. Generated text published online returns in future training corpora.

Measuring a synthetic dataset.

  • Fidelity. How close it is to real data: compare length, vocabulary and topic distributions; train a classifier to tell real from synthetic, where accuracy near chance is good.
  • Diversity. Distinct n-grams, embedding-space coverage and cluster counts against the real data; near-duplicate rate.
  • Correctness. Label error rate from a human audit of a random sample, and the pass rate of automatic verification.
  • Utility. The only measure that finally counts: train on it, test on real held-out data, and compare with training on real data alone and on both. Plot the gain against the amount of synthetic data; it usually saturates.
  • Slices. Check rare classes and minority groups, where synthetic data is weakest and where it is most often used.

A safe summary: synthetic data works best as an amplifier of real signal with independent verification, and worst as a closed loop.

Follow-ups

  • Under what conditions does a model trained on synthetic data exceed the model that generated it?
  • How would you detect that a dataset has lost its tail?
seniordesignMLE AI Design a data flywheel for an LLM product: how does production usage turn into better models or prompts, and what keeps the loop from degrading?

A flywheel is a loop in which usage produces data, data produces improvements, and improvements produce more usage. It has to be built; it does not happen by logging.

1. Capture. Log every interaction with enough to replay it: inputs, retrieved context, prompt and model versions, outputs, tool calls. Respect consent, retention and redaction rules, and separate data that may be used for training from data that may not.

2. Collect signals of quality.

  • Explicit: ratings, reports. Rare and skewed toward the unhappy.
  • Implicit: the user edits the output, retries, abandons, copies the answer, or accepts a suggestion. Plentiful and noisy.
  • Downstream outcomes: the ticket was resolved, the code was merged.
  • Automatic: judge-model scores and verification checks on a sample.

3. Mine. Cluster failures, find the largest categories, and sample them for review. This error analysis sets the priorities.

4. Label. Turn selected cases into training and evaluation examples: user corrections as targets, human or strong-model relabelling of failures, with review. Route uncertain or novel inputs to labelling first, since they carry the most information.

5. Improve. In order of cost: fix the prompt or retrieval; add the cases to the evaluation set; fine-tune or distil when enough examples of a failure type exist.

6. Gate and ship. Every change is evaluated on the growing regression set and in an online experiment.

What keeps the loop healthy.

  • Selection bias. Logged data reflects what the current system showed and whom it served. Keep some exploration and sample inputs uniformly, not only failures.
  • Self-reinforcement. Training on the model’s own accepted outputs teaches it its own habits. Prefer signals from outside the model: user edits, outcomes, human labels.
  • Noisy implicit feedback. Validate each signal against human judgement before trusting it.
  • Evaluation integrity. Keep the evaluation set separate from mined training data, and refresh it as usage shifts.
  • Privacy. The loop is only as broad as the data you are permitted to use.

Measure the loop itself: time from a failure being observed to its fix shipping.

Follow-ups

  • Which implicit signal would you trust most in a coding assistant, and how would you validate it?
  • How does training on accepted outputs differ from training on corrected outputs?

Pretraining at scale 5% of postings

  • Estimate training compute from parameters and tokens and convert it to GPU-days
  • Describe a pretraining data pipeline, including filtering, deduplication and contamination control
  • Say when continued pretraining on domain text helps and when fine-tuning alone is enough
seniorderivationMLE RE Estimate the compute needed to pretrain a transformer language model from its parameter count and the number of training tokens. Convert it to GPU time.

Rule of thumb. For a transformer with \(N\) parameters, processing one token costs about \(2N\) floating-point operations in the forward pass (each weight takes part in one multiply and one add) and about twice that in the backward pass. Training on \(D\) tokens therefore costs

\[C \approx 6\, N\, D \ \text{FLOPs}.\]

Inference costs about \(2N\) per token. The approximation ignores embeddings and the attention computation’s dependence on context length, which is minor until contexts are very long.

Example. \(N = 10^9\) parameters, \(D = 10^{11}\) tokens: \(C \approx 6 \times 10^{9} \times 10^{11} = 6 \times 10^{20}\) FLOPs.

To GPU time. Divide by the sustained throughput of the hardware, which is peak throughput times the utilisation actually achieved (often 30 to 50% of peak after data loading, communication and memory limits). Suppose a GPU sustains \(3 \times 10^{14}\) FLOPs per second on this workload:

\[\frac{6 \times 10^{20}}{3 \times 10^{14}} = 2 \times 10^{6}\ \text{s} \approx 23\ \text{GPU-days}.\]

On 8 such GPUs with good scaling that is about 3 days. Use measured tokens per second from a short run instead of an assumed FLOP rate as soon as you have one.

What the arithmetic is for.

  • Sizing a run before asking for the budget, and sanity-checking a throughput number: if the measured rate is a third of the estimate, something is wrong in the pipeline.
  • Comparing designs at equal compute. Doubling parameters at fixed compute halves the tokens seen.
  • Seeing that data is rarely free: \(10^{11}\) tokens is on the order of a hundred billion words of deduplicated, filtered text.

Scaling-law work on compute-optimal training found that parameters and tokens should grow together, with roughly 20 tokens per parameter as the reported optimum for one family of models; models meant for cheap inference are deliberately trained on far more tokens per parameter than that.

Follow-ups

  • Where does the factor of 6 come from?
  • Your measured throughput is 40% of the estimate. Where do you look?
seniordesignMLE REasked at OpenAI, Nvidia Describe the data pipeline for pretraining a language model. What decisions matter most for the quality of the resulting model?

Stages.

  1. Sources and mixture. Web text, books, code, scientific text, dialogue, structured data, multilingual text. The proportions set what the model is good at; they are a design decision, tuned with ablations at small scale.
  2. Extraction. Turning HTML, PDFs and markup into clean text is where much quality is won or lost: boilerplate, navigation, broken tables and encoding errors otherwise become what the model learns to produce.
  3. Filtering. Language identification; heuristics on length, repetition and symbol ratios; classifier-based quality scores; removal of unsafe or disallowed content and of personal data; licence and opt-out compliance.
  4. Deduplication. Exact, by hash, and near-duplicate, by MinHash or similar, at document and paragraph level. Duplicates waste compute, cause verbatim memorisation and inflate held-out metrics.
  5. Contamination control. Remove evaluation benchmarks and their near-copies from the training data, and record what was removed, or the model’s reported results are not trustworthy.
  6. Tokenisation and packing. Tokenise once offline, pack documents into fixed-length sequences with separator tokens, shuffle globally and write shards.
  7. Versioning. A manifest of sources, filters and code for every dataset version, so that a model’s behaviour can be traced to its data.

Decisions that matter most.

  • Quality against quantity. Aggressive filtering shrinks the data and usually improves the model per token, up to the point where diversity suffers. Evaluate filters by training small models, not by reading samples alone.
  • The mixture. More code improves code and often reasoning-style tasks; more multilingual text trades against English performance at a fixed budget.
  • Deduplication strength. Too weak leaves memorisation; too strong removes legitimate repetition.
  • Freshness and provenance. A knowledge cutoff, and increasingly a share of model-generated text in web data, which needs detection or down-weighting.

A senior answer treats the dataset as a product with its own tests, metrics and release process.

Follow-ups

  • How would you measure whether a quality filter helps before committing to a full run?
  • How do you detect that a benchmark leaked into the training data?

Reported in interviews (candidate reports on third-party sites, not verified)

  • OpenAI, Machine Learning Engineer, Dec 2025: Pipeline that selects high-quality math documents from web crawls (PracHub)
  • Nvidia, Product Manager, Jun 2026: How raw text becomes an LLM training set: filtering, deduplication, mixing, evaluation (PracHub)
seniortrade-offMLE RE You have a large corpus of unlabelled domain text (clinical notes, legal filings, internal code) and a small labelled set. When is continued pretraining on the domain text worth it before fine-tuning?

What it is. Continue the original self-supervised objective (next-token or masked prediction) on the domain corpus, starting from the pretrained weights, and then fine-tune on the labelled task. It is also called domain-adaptive pretraining.

When it helps.

  • The domain’s vocabulary, notation or style is far from general text: abbreviations in clinical notes, citations and defined terms in contracts, an in-house programming framework. The base model’s token statistics are then off, and unlabelled text fixes that cheaply.
  • Labelled data is scarce relative to unlabelled data. The unlabelled corpus teaches the domain and the labels teach the task.
  • The model is small or medium. Smaller models have less of the domain memorised, so they gain more.

When it does not.

  • The base model already reads the domain well. Check first: measure its perplexity on held-out domain text and its zero-shot task performance. If both are good, the gain will be small.
  • The need is facts that change or must be cited. Retrieval serves that better than weights.
  • The domain corpus is small. A few million tokens will not move a large model, and risks overfitting.

Risks and how to control them.

  • Forgetting. General abilities degrade if the model trains only on narrow text. Mix in general data, use a low learning rate, or train adapters.
  • Losing instruction-following. Continued pretraining of a chat-tuned model on raw text erodes its chat behaviour. Either adapt the base model and then redo instruction tuning, or reformat the domain text as tasks.
  • Privacy and memorisation. Domain corpora often contain sensitive text that the model may reproduce.

How to decide. Run the cheap experiment: a short continued-pretraining run, then the same fine-tune with and without it, compared on the task metric and on a general regression suite.

Follow-ups

  • How would you tell beforehand whether the base model already knows the domain?
  • What happens to a chat model’s behaviour when you continue pretraining it on raw documents?

Reasoning, planning and long-horizon behaviour of models 4% of postings

  • Explain why generating intermediate reasoning improves accuracy and what it costs
  • List the ways to spend more compute at inference and when each pays
  • Explain why success rates fall on long tasks and what training and scaffolding do about it
seniorconceptMLE AI RE Why does letting a model produce intermediate reasoning before its answer improve accuracy? What are the ways to spend more compute at inference, and what does each cost?

Why intermediate tokens help. A transformer’s forward pass is a fixed-depth computation: the number of sequential steps it can perform for one token is bounded by its layers. A problem needing more serial steps than that cannot be solved in one pass. Writing intermediate results into the context turns the model into an iterated computation: each generated token is the output of a full pass and becomes input to the next, so the model can carry state, decompose the problem and build on partial results. Reasoning text is working memory.

Models trained specifically to reason, with reinforcement learning on tasks whose answers can be checked, learn to use this scratch space far better than a general model prompted to “think step by step”.

Ways to spend inference compute.

  • Longer reasoning. A larger thinking budget. Gains are large on multi-step problems, small on recall or simple tasks, and they flatten.
  • Sampling and voting. Generate several answers and take the majority (self-consistency). Works when answers can be compared exactly; cost is linear in the number of samples.
  • Generate and verify. Produce candidates and select with a verifier: unit tests, a checker, or a judge model. The gain depends on the verifier; with a reliable one, many cheap attempts beat one expensive attempt.
  • Search. Explore a tree of partial solutions with a value estimate, expanding the promising branches.
  • Tools. Delegate exact computation, lookup or execution, which converts reasoning errors into tool calls.
  • Iteration with feedback. Run, observe the error and revise, as coding agents do.

Costs and cautions.

  • Output tokens are the expensive ones, and they are generated serially, so latency grows with reasoning length.
  • Returns diminish, and on easy inputs extra reasoning can talk the model out of a correct answer. Route by difficulty.
  • The visible reasoning is not guaranteed to be a faithful account of how the answer was produced.
  • Evaluate at matched cost: compare a small model with a large budget against a larger model with a small one on your task.

Follow-ups

  • When does majority voting over samples fail to help?
  • How would you decide per request how much reasoning budget to allow?
staffconceptMLE AI RE Models that answer single questions well still fail on tasks that take hundreds of steps. Why, and what is done in training and in the surrounding system to extend the horizon?

Why long tasks are harder than their steps.

  • Compounding error. If each step succeeds with probability \(p\) and errors are not caught, an \(n\)-step task succeeds with about \(p^n\). At \(p = 0.99\), 300 steps succeed about 5% of the time. Reliability per step must be very high, or errors must be detected and repaired.
  • Error recovery is a separate skill. Training data mostly shows clean solutions, not how to notice a wrong turn and back out of it.
  • Context management. The history outgrows the window or dilutes attention; the model loses track of the goal, of constraints stated early, or of what it has already tried.
  • Planning and self-assessment. Deciding what to do next, when a subgoal is done and when to stop requires an accurate view of progress, and models tend to declare success early.
  • Sparse feedback. The result is known only at the end, so learning which decision mattered is a hard credit-assignment problem.

In training.

  • Reinforcement learning on multi-step tasks in environments with a verifiable outcome (tests pass, the task state is reached), so that the model is optimised on whole trajectories, including recovery.
  • Training data containing mistakes and their corrections, tool errors and retries.
  • Curricula that lengthen tasks as the model improves.
  • Rewards for the outcome, with care that they cannot be satisfied by shortcuts.

In the system around the model.

  • Verification inside the loop: tests, type checks, validators. Each check turns silent errors into visible ones and resets the compounding.
  • External state: a plan, notes and a task list kept outside the context and re-read, plus compaction of history.
  • Decomposition: sub-tasks with their own context, and checkpoints from which to resume.
  • Budgets and escalation: step limits, and asking a human when stuck.

Measurement. Report success as a function of task length, for instance the length of task (in human time) that the model completes at a given success rate, not a single average. Read trajectories to find where runs go wrong; aggregate success hides the failure mode.

Follow-ups

  • How does a verifier inside the loop change the compounding-error argument?
  • What would you put in a training environment so that the model learns to recover from its own mistakes?

Code generation models 4% of postings

  • Explain execution-based evaluation of code generation, from function-level tests to repository-level tasks
  • Decide between retrieval and fine-tuning to adapt a code model to a private codebase
seniorconceptMLE AI RE How are code-generation models evaluated? Go from function-level benchmarks to repository-level tasks, and say what each measurement misses.

Code has an advantage over prose: it can be executed, so correctness can be checked against tests instead of compared with a reference text.

Function-level benchmarks. A prompt with a signature and docstring; the model’s completion is run against hidden unit tests. The metric is pass@k: the probability that at least one of \(k\) samples passes. With \(n\) samples per problem of which \(c\) pass, the unbiased estimate is

\[\text{pass@}k = \mathbb E_{\text{problems}}\left[1 - \binom{n - c}{k} \Big/ \binom{n}{k}\right].\]

These benchmarks are small, self-contained, mostly saturated by current models, and widely leaked into training data.

Repository-level tasks. The model, usually as an agent with tools, receives a real repository and an issue description and must produce a patch. The patch is judged by tests that the original human fix made pass, while tests that passed before must still pass. This measures what matters in practice: finding the relevant code, understanding conventions, making a multi-file change and not breaking anything.

What these measurements miss.

  • Test adequacy. Passing the available tests is not correctness. Weak tests accept wrong patches, and overly specific tests reject valid ones. Benchmarks need human-validated subsets.
  • Contamination. Public repositories and their fixes are in training data. Prefer tasks dated after the model’s cutoff, or private ones.
  • Quality beyond tests. Readability, maintainability, security, performance and fidelity to the codebase’s style, which need review or static analysis.
  • Scaffold dependence. An agent’s score reflects the model plus its tools, prompts and budget. Compare models under the same scaffold, and report cost and steps.
  • Distribution. Benchmarks over-represent popular open-source Python; your languages, frameworks and task mix may differ.
  • Interaction. Real use includes clarifying questions, partial specifications and review cycles.

For a product. Build an internal evaluation from your own repositories: historical issues and their merged fixes with tests, held out by date. Add online measures such as acceptance and retention of suggestions, merged changes and reverts. Track the model’s unsafe behaviours as well: deleting tests, disabling checks, or hard-coding expected outputs to make tests pass.

Follow-ups

  • Why is pass@10 much higher than pass@1, and which reflects product use?
  • An agent made the tests pass by editing the tests. How should the evaluation handle that?
seniordesignAI MLEasked at Meta Your company wants its coding assistant to work well on a large private codebase with in-house frameworks. Do you fine-tune, build retrieval, or both? Describe the system and its evaluation.

Start with context, not weights. What a general model lacks is knowledge of this codebase: its APIs, conventions and current state. Code changes daily, so that knowledge belongs in retrieval, where it is always current, respects access permissions and needs no retraining.

Retrieval and context for code.

  • Sources. The open file and cursor region, imports and their definitions, call sites of the symbols in play, sibling files, tests, recent edits, documentation and design notes.
  • Signals. Lexical search for identifiers (exact names matter in code), embeddings for intent, and the code graph from static analysis: definitions, references, type hierarchy. Structure-aware retrieval beats text similarity alone.
  • Agentic search. For multi-file tasks, let the model search, read and run tools itself.
  • Project rules. A maintained instructions file with conventions, commands and pitfalls, loaded into every session.

When to add fine-tuning.

  • In-house languages, frameworks or idioms pervasive enough that the model is slow and error-prone even with examples in context.
  • Latency-critical completion, where a small tuned model must work with little context.
  • Consistent style that prompts cannot enforce.

Training data: the repository history as edit examples (the state before, the change and its description), filtered to merged, reviewed changes; completion examples masked from real files. Exclude secrets and generated or vendored code. Retrain on a schedule, since the codebase moves.

Risks. Stale knowledge in a tuned model; memorised secrets; licensing of included code; a tuned model that degrades at general reasoning; and the cost of redoing tuning at each base-model upgrade.

Evaluation.

  • Offline: historical tasks held out by date, each with the repository state before the change and tests from the merged fix; completion accuracy on masked real code. Compare the base model, base plus retrieval, tuned, and tuned plus retrieval.
  • Online: acceptance rate, how much accepted code survives, task completion for agentic flows, review outcomes and reverts.
  • Guardrails: tests and linters in the loop, no secrets in suggestions.

The expected finding: retrieval and good project context give most of the gain; fine-tuning helps completion latency and house idioms.

Follow-ups

  • Why hold out evaluation tasks by date and not at random?
  • How do you keep repository permissions intact in retrieval?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Meta, Machine Learning Engineer, Jun 2026: LLM-based coding assistant end to end (PracHub)

Continual learning, memory and personalization of models 2% of postings

  • Explain in-context learning and when few-shot prompting substitutes for fine-tuning
  • Explain catastrophic forgetting and the three families of mitigation
  • Choose among context, retrieval and adapters for personalising a model
coreconceptMLE AI RE What is in-context learning? How does it differ from fine-tuning, and when is few-shot prompting enough?

In-context learning is a model’s ability to perform a task from instructions and examples placed in its prompt, with no change to its weights. Given a few input-output pairs and a new input, the model produces the corresponding output.

Why it works. Pretraining text is full of documents with internal regularities: lists in a consistent format, worked examples followed by another, translations side by side. Predicting the next token in such documents requires inferring the pattern from the earlier part and continuing it. Large models become good at this inference, so that a prompt containing examples is treated as a document whose pattern is to be continued. Mechanistically it is still debated how much is recognising a task already learned and how much is learning a new mapping on the fly; both appear to occur.

Compared with fine-tuning.

In-context Fine-tuning
Where the task lives In the prompt, per request In the weights
Setup Minutes; no training A dataset, a training run, an evaluation
Examples used A handful to a few hundred, limited by the context Thousands and more
Cost per request Every request pays for the example tokens Short prompts
Changing the task Edit the prompt Retrain
Ceiling Bounded by what the model can infer from few examples Higher for narrow, consistent tasks

Few-shot prompting is enough when the task is one the model nearly does already and the examples mainly communicate format, label set, tone or edge-case policy; when the task changes often; or when there is too little data to train.

Move to fine-tuning when quality stops improving as examples are added; the prompt has become long enough that cost or latency hurts; behaviour must be very consistent; or a smaller model must do the task.

Practicalities.

  • Results are sensitive to which examples are chosen, their order and their format. Retrieving examples similar to the query usually beats a fixed set.
  • Examples bias the output toward their labels and style, including their mistakes.
  • Put stable examples in a cached prefix to reduce cost.
  • Evaluate prompt variants on a held-out set as you would evaluate models.

Follow-ups

  • Performance drops when you reorder the examples. What does that tell you, and what do you do?
  • How would you decide how many examples to include?
seniorconceptMLE RE What is catastrophic forgetting, and what are the main ways to train a model on new data without losing what it knew?

The phenomenon. When a network is trained on new data alone, gradient descent moves the weights wherever the new loss decreases, with nothing to hold them where the old tasks need them. Performance on earlier tasks can fall sharply after a small amount of new training. It is the default behaviour of sequential training, and the reason models are usually retrained on all data together.

Three families of mitigation.

  1. Rehearsal (replay). Mix old data, or a sample of it, into the new training. Simple and the most effective. When the old data is unavailable, use pseudo-rehearsal: the old model’s own outputs on generic inputs serve as training targets, which is a form of distillation from the previous model.

  2. Regularisation. Penalise changes to weights that mattered for the old tasks. Elastic weight consolidation adds

    \[\mathcal L = \mathcal L_{\text{new}}(\theta) + \frac{\lambda}{2} \sum_i F_i\, (\theta_i - \theta_i^*)^2,\]

    where \(\theta^*\) are the old weights and \(F_i\) is the Fisher information, an estimate of how sensitive the old loss is to weight \(i\). Simpler versions are a low learning rate, few steps, weight decay toward the old weights, or a KL penalty toward the old model’s predictions.

  3. Parameter isolation. Give new tasks their own parameters and freeze the rest: adapters or LoRA modules per task, added heads or routing. Nothing is forgotten because nothing shared is changed; the cost is choosing the right module at inference and no transfer from new to old.

For fine-tuning large language models.

  • Mix general instruction data with the task data.
  • Prefer adapters with modest rank when the base model’s general ability must be kept.
  • Average or interpolate the tuned and original weights to trade task gain against retention.
  • Evaluate retention explicitly, on a suite covering what must not regress.

The underlying tension is stability against plasticity: a model that cannot change cannot learn, and one that changes freely cannot remember. Continual learning over long sequences of tasks without replay remains unsolved in general, which is why production systems lean on periodic retraining, retrieval and context for new knowledge.

Follow-ups

  • Why does replaying a small fraction of old data work so well?
  • What does the Fisher information measure in the penalty, and what is its weakness?
seniordesignMLE AI RE You want a model that adapts to each user over time and keeps up with new information. Compare putting that adaptation in the context, in retrieval memory, and in the weights.

Three places to put what the system learns after deployment, with different costs.

1. Context. Keep a profile, preferences and recent history in the prompt.

  • Immediate, transparent, easy to edit or delete, no training.
  • Limited by context length and paid for on every request; long histories dilute attention.
  • Best for stable preferences and the current session.

2. Retrieval memory. Store facts, past interactions and documents outside the model and fetch what is relevant per request.

  • Scales to large histories and to information newer than the model; sources can be cited; deletion is a database operation; permissions can be enforced.
  • Quality depends on what is written to memory and on retrieval. Wrong or outdated memories are retrieved with the same confidence as right ones, so writes need de-duplication, conflict resolution and expiry.
  • Best for knowledge and for episodic history.

3. Weights. Fine-tune on the user’s or organisation’s data: per-user or per-tenant adapters, or periodic updates of the shared model.

  • Changes behaviour that context cannot easily convey: style, skills, domain idioms. Nothing is paid per request in tokens.
  • Costly to produce and to serve at per-user granularity (storing, loading and batching thousands of adapters); slow to update; prone to forgetting; hard to inspect.
  • Deletion is hard. Removing one user’s influence from shared weights means retraining, which is a privacy and compliance problem. Per-user adapters at least isolate it.
  • Best for stable, shared skills, updated on a schedule from aggregated and permitted data.

Putting it together. A layered design: weights hold general ability and slowly changing skills; retrieval holds knowledge and history; context holds the current task and the most important preferences. Consolidation moves things downward over time: repeated corrections in sessions become memory entries, and patterns across many users become training data.

Research directions to know by name: adapting weights at inference on the current input (test-time training), model editing to change individual facts, and learned long-term memory modules. They are promising and not yet routine in production.

Evaluation. Does personalisation improve task success for returning users; does the system update when the user’s facts change; does anything leak between users; and can a user’s data be fully removed.

Follow-ups

  • A user’s preference changed. How does each of the three mechanisms pick that up?
  • What makes per-user adapters hard to serve at scale?

Tokenization and data preprocessing for LMs 1% of postings

  • Implement the BPE training loop and explain how encoding applies the merges
  • Explain the trade-off in vocabulary size and the failure modes around numbers, whitespace and special tokens
corecodingMLE RE Implement the training loop of byte-pair encoding: given word counts, learn a list of merges. Then explain how a new string is encoded.
from collections import Counter

def train_bpe(word_counts, num_merges):
    """word_counts: {word: count}. Returns the ordered list of merges."""
    vocab = {tuple(w) + ("</w>",): c for w, c in word_counts.items()}
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in vocab.items():
            for a, b in zip(symbols, symbols[1:]):
                pairs[(a, b)] += c
        if not pairs:
            break
        best = max(pairs, key=pairs.get)
        merges.append(best)
        new_vocab = {}
        for symbols, c in vocab.items():
            out, i = [], 0
            while i < len(symbols):
                if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == best:
                    out.append(symbols[i] + symbols[i + 1])
                    i += 2
                else:
                    out.append(symbols[i])
                    i += 1
            key = tuple(out)
            new_vocab[key] = new_vocab.get(key, 0) + c
        vocab = new_vocab
    return merges

The algorithm. Start from characters (or bytes). Repeatedly count adjacent symbol pairs over the corpus, weighted by word frequency, merge the most frequent pair into a new symbol, and record the merge. The vocabulary is the base symbols plus one symbol per merge, so the number of merges sets the vocabulary size.

Encoding a new string. Split it into base symbols, then apply the learned merges in the order they were learned (equivalently, repeatedly merge the adjacent pair with the lowest merge rank) until none applies. Frequent words end up as one token, rare words as several pieces.

Points to raise.

  • Complexity. This version recounts all pairs for every merge. Real implementations update the counts incrementally for the pairs affected by a merge and keep a priority queue.
  • Ties must be broken deterministically, or two runs give different tokenizers.
  • Byte-level BPE starts from the 256 byte values, so any string is representable and there is no unknown token.
  • Pre-tokenisation. Splitting on whitespace first, as here, prevents merges across word boundaries; how spaces are attached to tokens is a design choice that affects every downstream count.
  • The merge list is part of the model. Encoding with a different tokenizer than the one used in training silently breaks the model.

WordPiece and unigram tokenizers differ in how they score candidates but produce the same kind of subword vocabulary.

Follow-ups

  • How would you make the merge step efficient for a large corpus?
  • What does the end-of-word marker do, and what replaces it in byte-level tokenizers?
seniorconceptMLE AI REasked at Amazon How does the choice of tokenizer affect a language model? Discuss vocabulary size and the failure modes that trace back to tokenization.

Vocabulary size is a trade.

  • A larger vocabulary gives shorter sequences for the same text, so less compute per document and more text per context window. It costs a larger embedding and output matrix, and rare tokens that are seen too seldom to be learned well.
  • A smaller vocabulary gives longer sequences and well-trained tokens, and pushes more of the work of composing words onto the model.

Vocabularies from a few tens of thousands to a few hundred thousand tokens are common for general models. The compression ratio (characters or bytes per token) on your own data, per language, is the number to measure, because it sets cost and effective context length.

Failure modes that trace to tokenization.

  • Numbers and arithmetic. Digits are grouped inconsistently, so the same number splits differently depending on context, which makes digit-level operations hard to learn.
  • Character-level tasks. Spelling, counting letters and reversing strings are hard because the model sees tokens, not characters.
  • Whitespace and formatting. A leading space usually makes a different token. Trailing spaces in a prompt, or a different indentation convention in code, shift the model off-distribution.
  • Languages. A tokenizer trained mostly on English splits other scripts into many more tokens per word, which raises cost and lowers quality for those languages.
  • Rare strings. Identifiers, URLs, chemical names and base64 fragment into long sequences of meaningless pieces.
  • Special tokens. Role markers and control tokens must map to their reserved ids. User text that can produce those ids is an injection risk, so untrusted input must be encoded with special tokens disabled.
  • Mismatch. A model served with a different tokenizer version, or with tokens added without resizing and training the embeddings, degrades silently.

Engineering consequences.

  • Count tokens with the model’s own tokenizer for budgeting and truncation; character counts mislead.
  • Truncate at token boundaries and never in the middle of a multi-byte character.
  • When adding tokens for a domain, initialise their embeddings sensibly (for example the mean of their sub-tokens) and train them.
  • The tokenizer is fixed for the life of a model family; changing it means retraining.

Byte- or character-level models avoid most of these problems and pay with much longer sequences.

Follow-ups

  • Your product’s costs are 3 times higher for one language. How do you confirm that tokenization is the cause?
  • Why is letting user input produce special tokens a security problem?

Reported in interviews (candidate reports on third-party sites, not verified)

  • Amazon, Applied Scientist, Jun 2026: Subword tokenisation design and KL-regularised fine-tuning (PracHub)

Deep dives on this site