Inference, serving and model optimization
Named in 79% of 2253 senior postings · 33 review cards
Running models for users: serving systems and batching, LLM inference engines, latency and throughput engineering, quantization and compiled runtimes, on-device deployment, capacity and GPU cost, and the reliability practice around all of it. Four in five postings name something here, led by reliability (52%) and latency or performance (48%), which appear in AI engineer postings as often as in ML engineer ones. It is tested in system design rounds (a latency budget, a capacity estimate), in debugging scenarios (a slow or flaky endpoint) and in deep dives for inference and platform roles.
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 |
|---|---|---|---|---|---|
| Reliability, SLOs and on-call for ML systems | 41% | 64% | 33% | 4 | |
| Latency, throughput and performance engineering | 49% | 49% | 40% | 5 | |
| Model serving systems | 25% | 16% | 20% | 6 | |
| Capacity, autoscaling and GPU cost efficiency | 14% | 16% | 7% | 3 | |
| On-device / edge / embedded ML | 17% | 10% | 6% | 3 | |
| GPU programming and kernel-level optimization | 12% | 11% | 18% | 3 | |
| LLM inference engines (vLLM, TGI, TensorRT-LLM, llama.cpp) | 11% | 11% | 12% | 4 | |
| Quantization and efficient inference | 14% | 6% | 14% | 3 | |
| Inference runtimes and compilers (ONNX, TensorRT, CoreML) | 8% | 5% | 5% | 2 |
In the postings’ words
Establish strong ML production practices spanning offline and online evaluation, experimentation, observability, safe rollout and rollback, model-quality regressions, and incident response.
Atlassian · Senior Principal Machine Learning Systems Engineer, Search Platform
Build robust, low-latency, and compliant integration points with core Cloud and Alphabet systems (Salesforce, SAP, Vertex AI, Gemini Enterprise).
Google · Staff Software Engineer, AI Agent Architecture for Google Cloud Business Platforms
Familiarity with vector databases, model serving, and inference optimization is a plus
Experience deploying and scaling open-source or fine-tuned LLMs in production, including GPU capacity planning, batching, caching, quantization and inference optimization.
CrowdStrike · Sr. Software Engineer - Charlotte AI (Hybrid, ROU)
Experience with on-device ML, model optimization (knowledge distillation, quantization, pruning), or production-grade ML pipelines.
Experience leading architecture for highly available and performance-critical systems.
Proficiency in PyTorch/JAX, distributed training, and inference optimization (e.g., quantization, model compression)
TikTok · Research Engineer - Foundation Models, Ads Integrity
The senior bar
What separates a senior answer from a mid-level one in this area.
- Starts from the SLO and the traffic shape, then derives batch size, replica count and cost with arithmetic instead of adjectives.
- Explains where latency goes in a request (queueing, preprocessing, model, postprocessing, network) and measures each part before optimising any.
- Knows what an LLM engine does to raise throughput (continuous batching, cache management, prefill and decode scheduling) and what each technique costs in tail latency or memory.
- Treats quantization, compilation and distillation as changes that need an accuracy evaluation on the real task, not as free speedups.
- Scales GPU services on load signals that lead, plans for cold starts, and states cost per request.
- Designs for failure with timeouts, fallbacks and load shedding, and counts model quality as part of reliability.
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.
Reliability, SLOs and on-call for ML systems 52% of postings
- Define SLIs and SLOs for an ML service, including quality, and compute an error budget
- Design fallbacks and graceful degradation for a model dependency
- Set timeouts, retries and hedging without causing a retry storm
- Run an incident caused by a bad model release from detection to postmortem
coreconceptMLE AI Define SLI, SLO and error budget, and propose SLOs for a service whose core is a model.
- SLI (service level indicator): a measured ratio of good events to valid events, such as the share of requests answered successfully in under 300 ms.
- SLO (objective): a target for an SLI over a window, such as 99.9% over 30 days.
- Error budget: what the SLO allows to go wrong, \(1 - \text{SLO}\). At 99.9% over 30 days that is 0.1% of requests, or about 43 minutes of full outage. The budget is spent on incidents and on risky changes; when it is exhausted, releases slow down and reliability work takes priority. It turns “how reliable” into a shared decision between product and engineering.
- An SLA is a contract with consequences; it should be looser than the internal SLO.
SLOs for a model-backed service.
- Availability: share of valid requests that get a non-error response.
- Latency: share of requests under a threshold, at two thresholds if needed. For streaming LLM responses, separate objectives for time to first token and for inter-token or total time.
- Quality of the answer path: a request served by a fallback, a default or a truncated context is “up” but degraded. Track the share served by the full path.
- Freshness: age of the model, the features and the index against a limit.
- Correctness proxies: rate of malformed outputs, guardrail triggers, or a sampled quality score against a floor. These are noisier, so use them as SLOs only where the measurement is trustworthy.
Alerting. Page on the rate at which the budget burns, not on raw thresholds: a fast burn (for example 2% of the monthly budget in an hour, a burn rate of 14.4) pages immediately, and a slow burn opens a ticket. This removes most noisy alerts.
Choose targets from what users need and what dependencies allow; a service cannot be more available than a hard dependency unless it has a fallback.
Follow-ups
- Your model API depends on a provider with 99.5% availability. Can you offer 99.9%?
- How would you write a quality SLO for an LLM feature?
seniordesignMLE AIasked at Anthropic The model your product depends on is slow or unavailable. Design the fallbacks and the degradation path.
Decide in advance what the product does at each level of impairment, so that an incident executes a plan.
Detect quickly and per request.
- A timeout on every model call, set from the latency budget, not a library default.
- A deadline propagated from the edge, so that work on already-abandoned requests stops.
- A circuit breaker per dependency: after a failure-rate threshold, stop calling for a cool-down period and go straight to the fallback, which protects both sides and removes the timeout wait from every request.
A ladder of fallbacks, best first.
- Another replica, zone or region of the same model.
- A secondary model: a smaller or older version, or another provider. Its prompts and thresholds must be qualified in advance, since behaviour differs.
- A cached or precomputed result: the last good answer, a batch-scored prediction.
- A heuristic or rule: popularity ranking, a default decision that is safe (for fraud, which direction is safe is a business choice made beforehand).
- A clear failure: tell the user and offer retry, or queue the work for later.
Degrade before failing. Under load, reduce the work per request: fewer candidates, shorter context or output, no reranking step, lower-priority traffic shed first. Prioritise by request class, such as paying users, interactive over batch.
Make fallbacks real.
- Size them: the fallback path receives full traffic at the worst moment.
- Exercise them regularly with fault injection; an untested fallback fails when needed.
- Mark every response with the path that served it, measure the fallback rate and alert on it, because a silent fallback is a quality incident that looks healthy.
- Avoid amplification: no retries on top of retries, and bounded queues.
Recovery. Close the breaker gradually, and beware of a thundering herd refilling caches.
For agents and multi-step pipelines, also decide what to do with partially completed work: checkpoint and resume, or roll back side effects.
Follow-ups
- Which direction is the safe default when a fraud model times out?
- How do you keep a fallback model’s quality from being discovered during the incident?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Aug 2026: Review and scale an inference service design (PracHub)
- Anthropic, Software Engineer, Aug 2026: Improve an inference service with admission control, batching, shedding, caching and idempotency (PracHub)
- Anthropic, Machine Learning Engineer, Jan 2026: Production ML serving system with focus on scaling and reliability (PracHub)
- Anthropic, Software Engineer, Sep 2025: Review an inference API design for scale (PracHub)
seniorconceptMLE AIasked at Anthropic How do you set timeouts and retries for calls to a model service without making an outage worse? Where do hedged requests fit?
Timeouts. Every call needs one, derived from the caller’s remaining deadline. Too long, and threads pile up behind a dead dependency; too short, and normal tail requests fail and are retried, adding load. Set it a little above the dependency’s healthy p99 and pass the remaining budget downstream, so that a retry never exceeds what the user is still waiting for.
Retries. Retry only failures that are likely transient (connection errors, 429, 503, timeouts) and only operations that are idempotent or carry an idempotency key.
- Exponential backoff with jitter, so that clients do not retry in synchrony.
- Honour a retry-after hint from the server.
- A small maximum number of attempts.
- A retry budget: cap retries at a fraction (say 10%) of request volume per client. Without it, a dependency that slows down receives two or three times its normal load exactly when it is weakest. That feedback loop is a retry storm.
- Retry at one layer only. Three layers each retrying three times multiply into 27 attempts.
For GPU inference a retry is expensive, and a timed-out request may still be running on the server. Cancel the work on the server when the client gives up, or the retried request competes with its own abandoned predecessor.
Hedged requests. To cut tail latency, send a second copy of a request to another replica if the first has not answered within, say, the p95 latency, take whichever returns first and cancel the other. This trims the tail at the cost of a few percent extra load, because only slow requests are duplicated. Conditions: idempotent requests, independent replicas (a hedge to an equally overloaded replica helps nothing), and a cap on the hedge rate so that it switches itself off under overload. For streamed LLM output, hedging on time to first token is the practical form.
Server side. Shed load early with a clear, fast error, which is cheaper for everyone than a slow timeout.
Follow-ups
- Explain how retries can turn a brief slowdown into a sustained outage.
- Why must hedging be disabled or capped when the service is overloaded?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Aug 2026: Improve an inference service with admission control, batching, shedding, caching and idempotency (PracHub)
seniordebuggingMLE AI You are on call. A model version deployed an hour ago is returning degraded outputs, but every health check and latency dashboard is green. Walk me through the incident.
1. Confirm and size it. What is the evidence: user reports, a drop in a quality or business metric, a spike in fallback or guardrail rates, a change in the prediction distribution? Which share of traffic and which segments? Correlate the start time with the deploy.
2. Declare and assign roles. If users are affected, open an incident, name an incident lead and a communicator, and start a timeline. Do not debug alone in silence.
3. Mitigate before diagnosing. A change went out an hour ago and quality fell: roll back. Roll back the whole unit (model, preprocessing, prompt, feature definitions, configuration) to the last known good version, and verify that the symptom clears. If rollback is not possible, shift traffic to the previous version, switch to the fallback path or disable the feature. Minutes matter more than understanding at this stage.
4. Check for lasting damage. Did the bad model write anything: stored predictions, cached responses, messages sent to users, training logs that will feed the next retrain? Purge caches and mark the affected data range.
5. Diagnose on logs, not on production. Replay logged requests through both versions and compare. Typical causes: a preprocessing or tokenizer mismatch between training and serving, a wrong artefact or configuration promoted, a feature missing online and silently defaulted, a quantised or exported variant that was never evaluated, or an evaluation set that did not represent production traffic.
6. Communicate. Status updates at regular intervals to stakeholders, in plain terms: impact, mitigation, next update.
7. Postmortem, blameless. The key questions here are why health checks were green and why the release gate passed. Actions usually include an output-quality canary metric with automatic rollback, a shadow comparison against the previous version before rollout, a skew test in the release pipeline, and an alert on prediction-distribution change.
The lesson to state: availability and latency checks do not observe correctness; a model service needs a quality signal in its release and alerting path.
Follow-ups
- Rollback is impossible because the feature schema changed. What do you do?
- What would an automatic rollback criterion for output quality look like?
Latency, throughput and performance engineering 48% of postings
- Explain why p99 matters more than the mean and where tail latency comes from
- Write a latency budget for a request and say how each part is measured
- Relate utilisation to queueing delay and batch size to throughput
- Run a load test with an open-loop generator and realistic inputs, and find the knee
- Diagnose a GPU service that is slow while the GPU is mostly idle
coreconceptMLE AI Why do we set latency targets on p99 instead of the average, and where does tail latency come from?
Why percentiles. Latency distributions are skewed: most requests are fast and a few are very slow, so the mean describes almost no real request. Users experience the tail more often than “1%” suggests:
- A session makes many requests. With 20 requests per page view, the chance that at least one exceeds the p99 is \(1 - 0.99^{20} \approx 18\%\).
- A request fans out. If it waits for 100 backends and each is slow 1% of the time, \(1 - 0.99^{100} \approx 63\%\) of requests are slow.
- The slowest requests often belong to the heaviest and most valuable users.
Where the tail comes from.
- Queueing: bursts arrive while the server is busy. This is the largest source, and it grows sharply with utilisation.
- Input size: long sequences, large images, many candidates. Model time is a function of input size.
- Batching: waiting to fill a batch, or sharing a batch with a long input.
- Runtime pauses: garbage collection, memory allocation, page faults, a Python thread holding the interpreter lock.
- Cold paths: cache misses, first request after a deploy, lazy initialisation, model loading, autoscaling lag.
- Shared resources: noisy neighbours, CPU throttling, network retransmits.
- Dependencies: a slow feature store or downstream model, plus retries.
Practice. Measure at the client as well as the server, since queueing in front of the server is invisible to it. Keep histograms, not averages, and never average percentiles across hosts. Look at the slowest traces, which usually share one cause. State targets as “99% of requests under X ms over a window”, and consider p99.9 for high-fan-out systems.
Follow-ups
- Why is averaging the p99 of ten servers wrong?
- What is the difference between latency measured at the server and at the client?
coredesignMLE AIasked at Anthropic You are given a 200 ms p99 budget for an endpoint that calls a model. How do you break it down, and how do you make sure each part is measured?
Write the request path as stages and give each a budget that sums to less than the total, leaving slack for variance.
A typical breakdown:
| Stage | Example budget |
|---|---|
| Network and TLS, client to edge and edge to service | 20 ms |
| Authentication, routing, request parsing | 5 ms |
| Feature or context retrieval (parallel calls) | 30 ms |
| Preprocessing or tokenisation | 5 ms |
| Queue and batch wait | 10 ms |
| Model forward pass | 80 ms |
| Postprocessing, business rules, serialisation | 10 ms |
| Slack | 40 ms |
Principles:
- Budgets are for the tail. Stage p99s do not add up to the end-to-end p99, but assigning each stage a p99 budget and requiring the sum to fit is a safe engineering rule.
- Parallelise independent calls so the stage costs the maximum, not the sum, and give each a timeout with a default so one slow dependency cannot consume the budget.
- Propagate a deadline with the request, so that downstream stages stop working on a request that has already timed out.
- The model’s share is set by input size. Cap sequence length or candidate count so that worst-case inputs fit.
Measurement:
- Distributed tracing with a span per stage, including time spent in queues, which is the part most often missing.
- Histograms per stage, broken down by input size and model version.
- Client-side measurement for the true end-to-end number.
- A continuous synthetic probe and a load-test regression in CI, so that a change which spends another stage’s budget is caught before production.
When the budget does not close, the options are a smaller or distilled model, quantization or compilation, caching or precomputation, reducing work (fewer candidates, shorter context), or renegotiating the budget with evidence.
Follow-ups
- The model stage is within budget but end-to-end p99 is 400 ms. Where do you look first?
- How would this breakdown change for a streaming LLM response?
seniorderivationMLE AI Why does latency explode as a server approaches full utilisation? Give the queueing argument and say what it implies for capacity planning.
Model one server with random arrivals at rate \(\lambda\) and service rate \(\mu\) (an M/M/1 queue). Utilisation is \(\rho = \lambda / \mu\), and the mean time in the system is
\[W = \frac{1}{\mu - \lambda} = \frac{1/\mu}{1 - \rho}.\]
Time in system is the service time divided by \(1 - \rho\): twice the service time at 50% utilisation, 5 times at 80%, 10 times at 90%, 100 times at 99%. The tail is worse than the mean, because the waiting time is itself widely spread.
Why. Arrivals are bursty and capacity that sat idle during a gap cannot be saved for the next burst. As \(\rho \to 1\) the queue takes longer and longer to drain after each burst.
What changes the curve.
- Variance. More variable service times make waiting worse (for a general service distribution the wait scales with \(1 + c_s^2\), where \(c_s\) is the coefficient of variation). Mixed short and long inputs are expensive; separating them into pools helps.
- Pooling. \(c\) servers behind one queue behave much better than \(c\) separate queues at the same utilisation, which is why least-loaded or shared-queue routing beats random assignment.
- Batching. A GPU serves a batch at a time, so it tolerates higher utilisation than the simple model suggests, but the same knee exists.
Implications.
- Plan to a target utilisation well below 100% at peak; 50 to 70% is common for latency-sensitive services, higher for batch.
- The latency SLO, not the average throughput, determines capacity.
- Past the knee no tuning helps; you need more capacity or load shedding. A bounded queue with rejection keeps latency of accepted requests finite.
- Autoscaling must react before the knee, since queues grow faster than replicas start.
Follow-ups
- Two pools at 60% utilisation each or one pool of twice the size at 60%. Which has lower latency and why?
- How does a bounded queue change what happens above capacity?
seniorconceptMLE AI How do you load test an inference service so that the result predicts production behaviour?
Use an open-loop generator. A closed-loop tool keeps a fixed number of virtual users, each waiting for its response before sending the next request. When the server slows down, the tool sends less, so it never observes the queue that real, independent users would create, and it under-reports the tail. This is coordinated omission. An open-loop generator sends at a fixed arrival rate regardless of responses, and measures latency from the intended send time.
Use realistic inputs. Model latency depends on input size. Replay sampled production requests, or match the distribution of sequence lengths, image sizes, candidate counts and, for LLMs, both prompt and output lengths. A test with one short prompt overstates capacity several times. Include the cache hit rate you expect, not 100%.
Find the curve, not a number. Step the arrival rate up and record throughput, p50, p99 and error rate at each step, holding each level long enough for steady state. The knee where p99 leaves the SLO is the capacity of one replica.
Test what breaks.
- Bursts and ramps at the speed real traffic changes, to test autoscaling and cold start.
- Overload beyond capacity: does the service shed load and recover, or collapse?
- A slow or failing dependency.
- A long soak run for memory growth and fragmentation.
Conditions. Same hardware, model version, batching configuration and replica count logic as production; warm up before measuring; generate load from enough machines that the generator is not the bottleneck; measure on the client side.
Use the result. Per-replica capacity at the SLO feeds the replica calculation and the autoscaling target; rerun it in CI on a schedule so that a regression in a dependency or a model change is caught as a capacity change.
Follow-ups
- Your closed-loop test showed p99 of 80 ms and production shows 600 ms at the same request rate. Explain.
- How do you load test an endpoint whose outputs are streamed tokens?
seniordebuggingMLE AI An inference service on a GPU is slower than expected, and monitoring shows GPU utilisation around 30%. What is going on and how do you find it?
Low utilisation with high latency means the GPU is waiting for work. The bottleneck is somewhere on the way to it or around it.
Likely causes.
- CPU-side preprocessing. Tokenisation, image decoding and resizing, feature assembly in Python. Often single-threaded and holding the interpreter lock.
- Batch size of one. No batching, or a batcher whose wait is too short at this traffic level, so each pass uses a small part of the device.
- Many small operations. A model made of small layers or Python-level loops pays launch overhead per operation; the GPU idles between them.
- Host-device transfers and synchronisation points. Moving tensors back to the CPU in the middle of the forward pass (
.item(),.cpu(), printing, Python control flow on tensor values) forces a wait each time. - I/O per request. Reading features, loading an adapter, or logging synchronously.
- Too few serving threads or processes, so requests queue in front of an idle GPU.
- Memory allocation. Varying input shapes cause repeated allocation and cache misses in the allocator or, with a compiling runtime, recompilation for each new shape.
How to find it.
- Trace one request with spans for queue, preprocess, transfer, forward and postprocess.
- Run a profiler that shows CPU and GPU timelines together. Gaps on the GPU timeline aligned with CPU activity name the culprit.
- Time the forward pass alone on a prepared batch, with proper synchronisation, to get the model’s floor. If the floor is fine, the model is not the problem.
- Look at CPU utilisation per core and at throttling: one core pinned at 100% is the signature of a Python bottleneck.
Fixes in the usual order. Batch; move preprocessing out of the request thread or onto the GPU; use a fast tokenizer and multiple workers; remove synchronisation points; compile or fuse the model to cut per-operation overhead; fix shapes or bucket them.
Follow-ups
- How do you time a forward pass correctly on a GPU?
- Utilisation reads 100% but throughput is still poor. What does utilisation actually measure?
Model serving systems 20% of postings
- Choose among online, batch, streaming and asynchronous inference for a use case
- Trace a request through a model server and say where it can queue
- Explain dynamic batching and tune maximum batch size and maximum wait against an SLO
- Design serving for many models on few GPUs, including loading, routing and isolation
coretrade-offMLE AIasked at Anthropic Online, batch, streaming or asynchronous inference: how do you choose for a given feature?
Choose by when the input is known and how soon the output is needed.
| Mode | How | Fits | Costs |
|---|---|---|---|
| Batch (offline) | Score a whole table on a schedule and store the results | Inputs known in advance and slowly changing: nightly recommendations, churn scores, embeddings for a catalogue | Stale by up to one period; computes predictions nobody reads; cannot use request-time context |
| Online (synchronous) | Model called inside the request | Output depends on request-time input: search ranking, fraud at checkout, chat | Latency SLO, provisioning for peak, online feature availability |
| Streaming | Triggered by events on a stream; results written to a store or topic | Freshness in seconds without a user waiting: fraud features, alerting, session updates | Stream infrastructure, ordering and exactly-once concerns |
| Asynchronous | Request is queued; client polls or receives a callback | Slow jobs of seconds to minutes: document processing, image or video generation, long agent runs | Job state, retries and idempotency; a UX that tolerates waiting |
Decision questions:
- Is the input space enumerable and small enough to precompute? Then batch is cheapest and its serving is a key-value lookup.
- What is the value of freshness? Measure how the metric decays with staleness.
- What latency does the product tolerate? Under about 100 ms end to end rules out large models unless results are precomputed or cached.
- How bursty is traffic? Batch and async smooth the load and can use cheaper capacity.
Hybrids are the norm: precompute what you can (item embeddings, candidate sets) and do only the request-dependent part online; fall back to the batch result when the online path times out.
Follow-ups
- Your nightly batch scores cover users who never log in. How would you cut that waste?
- What changes when a batch feature moves online?
coreconceptMLE AIasked at Anthropic What is dynamic batching in a model server, why does it help on a GPU, and how do you set its parameters?
A model server receives single requests but a GPU is most efficient on batches. Dynamic batching holds incoming requests briefly, groups them into one tensor, runs one forward pass and splits the results.
Why it helps. A forward pass costs roughly \(t(b) = t_0 + t_1 b\): a fixed overhead (kernel launches, memory traffic for the weights) plus a per-item part that stays small until the GPU saturates. Throughput \(b / t(b)\) rises with \(b\) toward \(1/t_1\). At batch 1 a large GPU is mostly idle.
The two knobs.
- Maximum batch size: bounded by memory and by the point where \(t(b)\) itself exceeds the latency budget.
- Maximum wait (queue delay): how long the first request in a batch may wait for company.
Added latency per request is the wait to fill plus the longer batched pass. Under high load, batches fill immediately and the wait is not paid; under low load every request pays the full wait for nothing. So set the maximum wait to a small fraction of the SLO (often 1 to 10 ms) and let the batch size float.
Tuning. Measure \(t(b)\) for a range of batch sizes, then pick the largest \(b\) such that wait plus \(t(b)\) fits the p99 budget with headroom. Verify under a realistic load test, since arrival patterns determine actual batch sizes.
Complications. Variable-length inputs must be padded to the longest in the batch, so bucket by length or one long request slows the rest. Requests with different options cannot share a batch. For autoregressive generation, request-level batching is replaced by continuous batching at the token step.
Follow-ups
- At low traffic, dynamic batching makes latency worse. What do you do?
- How does padding waste change your choice of batch composition?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Mar 2026: Request batching for GPU inference (PracHub)
- Anthropic, Machine Learning Engineer, undated: Inference batching system for one GPU, up to 100 inputs per batch, synchronous callers (Aced (formerly Exponent))
seniorcodingMLE AIasked at Anthropic Implement a dynamic batcher with asyncio: requests are awaited individually, and the model is called on batches of up to N items or after at most T milliseconds.
import asyncio
class DynamicBatcher:
def __init__(self, infer_fn, max_batch=32, max_wait_ms=5, max_queue=1024):
self.infer_fn = infer_fn # list[x] -> list[y], blocking
self.max_batch = max_batch
self.max_wait = max_wait_ms / 1000
self.queue = asyncio.Queue(maxsize=max_queue)
async def submit(self, x):
fut = asyncio.get_running_loop().create_future()
try:
self.queue.put_nowait((x, fut)) # shed load when full
except asyncio.QueueFull:
raise RuntimeError("overloaded")
return await fut
async def run(self):
loop = asyncio.get_running_loop()
while True:
items = [await self.queue.get()]
deadline = loop.time() + self.max_wait
while len(items) < self.max_batch:
timeout = deadline - loop.time()
if timeout <= 0:
break
try:
items.append(await asyncio.wait_for(self.queue.get(), timeout))
except asyncio.TimeoutError:
break
xs, futs = zip(*items)
try:
ys = await loop.run_in_executor(None, self.infer_fn, list(xs))
for f, y in zip(futs, ys):
if not f.cancelled():
f.set_result(y)
except Exception as e:
for f in futs:
if not f.cancelled():
f.set_exception(e)Points an interviewer checks:
- The wait clock starts at the first request of the batch, so no request waits more than
max_waitin the batcher. - The blocking model call runs in an executor; calling it directly would freeze the event loop and stop new requests from being queued.
- One failed batch must fail only its own futures, and the loop must keep running.
- A bounded queue with rejection gives backpressure; an unbounded one turns overload into unbounded latency.
- A caller that timed out leaves a cancelled future; skip it instead of raising.
Extensions worth naming: bucketing by input length, per-request deadlines that drop expired items before inference, several worker loops for several GPUs, and metrics for batch size and queue time.
Follow-ups
- How would you drop requests whose client has already given up?
- What happens to latency if
infer_fnis called on the event loop thread?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Mar 2026: Request batching for GPU inference (PracHub)
- Anthropic, Machine Learning Engineer, undated: Inference batching system for one GPU, up to 100 inputs per batch, synchronous callers (Aced (formerly Exponent))
seniordesignMLE AIasked at Anthropic Design a serving platform for several hundred models, most of them rarely called, on a limited pool of GPUs.
One GPU per model is unaffordable when most models are idle, so the design is about sharing memory and absorbing cold starts.
Classify the models. A few hot models get dedicated, autoscaled replicas. The long tail shares a pool. If many models are fine-tunes of one base, serve them as adapters on a shared base model: the base stays in GPU memory and a small adapter is selected per request, which turns hundreds of models into one deployment.
Placement and loading for the tail.
- Each pool replica holds several models in GPU memory, bounded by a memory budget, with least-recently-used eviction.
- A router maps model id to the replicas that currently have it loaded and prefers those (affinity). On a miss it picks a replica with room, triggers a load and either queues the request or returns a retry-after.
- Make loads fast: weights on local NVMe or a memory-mapped cache, a weight-only format, models kept warm in host RAM when evicted from the GPU.
Isolation. A slow or heavy model must not starve its neighbours: per-model concurrency limits and queues, per-tenant rate limits, and memory accounting that includes peak activation memory, not only weights.
Control plane. A registry with each model’s version, resource profile and SLO class; rolling updates per model; per-model metrics for latency, load time, eviction count and cost attribution.
SLO classes. Promise low latency only for models that pay for reserved capacity; tail models get an explicit cold-start SLO. Predictive pre-loading from usage patterns (a customer’s working hours) removes most cold starts cheaply.
Risks to name: thrashing when the working set exceeds memory, fragmentation, and a popular new model evicting many small ones.
Follow-ups
- How do you detect and stop thrashing?
- What changes if the models are adapters over one shared base model?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Aug 2025: GPU-backed inference API for multiple models (PracHub)
seniordesignMLE AIasked at Anthropic Design the system that distributes model weight files of several hundred gigabytes to a fleet of GPU workers and activates a new version. Workers must never serve from a partial or corrupted copy, and a rollback must be fast.
Separate three things: the artifact, its distribution, and its activation. Most failures come from coupling them.
Artifact. Immutable and content-addressed. A version is a manifest: the version id, the list of chunks with size and SHA-256, the file format, and a signature. Chunks of 64 to 256 MB make downloads parallel and resumable. Publish chunks first and the manifest last, so a visible manifest never points at missing data.
Distribution.
- Tiers: origin object store, a cache per region or cluster, then local NVMe on each node. Peer-to-peer fetching between nodes in a cluster spreads the fan-out.
- The arithmetic decides the design. 500 GB over a dedicated 10 Gbit/s link takes about 400 seconds. 1,000 nodes pulling at once is 500 TB; through a shared 100 Gbit/s path that is about 11 hours, and it competes with serving traffic. So stage in the background with a bandwidth limit, in waves, from the nearest cache.
- The node agent fetches and verifies the manifest signature, checks free disk, downloads chunks with range requests into a staging directory, verifies every hash, and retries a bad chunk from another source. Progress is recorded per chunk, so a crash resumes instead of restarting.
Activation.
- When all chunks verify, fsync and rename the staging directory to
versions/<id>. Rename is atomic on one filesystem, so a version directory either exists complete or does not exist. The server only ever opens paths underversions/. - Which version serves is control-plane state, not “the newest directory on disk”. The agent reports “staged”; the controller flips a desired-version setting for a canary group, then in stages.
- Loading hundreds of gigabytes into GPU memory takes minutes, so a worker drains, loads, passes a health check with a known prompt and expected output, and only then rejoins. The router tracks the version each worker serves so a request is never split across versions.
- Rollback is the same flip in reverse. Keep the previous version on disk until the new one has soaked; garbage-collect by reference count after that.
Loading speed. Use a format that can be memory-mapped and read at disk speed without deserialising, shard files per GPU, and keep hot versions in the page cache on warm nodes.
Scale-up. New nodes with empty disks are the worst case: autoscaling during a traffic spike makes every new node pull at once. Keep a warm pool with the current version staged, or bake it into the node image, and admit new nodes to the cache in bounded numbers.
Security. Weights are among the most valuable assets the company has. Encrypt in transit and at rest, give nodes short-lived credentials scoped to the versions they should run, sign manifests, log every fetch, and alert on fetch volume that does not match a rollout.
Failure modes. Silent disk corruption after verification (re-verify on load or periodically), disk full mid-download (reserve before starting), version skew between router and worker, a manifest signed for the wrong build (the canary’s golden-output check catches it), and a rollback blocked because the old version was already deleted.
Metrics. Time to stage the fleet, time from node start to ready, verification failures, origin egress, and the share of nodes on the desired version.
Follow-ups
- Why should activation be a control-plane decision and not a property of what is on disk?
- A region’s cache is down during a rollout. What should the agents do?
- How would you cut the time from node start to first request for a model of this size?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Apr 2026: Distribute large model weight files to a GPU worker fleet (PracHub)
- Anthropic, Machine Learning Engineer, Feb 2026: Model downloader with versioning and integrity checks (PracHub)
- Anthropic, Software Engineer, May 2026: Distribute and activate model weights without exposing partial state (PracHub)
seniordesignMLE AI REasked at Anthropic You have a pool of eight GPUs and two kinds of inference work: a small model that runs on one GPU and serves many short requests, and a large model that needs all eight GPUs at once. Design the routing, batching and scheduling. How do you keep the large jobs from starving and the small ones fast?
Name the conflict. Small jobs can always start on any free GPU; the large job needs all eight free at the same moment. A scheduler that starts whatever fits will keep some GPU busy forever and the large job never runs. Everything else is refinement.
Scheduling between the two classes.
- Reservation with draining. When a large job reaches the head of the queue (or has waited past a threshold), stop admitting small jobs to the pool and let running ones finish.
- The drain is expensive. The wait is the maximum of the eight remaining run times, not the mean. For exponentially distributed remaining times with mean \(m\), that is \(m(1 + \tfrac12 + \dots + \tfrac18) \approx 2.7m\), and about \(13.7m\) GPU-seconds sit idle while the others finish. So keep small jobs short and bounded, and run large jobs back to back to amortise each switch.
- Backfill. During a drain, admit a small job only if its estimated run time ends before the drain does. This needs a run-time estimate: maximum output tokens gives an upper bound.
- Fairness. Account in GPU-seconds, not in job counts: one large job for a minute costs 480 GPU-seconds. Weighted fair sharing between the classes with ageing guarantees that neither waits without bound.
- Switching cost. If loading a model’s weights takes minutes, a switch costs more than the drain. Either keep both resident if memory allows, or schedule in windows (large jobs at fixed intervals, sized from their arrival rate and deadline).
- If the large model’s demand is steady, the honest answer may be a static split of the fleet, which this pool is too small for: say so and ask whether more hardware is an option.
Routing small requests across GPUs.
- One replica and one queue per GPU. Route to the replica with the least outstanding work (queued tokens), not the fewest requests; with many routers, sample two replicas and pick the lighter one.
- Session affinity helps when a replica holds a cached prefix for that conversation, and conflicts with load balance; break affinity above a queue-length threshold.
Batching.
- Dynamic batching: dispatch when the batch is full or the oldest request has waited \(d\) milliseconds. If a batch of \(b\) takes \(t_0 + t_1 b\), with \(t_0 = 20\) ms and \(t_1 = 2\) ms, throughput goes from 45 requests per second at \(b = 1\) to about 308 at \(b = 16\), while the compute latency goes from 22 to 52 ms plus the wait.
- Group requests of similar length so padding does not waste the batch. For token-by-token generation use continuous batching: requests join and leave the running batch at step boundaries.
- Set \(d\) from the latency budget, not from throughput: at low load a long wait buys nothing.
Overload and failure. Bounded queues, deadlines carried with each request, and rejection at admission when the estimated wait exceeds the deadline; a request that will miss its deadline should not consume a GPU. On a GPU failure the large model cannot run at all, so its queue needs a policy (fail fast, or run a degraded configuration), while small traffic re-routes to seven replicas.
Heterogeneous backends. With CPU and several GPU types, route on a per-backend cost model: estimated latency and cost for this request size on each backend, capability constraints (memory, supported model), and current queue. Send small, latency-tolerant requests to the cheap backend first.
Metrics. Queue wait and total latency at p50 and p99 by class, GPU-seconds idle during drains, utilisation, deadline misses and rejection rate.
Follow-ups
- Small-model traffic is bursty. How do you stop a burst from delaying a large job that has already waited ten minutes?
- Where does your run-time estimate come from, and what happens when it is wrong?
- Why is join-shortest-queue by request count a poor rule for generation workloads?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Sep 2026: Route and batch inference across eight GPUs (PracHub)
- Anthropic, Machine Learning Engineer, Aug 2026: Schedule large-model and small-model inference on an eight-GPU pool (PracHub)
- Anthropic, Software Engineer, Aug 2026: Schedule one-GPU and eight-GPU jobs fairly (PracHub)
- Anthropic, Machine Learning Engineer, Sep 2025: Routing and scheduling layer for heterogeneous GPU and CPU backends (PracHub)
Capacity, autoscaling and GPU cost efficiency 14% of postings
- Choose a scaling signal for GPU inference and explain why CPU and GPU utilisation mislead
- Break down a cold start and name a mitigation for each part
- Compute replicas needed for a peak load, an SLO and a redundancy requirement
- Compare time-slicing, process-level sharing and hardware partitioning of a GPU
seniorconceptMLE AI How do you autoscale a GPU inference service? Which signal do you scale on, and what makes it harder than scaling a stateless web service?
Signals.
- CPU utilisation, the default for web services, says little when the GPU is the bottleneck.
- GPU utilisation is tempting and misleading: it reports the share of time any kernel was running, so it reads near 100% with a single stream and does not show how much headroom batching still offers.
- Concurrency or in-flight requests per replica against a target derived from a load test is the most direct signal.
- Queue depth or queue wait time leads latency and is the natural signal for asynchronous workloads.
- For LLM serving: running plus waiting sequences, or tokens in flight, relative to the KV cache capacity.
- Latency itself is a lagging signal and noisy; use it as an alarm, not as the control input.
Why it is harder.
- Cold start is minutes, not seconds: provisioning a GPU node, pulling a multi-gigabyte image, loading weights into memory, warming up. By the time capacity arrives the burst may be over, or the queue long.
- Capacity is lumpy and scarce: GPUs come in whole units, cost a lot when idle, and may not be available on demand.
- Scale-down is risky: long-running streams must drain first.
Mitigations.
- Keep a minimum number of warm replicas and headroom sized to the fastest realistic ramp.
- Shorten the cold start: pre-pulled or lazily loaded images, weights on local disk or a shared cache, a pool of warm nodes.
- Scale up fast and down slowly, with a stabilisation window to avoid flapping.
- Predictive or scheduled scaling for daily patterns.
- Absorb bursts with a bounded queue, and shed or degrade (smaller model, shorter output) beyond it.
- Scale to zero only for workloads that tolerate a cold start.
Follow-ups
- Traffic doubles in 30 seconds and a new replica takes 4 minutes. What happens, and what do you design for it?
- Why is GPU utilisation at 100% not a reason to scale up?
corederivationMLE AI Peak traffic is 1 500 requests per second with a p99 latency SLO. How many GPU replicas do you provision? Show the calculation.
1. Per-replica capacity at the SLO. From a load test with realistic inputs, find the highest arrival rate at which one replica still meets the p99 target. Say 200 requests per second. This is not the maximum throughput: at maximum throughput the queue, and so the latency, is unbounded.
2. Target utilisation. Run below that capacity to absorb bursts and the lag of autoscaling. With a 70% target, plan for \(0.7 \times 200 = 140\) requests per second per replica.
3. Replicas for peak.
\[N = \left\lceil \frac{1500}{140} \right\rceil = 11.\]
4. Redundancy. Add capacity so that losing a replica, or a whole zone if the service spans zones, still leaves enough. With N+1: 12 replicas. Across three zones with tolerance for losing one: each zone must hold half the required capacity, so \(3 \times \lceil 11 / 2 \rceil = 18\).
5. Rollouts. During a rolling update some replicas are unavailable or warming; either surge extra replicas or include the reduction in the plan.
6. Cost. Multiply by the hourly price to get the peak cost, then apply autoscaling to follow the daily curve. Average utilisation over the day, not peak sizing, drives the bill. Cost per thousand requests is hourly price times replicas divided by requests served in the hour.
Sanity checks.
- Is the peak a measured peak (the busiest minute, not the daily mean), with growth included?
- Does per-replica capacity hold when several replicas share upstream dependencies?
- What is the largest input the system admits, and was it in the load test?
- What happens above the plan: is there load shedding, or does latency for everyone degrade?
An interviewer wants the structure (capacity at SLO, headroom, redundancy) more than the numbers.
Follow-ups
- Why not plan to 100% of the measured capacity?
- How does the answer change if requests vary by a factor of 50 in cost?
seniortrade-offMLE AI Your GPU inference fleet averages 25% utilisation. What are the ways to raise it, and what does each cost?
Low average utilisation has three sources: peak-sized capacity sitting idle off-peak, requests that use little of each GPU, and many small services each holding a whole device.
Follow the load.
- Autoscale on concurrency or queue depth, with faster cold starts so that less headroom is needed.
- Fill the troughs: run batch and offline inference, evaluation and embedding jobs on the idle serving fleet at low priority, preempted when online traffic returns.
Use more of each GPU.
- Batching (dynamic or continuous) and higher concurrency per replica, up to the latency knee.
- Right-size the hardware: a smaller or older GPU model for small models; a large-memory device only where the model needs it.
- Make the model cheaper: quantization, compilation, distillation or a cascade in which a small model handles easy requests.
Share devices among services.
- Time-slicing: several processes take turns. Simple; no memory or fault isolation, and latency interference.
- Process-level sharing (such as NVIDIA MPS): processes run concurrently on one device with better throughput than time-slicing; limited isolation.
- Hardware partitioning (such as NVIDIA MIG on supported devices): fixed slices with dedicated memory and compute. Strong isolation; coarse, static sizes.
- One multi-model server per GPU: an application-level scheduler loads several models and batches across them. Most efficient, most engineering.
Buy capacity differently. Committed capacity for the baseline, on-demand for peaks, spot for preemptible batch work.
Costs to state: every sharing technique trades isolation and tail latency for utilisation; consolidation increases blast radius; and aggressive scale-down raises cold-start risk. Set the target by SLO class. Report cost per request, since utilisation is only a means.
Follow-ups
- Which sharing mechanism would you use for two latency-sensitive models from different teams?
- What is the risk of running batch jobs on the serving fleet?
On-device / edge / embedded ML 12% of postings
- List the constraints of phones and embedded devices and what each does to model design
- Decide what runs on the device and what in the cloud, and design the fallback between them
- Pick a compression strategy to meet a size and latency target
coreconceptMLE AI What changes when a model has to run on a phone or an embedded device instead of a server?
The constraints are harder and you do not control the hardware.
- Memory. The model shares RAM with the operating system and other apps; exceeding a budget gets the app killed. Budgets of tens to a few hundred megabytes are normal for phones, kilobytes to megabytes for microcontrollers.
- Storage and download size. The model ships in the app or is downloaded on first use. Size affects install rates and update cost.
- Compute heterogeneity. CPUs, GPUs and neural accelerators differ by device and vendor. An operator that the accelerator does not support falls back to the CPU and can erase the speedup. You must test on a matrix of real devices, including old ones.
- Power and heat. Sustained inference drains the battery and triggers thermal throttling, so performance after a minute is lower than in a short benchmark.
- Latency without a network. No round trip, which is a benefit; but also no elastic capacity.
- Updates. A model update is an app release or a managed download; old versions stay in the field for months. You cannot roll back instantly.
- Observability. Little telemetry, constrained by privacy and bandwidth.
What you gain: privacy, since data stays on the device; offline operation; no per-request serving cost; and low, predictable latency.
Consequences for design:
- Architectures chosen for the target’s supported operators, not only for accuracy.
- Quantization (usually 8-bit integer) as the default, with distillation or pruning to reach the size.
- The whole pipeline on the device, including preprocessing, in the same framework (Core ML, LiteRT, ExecuTorch, ONNX Runtime Mobile).
- Tiered models selected by device capability, and a cloud fallback where the product allows.
- Evaluation on device: accuracy after conversion, latency percentiles, peak memory, energy per inference.
Follow-ups
- Why does one unsupported operator matter so much on a neural accelerator?
- How would you roll out a new model to devices safely?
seniordesignMLE AI Design a feature that runs a model on the phone when it can and in the cloud when it must. How do you split the work and keep the two consistent?
Decide what runs where. Put on the device what must be fast, private or offline and fits the budget: wake-word or trigger detection, classification, small-vocabulary speech recognition, embedding, a small language model for short tasks. Use the cloud for what needs a large model, fresh or global data, or heavy retrieval.
Common split patterns.
- Cascade: a small on-device model handles easy cases and estimates its own confidence; uncertain or complex requests go to the cloud. Cost and latency fall with the share handled locally.
- Split pipeline: the device does perception and feature extraction and sends compact features, not raw audio or images, which helps privacy and bandwidth.
- Cloud with local fallback: best quality when online, a degraded local answer when offline or slow.
Routing policy. Decide per request from confidence, input complexity, connectivity, battery and thermal state, and user privacy settings. Make the policy remotely configurable so thresholds can be tuned without an app release.
Consistency. Users notice when the same request gives different answers by network state.
- Share preprocessing and postprocessing code between device and server.
- Train the small model by distillation from the large one, and measure their agreement as a metric.
- Version the pair; a server model update can break the cascade’s thresholds.
Delivery and fleet management. Models delivered as downloadable assets, versioned and selected by device tier; staged rollout with on-device health metrics (latency, crashes, fallback rate); the ability to disable the local path remotely.
Privacy and security. State what leaves the device and obtain consent. Model files on a device can be extracted, so do not put secrets in them.
Evaluation. Quality per tier and per path, share of requests served locally, latency and energy on a device matrix, and an end-to-end metric across the routing policy.
Follow-ups
- How does the small model know when it is wrong?
- What telemetry would you collect without sending user content?
seniortrade-offMLE RE You must make a model four times smaller and three times faster for an edge target with at most a one-point accuracy loss. Which compression techniques do you combine, and in what order?
The techniques are complementary, and the order matters because each changes what the next can do.
Measure the starting point on the target. Latency by layer, peak memory and which operators run on the accelerator. Often a few layers or an unsupported operator dominate, and fixing that is cheaper than compressing everything.
Change the architecture first. A smaller or more efficient architecture (fewer layers or channels, lower input resolution, efficient blocks that the target’s accelerator supports) trained by distillation from the original model. This gives the largest and most reliable gain in both size and speed, because it reduces the actual operations, and distillation recovers much of the accuracy a small model would lose if trained from scratch.
Quantise. 8-bit integer quantization gives about 4 times smaller weights and a substantial speedup on hardware with integer kernels. Try post-training quantization with calibration; if the loss is too large, fine-tune with quantization-aware training, ideally with the distillation loss still on.
Prune only if it pays on this hardware. Unstructured pruning makes weights sparse, which shrinks the compressed file but does not speed up dense kernels. Structured pruning (removing channels, heads or layers) gives real speedups and is closer to choosing a smaller architecture.
Compile for the target with the vendor runtime, and re-measure.
Why this order: architecture decisions determine operator support and the baseline; quantization is applied last because it is hardware-specific and any later weight change would undo it.
Accounting: the 4 times size target is met by 8-bit quantization alone if the model was 32-bit; the 3 times latency target usually needs architecture change plus quantization. Track accuracy after every step on the task metric and on the slices that matter, since compression errors concentrate on rare classes.
Follow-ups
- Why does unstructured sparsity rarely make inference faster?
- How would you set up distillation and quantization-aware training together?
GPU programming and kernel-level optimization 12% of postings
- Explain how work reaches a GPU and why many small operations are slow
- Time GPU code correctly and read a profiler trace
- Say when a custom kernel is justified and what to try before writing one
coreconceptMLE RE Explain how a deep learning framework’s operations actually execute on a GPU, and why a model made of many small operations is slow even though each one is trivial.
The execution model. A GPU runs kernels: one function executed by thousands of lightweight threads in parallel, each handling some elements of the data. The CPU is the conductor. For every tensor operation the framework, on the CPU, checks types and shapes, picks a kernel, allocates the output and enqueues the launch. The call returns immediately; the GPU executes queued kernels asynchronously, in order. The CPU blocks only when it needs a value back, for example to print it or branch on it.
Memory. The device has its own high-bandwidth memory, with small fast memories near the compute units. Host memory is reached over a much slower bus, so host-device copies are expensive, and page-locked host memory makes them faster and asynchronous.
Why small operations are slow.
- Per-operation overhead. Framework dispatch plus kernel launch costs on the order of microseconds to tens of microseconds on the CPU, regardless of tensor size. A model doing thousands of tiny operations per step is limited by the CPU, and the GPU idles.
- Memory traffic. Each elementwise operation reads its inputs from device memory and writes its output back. A chain of five operations makes five passes over memory where one fused kernel would make one. Most simple operations are limited by memory bandwidth, not arithmetic.
- Poor parallelism. A small tensor cannot occupy thousands of threads.
What follows.
- Batch, so that each launch does more work.
- Vectorise: replace Python loops over elements with one operation on a larger tensor.
- Fuse: graph compilers combine adjacent operations into one kernel and remove intermediate tensors.
- Avoid round trips to the host inside the hot path.
- Use the library’s composite operations (attention, normalisation, convolution), which are implemented as single optimised kernels.
The mental model: the CPU issues instructions, the GPU moves and transforms large blocks of memory, and performance comes from fewer, larger, fused passes.
Follow-ups
- What does calling
.item()in a training loop do to this pipeline? - Why can a model be CPU-bound while running on a GPU?
seniordebuggingMLE RE How do you correctly measure and profile the GPU part of an inference or training step? What mistakes make the numbers wrong?
The basic mistake: timing asynchronous code. GPU calls return before the work is done, so wall-clock timing around a forward pass measures only the time to enqueue it. The cost then appears at whichever later line forces a wait, often a .cpu() or a print, and that line gets blamed. Synchronise before reading the clock:
import time, torch
def timed(fn, *args, warmup=10, iters=50):
for _ in range(warmup):
fn(*args)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(iters):
fn(*args)
torch.cuda.synchronize()
return (time.perf_counter() - t0) / itersOther mistakes.
- No warm-up: the first calls include memory-pool growth, lazy initialisation, kernel selection and, with a compiler, compilation.
- Measuring one shape when production shapes vary.
- Including data loading or host-device transfer without meaning to, or excluding it when it is the real bottleneck.
- Benchmarking with gradients enabled for inference, or in training mode.
- Comparing runs on a GPU shared with other jobs, or one that is thermally throttled.
Profiling.
- Start with a framework profiler that records CPU and GPU activity together (
torch.profiler), and look at the table sorted by GPU time and by CPU time, and at the timeline. - Read the timeline for gaps. GPU idle while the CPU is busy means the CPU side (dispatch, data loading, Python) is the bottleneck. A solid GPU timeline means the kernels themselves are.
- Look for many short kernels (overhead-bound), for copies between host and device, and for synchronisation points.
- Check memory: peak allocated against reserved, and allocation events inside the loop.
- Only if one kernel dominates, go deeper with vendor tools that show per-kernel hardware behaviour.
Report results with the batch size, shapes, precision, hardware and software versions, as mean and percentiles over many iterations.
Follow-ups
- The profiler says
.cpu()takes 80% of the step. What is really happening? - How would you tell an overhead-bound model from a bandwidth-bound one?
stafftrade-offMLE RE When is it justified to write a custom GPU kernel or operator for a model, and what do you try first?
Rarely, and only after measurement shows that one operation dominates and that nothing existing serves it. A custom kernel is code with a high maintenance cost: it is tied to hardware and library versions, needs its own correctness and numerical tests, and must be kept working through every upgrade.
Try first, in order of cost.
- Do less work. Shorter sequences, smaller batch padding, caching, removing redundant computation. Algorithmic savings beat low-level tuning.
- Use the library’s optimised composite operations instead of hand-assembling them from primitives. Fused attention, normalisation and convolution kernels already exist.
- Reduce precision and fix memory layout: mixed precision, a channel layout the kernels prefer, contiguous tensors.
- Let a compiler fuse. Graph compilation (
torch.compile, XLA, a vendor runtime) removes dispatch overhead and fuses elementwise chains. This captures much of what a hand-written fused kernel would give. - Vectorise remaining Python-level loops.
When a custom kernel is justified.
- Profiling shows one operation taking a large share of the step after the steps above.
- The operation is not expressible efficiently with existing ones: a new attention variant, a sparse or irregular access pattern, a custom sampling or decoding step.
- The gain is multiplied by scale: a hot path in a large training run or a high-traffic service, where even a modest percentage pays for the engineering.
How, with increasing cost. A kernel-level domain-specific language embedded in Python that compiles to GPU code; then a native extension written against the vendor toolkit. Whichever route: test against a slow reference implementation over many shapes and data types, check gradients numerically if it is differentiable, benchmark against the baseline on real shapes, and keep the reference as a fallback.
In an interview the point to make is the decision process and the cost, not the code. Be honest about how much of this you have done yourself.
Follow-ups
- How do you test a custom differentiable operator for correctness?
- Your kernel is twice as fast on one GPU model and slower on another. What now?
LLM inference engines (vLLM, TGI, TensorRT-LLM, llama.cpp) 11% of postings
- Explain prefill versus decode and why time to first token and tokens per second are separate metrics
- Describe continuous batching and block-based KV cache management
- Estimate how many concurrent sequences fit on a GPU from weights and KV cache memory
- Explain speculative decoding and when it helps or hurts
- Compare the main open inference engines and a hosted API for a given workload
seniorconceptMLE AI REasked at Amazon How does an LLM inference engine serve many concurrent requests efficiently? Explain prefill and decode, continuous batching and how the KV cache is managed.
Two phases. Prefill processes the whole prompt in one parallel pass and fills the KV cache; its time grows with prompt length and determines time to first token (TTFT). Decode then produces one token per forward pass per sequence, reading the cache; it is limited mostly by memory bandwidth and determines tokens per second.
Continuous batching. With request-level batching a batch runs until its longest sequence finishes, so short answers wait and new requests queue. Continuous (iteration level) batching re-forms the batch at every decode step: finished sequences leave, and waiting requests join after their prefill. GPU slots are never held by finished sequences, which raises throughput several times on mixed-length traffic.
Scheduling prefill against decode. A long prompt’s prefill can stall every running stream for hundreds of milliseconds. Engines split prefill into chunks interleaved with decode steps, trading a little TTFT for smooth streaming.
KV cache management. Each sequence’s cache grows by one token per step and its final length is unknown. Reserving the maximum per sequence wastes most of the memory. Engines allocate the cache in fixed-size blocks on demand, in the manner of virtual-memory pages, which removes fragmentation and lets sequences with a common prefix share blocks. That sharing is also what makes prefix caching of a common system prompt cheap.
What limits concurrency. After the weights, the remaining GPU memory is KV cache, so the number of concurrent tokens is fixed. Admission control must queue or reject beyond that, or the engine preempts sequences and recomputes them.
Metrics. TTFT, inter-token latency, end-to-end latency, output tokens per second per GPU, and queue time, each at p50 and p99 and as a function of load.
Follow-ups
- Why is decode bound by memory bandwidth and prefill by compute?
- Throughput is high but streaming stutters. Which scheduling decision is responsible?
Reported in interviews (candidate reports on third-party sites, not verified)
- Amazon, Software Engineer, Sep 2026: How a decoder-only transformer produces next-token probabilities and how an inference engine serves it efficiently (PracHub)
seniorderivationMLE AI Estimate how many concurrent requests one GPU can serve for an open-weights LLM. Walk through the memory arithmetic.
GPU memory is spent on weights, KV cache and working memory. Concurrency is what the KV cache budget allows.
Weights. Parameters times bytes per parameter. A model with \(8 \times 10^9\) parameters takes 16 GB in 16-bit floats, 8 GB at 8 bits, about 4 to 5 GB at 4 bits.
KV cache per token. Each layer stores a key and a value vector per token:
\[\text{bytes per token} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_{\text{head}} \cdot b,\]
with \(L\) layers, \(n_{\text{kv}}\) key-value heads, head dimension \(d_{\text{head}}\) and \(b\) bytes per number. For \(L = 32\), \(n_{\text{kv}} d_{\text{head}} = 4096\) and 16-bit floats: \(2 \cdot 32 \cdot 4096 \cdot 2 \approx 0.5\) MB per token. With grouped-query attention using 8 KV heads of dimension 128 it is \(2 \cdot 32 \cdot 1024 \cdot 2 \approx 0.13\) MB.
Budget. On a 24 GB card with 16 GB of weights and about 1 GB reserved for activations and fragmentation, roughly 7 GB remains. At 0.13 MB per token that is about 54 000 cached tokens in total.
Concurrency. Divide by the average tokens a live sequence holds (prompt plus output so far). At 2 000 tokens per sequence: about 27 concurrent sequences. At 16 000 tokens: about 3. Context length, not request count, is what consumes capacity.
From concurrency to throughput. If each sequence decodes at \(r\) tokens per second in a batch of that size, the GPU yields \(27 r\) output tokens per second; divide by output tokens per request for requests per second. Measure \(r\), since it falls as the batch grows.
Levers, in order: quantise the weights to free memory for cache, share common prefixes, cap context length, use a larger-memory GPU. Check the arithmetic against the engine’s reported cache capacity.
Follow-ups
- What happens when a burst of long-context requests arrives?
- How does prefix sharing change the estimate when every request has the same 3 000-token system prompt?
seniorconceptMLE RE What is speculative decoding? Why does it not change the output distribution, and when does it fail to help?
Decoding is slow because each token needs a full pass through a large model, and the passes are sequential. Speculative decoding uses a small, fast draft model to guess several tokens ahead and the large target model to check all of them in one parallel pass.
Procedure.
- The draft model \(q\) generates \(\gamma\) tokens autoregressively.
- The target model \(p\) scores the prefix plus those \(\gamma\) tokens in a single forward pass, which yields \(p\)’s distribution at every position.
- Accept each drafted token \(x\) in order with probability \(\min(1, p(x) / q(x))\). At the first rejection, resample that position from the normalised residual \(\max(0, p - q)\) and discard the rest.
- If all are accepted, sample one extra token from \(p\) for free.
Why the distribution is unchanged. The accept-or-resample rule is a rejection sampling scheme whose output at each position is distributed exactly as \(p\). With greedy decoding it reduces to “accept while the draft’s token equals the target’s argmax”.
Speedup. If each token is accepted with probability \(\alpha\), the expected number of tokens produced per target pass is \((1 - \alpha^{\gamma + 1}) / (1 - \alpha)\). The gain depends on \(\alpha\) and on how cheap the draft is relative to the target.
When it does not help.
- Low acceptance: the draft is too weak for the domain, or sampling temperature is high.
- The draft is not much cheaper than the target.
- A throughput-bound server: verification passes do extra work for rejected tokens, so under heavy batching total tokens per second can fall even though single-request latency improves. It is a latency technique.
- Extra memory for the draft model and its cache.
Variants replace the draft model with early-exit heads, n-gram or retrieval lookups (useful when the output copies the input, as in code edits), or multiple candidates.
Follow-ups
- Why does a higher sampling temperature lower the acceptance rate?
- How would you choose the number of drafted tokens?
seniortrade-offMLE AI You need to serve an open-weights LLM. How do you choose between a hosted API, a general-purpose engine such as vLLM, a compiled engine such as TensorRT-LLM, and llama.cpp?
Start from the workload: traffic volume and burstiness, latency target, model customisation, data constraints and who will operate it.
Hosted API or managed endpoint. No operations, pay per token or per hour, scale handled for you. Right for low or unpredictable volume and for standard models. Limits: per-token cost at high steady volume, less control over versions, quantization and latency, and data leaves your environment.
General-purpose GPU engine (vLLM, SGLang, Hugging Face TGI and similar). Continuous batching, block-based KV cache, prefix caching, an OpenAI-compatible server, broad and fast model support, adapters and structured-output features. The default for self-hosting on GPUs: good throughput with little build effort.
Compiled, vendor-specific engine (TensorRT-LLM, usually behind Triton). The model is compiled into an engine for a specific GPU type and settings. Can give the best latency and throughput on that hardware, at the price of a build step per model and GPU, slower support for new architectures and a harder debugging story. Worth it at large scale for a stable model.
CPU and edge runtime (llama.cpp and wrappers, with GGUF quantised weights). Runs on CPUs, laptops and Apple silicon with small memory. Designed for one or a few users, not for high-concurrency serving.
How to decide in practice:
- Benchmark candidates on your own prompt and output length distribution at your target concurrency; published numbers rarely transfer.
- Compare cost per million output tokens at the latency SLO, including idle capacity.
- Weigh operational features: metrics, graceful reload, adapter loading, structured output, version pinning.
This field moves quickly and project status changes, so check current documentation before committing.
Follow-ups
- At what volume does self-hosting beat a per-token API?
- What would make you move from a general engine to a compiled one?
Quantization and efficient inference 10% of postings
- Write the affine quantization mapping and compute scale and zero point
- Compare dynamic and static post-training quantization with quantization-aware training
- Explain per-channel quantization and activation calibration
- Say what 8-bit and 4-bit weight quantization do to an LLM and how to check the damage
coreconceptMLE AI REasked at Nvidia Explain quantization for inference. What is the mapping, and how do post-training quantization and quantization-aware training differ?
Quantization stores and computes with low-precision integers instead of 32-bit floats. The affine mapping from a real value \(x\) to an integer \(q\) in \([q_{\min}, q_{\max}]\):
\[q = \operatorname{clip}\big(\operatorname{round}(x / s) + z,\ q_{\min}, q_{\max}\big), \qquad \hat x = s\,(q - z),\]
with scale \(s = (x_{\max} - x_{\min}) / (q_{\max} - q_{\min})\) and zero point \(z\), the integer that represents real zero. Inside the range the rounding error is at most \(s/2\); outside it, values are clipped. Weights usually use the symmetric form (\(z = 0\)) with a separate scale per output channel, because channels differ widely in range.
Why it helps. 8-bit integers are 4 times smaller than 32-bit floats, which cuts memory, download size and memory traffic, and integer arithmetic is faster on hardware with kernels for it.
Post-training quantization (PTQ). No retraining.
- Dynamic: weights are quantised ahead of time; activation ranges are computed at run time. Simple, good for linear and recurrent layers on CPU.
- Static: activation ranges are fixed in advance from a calibration set of a few hundred representative inputs, using min-max, a percentile, or the range that minimises error. Fully integer inference.
Quantization-aware training (QAT). Insert fake-quantization operations in the forward pass during fine-tuning, so the weights adapt to rounding; gradients pass through the rounding with the straight-through estimator. It recovers most of the accuracy PTQ loses, at the cost of a training run.
Choosing. Try PTQ first and measure on the real task. Use QAT when PTQ loses too much: small or already compact models, low bit widths, or layers with wide activation ranges. Keep sensitive layers (often the first and last) at higher precision.
Follow-ups
- Why must the zero point be an exact integer?
- Your calibration set does not cover a rare input type. What happens at inference?
Reported in interviews (candidate reports on third-party sites, not verified)
- Nvidia, Software Engineer, Sep 2026: Convert 32-bit float tensors to int8: scale, zero point, clipping and outliers (PracHub)
corecodingMLE REasked at Nvidia Implement uniform affine quantization and dequantization of a tensor in NumPy, for both the asymmetric and the symmetric case.
import numpy as np
def quant_params(x, bits=8, symmetric=False):
if symmetric: # signed, zero point 0
qmin, qmax = -(2 ** (bits - 1) - 1), 2 ** (bits - 1) - 1
scale = float(np.abs(x).max()) / qmax
zero = 0
else: # unsigned, range includes 0
qmin, qmax = 0, 2 ** bits - 1
lo, hi = min(float(x.min()), 0.0), max(float(x.max()), 0.0)
scale = (hi - lo) / (qmax - qmin)
zero = int(round(qmin - lo / scale)) if scale > 0 else 0
return (scale if scale > 0 else 1.0), zero, qmin, qmax
def quantize(x, scale, zero, qmin, qmax):
return np.clip(np.round(x / scale) + zero, qmin, qmax).astype(np.int32)
def dequantize(q, scale, zero):
return scale * (q.astype(np.float32) - zero)Checks to state:
- Round trip error:
np.abs(x - dequantize(quantize(x, ...), ...)).max()is at mostscale / 2for values inside the range. - The asymmetric range is widened to include 0, so that zero (padding, ReLU outputs) is represented exactly.
- The symmetric range drops the most negative code so that it is symmetric about zero.
- A constant tensor gives scale 0; guard against the division.
Follow-ups an interviewer may ask for:
- Per-channel scales for a weight of shape
[out, in]: compute the maximum overaxis=1and broadcast, which removes most of the error when rows differ in magnitude. - Clipping the range to a percentile instead of min and max: outliers otherwise stretch the scale and waste resolution on values that rarely occur. This trades clipping error for rounding error.
- Integer-only inference: the product of two quantised tensors has scale \(s_1 s_2\), and the rescaling to the output scale is done with a fixed-point multiplier and a shift.
Follow-ups
- Why does one outlier weight hurt min-max quantization so much?
- How many distinct values can a 4-bit symmetric quantizer represent, and what does that imply for the scale?
Reported in interviews (candidate reports on third-party sites, not verified)
- Nvidia, Software Engineer, Sep 2026: Convert 32-bit float tensors to int8: scale, zero point, clipping and outliers (PracHub)
seniortrade-offMLE AI RE What does quantizing a large language model to 8 or 4 bits buy and cost? How would you decide which precision to deploy?
What it buys. LLM quantization is mostly weight-only: weights are stored in few bits and activations stay in 16-bit floats. The gains are memory (16-bit to 4-bit is about a 4 times smaller model, so it fits on a smaller GPU or leaves room for more KV cache and concurrency) and, because decoding is limited by memory bandwidth, often speed. The speed gain depends on the engine having efficient kernels for the format; without them a low-bit model can be slower than the 16-bit one.
What it costs. Quality loss that is uneven:
- 8-bit is close to lossless for most models.
- 4-bit with a calibration-based method is usually a small loss; naive rounding to 4 bits is noticeably worse.
- Below 4 bits quality falls quickly.
- Smaller models tolerate less than larger ones, so a larger model at 4 bits often beats a smaller one at 16 bits for the same memory.
- Damage concentrates in harder behaviours: long reasoning chains, exact numbers, rare languages, structured output. Perplexity can look fine while these regress.
Methods, by idea. Round-to-nearest with per-channel or per-group scales is the baseline. Calibration-based methods use a few hundred samples to reduce the layer’s output error instead of the weight error: GPTQ adjusts the remaining weights to compensate for each rounding, and AWQ rescales channels by activation magnitude before rounding. Mixed precision keeps sensitive layers at more bits.
Deciding.
- Fix the hardware and the memory you need for cache at target concurrency.
- Produce candidates (16-bit, 8-bit, 4-bit, and a smaller model) and run your task evaluation and a regression set, not only perplexity.
- Benchmark latency and throughput in the engine you will deploy.
- Pick the cheapest candidate that passes the quality gate, and re-qualify on every model update.
Treat a quantised model as a new model version in the registry.
Follow-ups
- Perplexity is unchanged after quantization but users report worse answers. Where do you look?
- Why are activations and the KV cache usually left at higher precision?
Inference runtimes and compilers (ONNX, TensorRT, CoreML) 6% of postings
- Describe what exporting to ONNX captures and what tracing loses
- Explain what an optimising runtime such as TensorRT does to a graph and why the result is not portable
- Verify an exported model numerically and handle unsupported operators and dynamic shapes
seniorconceptMLE AI What happens when you export a PyTorch model to ONNX and run it with an optimising runtime such as TensorRT? What are the usual pitfalls?
Export. The model’s computation is captured as a static graph of standard operators (an ONNX opset). Capture is done by tracing a run with example inputs or by a compiler front end that analyses the program. Tracing records the operations that happened for that input, so data-dependent Python control flow is frozen to the branch taken, and shapes become constants unless declared dynamic.
Optimising runtime. A runtime such as ONNX Runtime, TensorRT, OpenVINO or Core ML takes the graph and
- folds constants and removes dead nodes,
- fuses adjacent operations (convolution, normalisation and activation into one kernel),
- chooses precision per layer (32-bit, 16-bit, 8-bit with calibration),
- selects the fastest kernel implementation for the target hardware, and plans memory.
TensorRT does this at build time for a specific GPU model, TensorRT version and input shape profile, and the resulting engine is not portable across them.
Pitfalls.
- Unsupported operators: newer or custom operations have no ONNX or runtime equivalent. Options: rewrite with supported operations, raise the opset, write a plugin, or let the runtime fall back to another provider for that subgraph, which costs transfers.
- Dynamic shapes: batch and sequence dimensions must be declared; each shape profile constrains optimisation, and shapes outside the profile fail.
- Frozen control flow: loops and branches traced for one input.
- Numerical differences: 16-bit overflow in normalisation or attention, different operator semantics (resize modes, integer division, padding).
- Pre- and postprocessing left behind in Python, which reintroduces skew and a CPU bottleneck.
- Build time and versioning: engines must be rebuilt for each GPU type and runtime upgrade, which belongs in CI.
Always verify. Compare outputs with the original model on real inputs, within a tolerance, and rerun the task evaluation. Then benchmark; a compiled graph is not automatically faster than a well-configured framework runtime for transformer models.
Follow-ups
- Your model has an if statement that depends on the input’s content. What does the exported graph do?
- When would you not bother with ONNX at all?
seniordebuggingMLE AI After exporting a model to a compiled runtime, accuracy on your evaluation set drops by two points. How do you find the cause?
Treat it as a differential debugging problem: same inputs through both paths, and find the first place they diverge.
- Reproduce on a handful of inputs. Pick examples whose predictions changed. Feed the same tensors to both models to separate model differences from preprocessing differences.
- Check preprocessing parity first. Most “export” regressions live outside the graph: a different image resize or interpolation mode, colour channel order, normalisation constants, tokenizer version or truncation, padding side. Compare the input tensors of both pipelines numerically.
- Compare at full precision. Build the engine in 32-bit floats. If the outputs now match, the cause is reduced precision.
- 16-bit: overflow or loss of small values in normalisation, softmax or large activations. Keep the offending layers at 32 bits.
- 8-bit: unrepresentative calibration data, a layer with a wide range, or activation outliers. Recalibrate with representative data, use per-channel scales, or exclude sensitive layers.
- If full precision also differs, bisect the graph. Expose intermediate outputs in both models and find the first layer where the difference exceeds tolerance. Usual suspects: an operator with different semantics (resize, rounding, integer division), a traced branch frozen to the wrong path, dynamic shapes handled differently, or dropout and normalisation layers exported in training mode.
- Check evaluation conditions. Same batch size and padding, since batch-dependent behaviour changes results, and the same postprocessing and thresholds.
Prevent recurrence with an export test in CI: a fixed set of inputs, a maximum output difference, and a task-metric gate, run for every model and runtime version.
Follow-ups
- Outputs match within 1e-3 on random inputs but the metric still drops. Why might that be?
- Which layers would you keep at higher precision first?