Batch LLM Inference with Heterogeneous Hardware Routing
Medium · ML System Design · Member of Technical Staff, ML Systems · Onsite
Prompt
Architect an asynchronous batch LLM inference system that schedules work across heterogeneous accelerator clusters—including older-generation GPUs whose memory-bandwidth-per-dollar makes them attractive for autoregressive token decoding.
Your design must operate under four real-world constraints: - Batch submissions are non-interactive, yet carry explicit completion deadlines and per-tenant priority tiers. - Accelerator pools vary substantially in device RAM, memory bandwidth, compute throughput, supported numeric precisions, and node failure rates. - Shipping intermediate attention state (KV cache) between disaggregated stages consumes substantial datacenter network bandwidth. - Giant batch submissions from a single customer must never starve competing tenants, and routing must adapt to live empirical hardware performance rather than static datasheet numbers.
Clarify your assumptions around target model architectures, prompt and output token lengths, numeric formats, whether prefill and decode split selectively or always, and how deadline adherence, cost per token, fleet utilization, and numerical fidelity are ranked.
Scope & Expectations
- Job intake, sharding, & fairness: Structure admission control, shard sizing, prefix/length-aware batching, deadline slack scheduling, and multi-tenant fair-share enforcement.
- Disaggregated execution & placement: Coordinate model weight residency and optional prefill-to-decode KV-cache streaming across heterogeneous GPU pools under network and memory budgets.
- Empirical hardware-aware routing: Continuously fit and validate runtime performance and failure profiles from live execution telemetry to guide placement without relying on static specs.
- Resilience & capacity planning: Handle worker crashes, partial-progress recovery, retry idempotency, and sudden capacity drops while protecting accepted deadlines.
Step-by-step walkthrough
Clarify requirements, LLM phases, and hardware pools
Large language model (LLM) generation runs in two distinct phases with opposite hardware needs:
- Prefill reads the entire input prompt in parallel to compute the model's initial attention memory—called the KV cache (Key-Value cache), the per-layer key and value vectors saved for every token so earlier tokens never have to be recomputed. Prefill does huge matrix-matrix multiplications and is compute-bound (limited by math operations per second, FLOPs).
- Decode generates output tokens one token at a time, reading all model weights plus the growing KV cache from GPU memory on every single step. Decode is memory-bandwidth-bound (limited by how fast gigabytes can stream out of GPU High-Bandwidth Memory, HBM).
Pin down explicit production assumptions before sizing the cluster:
- Supported models, lengths, and formats: dense decoder-only transformers (
8Bto70Bparameters) using grouped-query attention (GQA)—an attention layout where multiple query heads share fewer KV heads to shrink the KV cache. Prompts reach32ktokens (median2,000), outputs reach4ktokens (median400). Weight formats areBF16,FP8,FP16, andINT4weight-only (FP16lets older V100 GPUs, which lackBF16andFP8hardware, run8Bmodels). The tenant chooses the format per job; the router never silently quantizes a job, because changing precision alters output quality. - Disaggregation policy: prefill and decode are optionally separated per shard of requests. Colocated execution on one replica is the safe default; splitting across pools happens only when decode cost savings beat network transfer overhead.
- Optimization goals (in priority order): (1) meet
>= 99%of accepted job completion deadlines, (2) minimize total dollars per generated token, (3) keep every hardware pool well utilized without letting one giant batch starve other tenants, and (4) preserve numerical reproducibility when requested.
Pool Accelerator HBM RAM HBM Bandwidth Peak BF16/FP16 Supported Formats Assumed $/GPU-hr ---- ---------------- ------- ------------- -------------- ----------------- ---------------- H H100-class SXM 80 GB 3.35 TB/s ~989 TFLOPS BF16, FP8, FP16 $2.50 A A100-class SXM 80 GB 2.04 TB/s ~312 TFLOPS BF16, FP16 $1.20 V V100-class SXM 32 GB 0.90 TB/s ~125 TFLOPS FP16, INT4 only $0.35Back-of-the-envelope: why prefill, decode, and KV transfer pull apart
Run the numbers on a concrete
70BGQA model (80layers,8KV heads of dimension128,BF16weights =70B * 2 B = 140 GB):1. Per-token fundamentals Prefill math ~2 * 70e9 = 1.4e11 FLOPs/prompt token (+ ~2% causal attention at 2k, ~30% at 32k) KV cache size 2 (K,V) * 80 layers * 8 heads * 128 dims * 2 B = 327,680 B = 320 KiB / token 2. Prefill cost (compute-bound; assume 40% achieved FLOP utilization) H100: 989e12 * 0.40 / 1.4e11 = ~2,830 prompt tok/s/GPU -> $2.50 / (2,830 * 3,600) = $0.25 / 1M tok A100: 312e12 * 0.40 / 1.4e11 = ~890 prompt tok/s/GPU -> $1.20 / ( 890 * 3,600) = $0.37 / 1M tok 3. Decode cost (bandwidth-bound; 8-GPU replica, batch = 256, context = 2,500, 70% HBM bandwidth) Bytes read/step = 140 GB weights + (256 * 2,500 * 320 KiB = 210 GB KV) = 350 GB total 8x A100 (8 * 2.04 = 16.3 TB/s): 350 GB / (16.3 TB/s * 0.70) = 31 ms/step -> ~8,400 tok/s roofline 8x H100 (8 * 3.35 = 26.8 TB/s): 350 GB / (26.8 TB/s * 0.70) = 19 ms/step -> ~13,700 tok/s roofline Budgeting conservatively at 50% of roofline (~4,200 tok/s on 8x A100 @ $9.60/hr; ~6,900 on 8x H100 @ $20/hr): Pool A decode = $0.64 / 1M output tok vs. Pool H decode = $0.81 / 1M output tok 4. Daily workload (assumed: 10B prompt tokens/day = 115,700 tok/s; 2B output tokens/day = 23,100 tok/s) Fleet size (+25% headroom): Pool H = 52 H100s (13 replicas of TP=4); Pool A = 56 A100s (7 replicas of TP=8) KV network load if 100% split: 115,700 prompt tok/s * 320 KiB = 37.9 GB/s = ~303 Gb/s!Four design lessons jump right out of this math:
- Comparative advantage is real but bounded: Pool H is
~1.5xcheaper on prefill ($0.25vs.$0.37/M), while Pool A is~1.25xcheaper on decode ($0.64vs.$0.81/M, saving$0.17/Moutput tokens). Across2,000Moutput tokens/day, splitting saves2,000 * $0.17 = ~$340/day(~8.5%off$4,070/daycolocated on H down to$3,730/day). - Inter-pool KV bandwidth is the bottleneck: moving
320 KiB/token(655 MBfor a2,000-token prompt;2.62 GBfor8,000tokens) for every prompt would consume~303 Gb/s—nearly saturating a400 Gb/sinter-pool link. The router must split selectively. - Why
TP = 4for prefill andTP = 8for decode: tensor parallelism (TP) splits each layer's weight matrices acrossNGPUs connected over fast NVLink. On prefill,4H100s (320 GBHBM) easily hold140 GBof weights (35 GB/GPU) with minimal cross-GPU sync; on decode,8A100s (640 GBHBM) leave~430 GBfree for KV cache so hundreds of sequences batch together and amortize the140 GBweight read. - Pool V (
32 GBV100s) serves8BFP16models (16 GBweights +~13 GBKV cache on a single GPU, no cross-card70Bconversion headaches).
- Comparative advantage is real but bounded: Pool H is
API contracts, reproducibility, and job lifecycle
Expose an asynchronous batch API that checks deadline feasibility before accepting a job:
POST /v1/jobs { "model": "dense-70b", "weight_format": "bf16", "input_uri": "s3://tenant-a/prompts.jsonl", # one JSON line per custom_id "sampling": { "temperature": 0.0, "max_tokens": 1024, "seed": 7 }, "deadline": "2026-11-28T06:00:00Z", "priority": "standard", "placement": { "pin_hardware": null, "allow_split": true } } -> 202 Accepted { "job_id": "job_8f2", "state": "validating" } -> 409 Conflict { "error": "deadline_infeasible", "earliest_feasible": "2026-11-28T11:30:00Z" } GET /v1/jobs/{id} -> progress counts, predicted finish timestamp, slack status POST /v1/jobs/{id}/cancel -> halts queued shards; keeps completed shard outputs intact GET /v1/jobs/{id}/results -> manifest of output JSONL files (exactly one record per custom_id)Internal control-plane and data-plane RPCs:
Scheduler -> Worker Assign { shard_id, attempt, plan: Colocate(pool) | Split(p_pool, d_pool), lease_s: 60 } Worker -> Scheduler Heartbeat { shard_id, attempt, reqs_done, tokens_done } (every 10 s) Worker -> Scheduler Done { shard_id, attempt, output_uri, batch_timings[] } Prefill -> Decode KVStream { request_id, layer_idx, kv_pages } (RDMA per layer)- Why
pin_hardwareexists: floating-point addition is not associative, so H100 vs. A100 tensor cores—or even different batch sizes on the same GPU—produce tiny rounding differences that occasionally flip greedy token choices. Tenants needing bit-identical reruns setpin_hardwareand enable batch-size-invariant reduction kernels, trading slightly lower throughput for determinism. - Zero-overhead profiling: every
DoneRPC piggybacks measured(batch_shape, elapsed_ms)tuples from live production work.
- Why
Data model: shards, manifests, partial checkpoints, and versioned profiles
Break huge jobs into shards of
~512requests (~1.2Mtokens, taking a few minutes on one replica) grouped by shared system-prompt prefix hash and prompt-length bucket:jobs job_id PK, tenant_id, model, weight_format, sampling, deadline, priority, state, est_prompt_tokens, est_output_tokens, submitted_at shards shard_id PK, job_id, req_range, prefix_hash, length_bucket, est_gpu_seconds, state: queued | leased | done | failed, attempt INT, lease_owner, lease_expires_at manifest (job_id, shard_id) PK -> winning_attempt INT, output_uri # written atomically once partials request_id PK -> generated_token_ids[] # checkpointed every 256 tokens profiles key = (pool, gpu_sku, driver_ver, runtime_ver, model, weight_fmt, kv_fmt, tp_degree, phase) coeffs: { a0, a1, a2 } | { b0, b1, b2 }, sample_count, p50_err, p90_err, state: fresh | suspect | expired, updated_at pools pool_id PK, total_gpus, healthy_gpus, cost_per_gpu_hr, failures_per_gpu_hr, link_gbps_map tenants tenant_id PK, fair_share_weight, reserved_gpu_s_rate, max_pool_fraction- Why group shards by prefix and length: grouping requests that share a
1,500-token system prompt computes and transfers that prefix KV once per shard; bucketing similar prompt lengths eliminates wasted padding and makes batch duration tightly predictable. - Why commit via
manifest: retried shards write to.../shard_12_attempt_2.jsonl; atomic insertion intomanifestselects exactly one winning attempt so retries never duplicate results.
- Why group shards by prefix and length: grouping requests that share a
Draw the high-level platform architecture
Tenants --(POST /v1/jobs)--> Job API --> CPU Ingestion Pool (tokenize, hash prefixes, cut ~512-req shards) | v +---------------------------------------------------------------------+ | Hardware-Aware Scheduler & Router | | - Admission control (sells <= 80% of measured pool capacity) | | - Least-slack-first queue + GPU-second deficit round robin | | - Per-shard planner: Colocate vs Split under inter-pool link cap | +----------------------------------+----------------------------------+ | Assign (60 s lease) | ^ v v | live timings + errors +-------------------------+ RDMA KV +-------------------------+ +-------------------+ | Pool H (H100, TP=4/8) |==400 Gb/s==> | Pool A (A100, TP=8) | | Profile Service | | Prefill + Colocated Dec | streaming | Dedicated Decode | | (roofline fits, | +-------------------------+ +-------------------------+ | drift & probing) | | +-------------------+ +-------------------------+ | | Pool V (V100, TP=1) | Placement Controller (rebalances model replicas every 5 min) | 8B FP16 Colocated | | +-------------------------+------------------------+ v Regional Object Storage (inputs, attempt JSONLs, manifests, 256-tok partials, weights)For a shard planned as
Split(H, A):- The scheduler leases the shard on a Pool H prefill replica and simultaneously reserves decode KV slots on a Pool A replica before prefill begins, so
655 MB+ of KV never stalls in expensive H100 memory waiting for downstream room. - Pool H runs chunked prefill and streams each transformer layer's KV pages directly into Pool A's GPU memory via RDMA (Remote Direct Memory Access)—network hardware that copies memory card-to-card without CPU copies—overlapping Layer
inetwork transfer with Layeri+1compute. - Pool A folds the arrived sequences into its continuous decode batch, checkpoints long outputs every
256tokens, writes the attempt output file, commits themanifestrow, and releases both reservations.
- The scheduler leases the shard on a Pool H prefill replica and simultaneously reserves decode KV slots on a Pool A replica before prefill begins, so
Deep dive 1: hardware-aware routing from live roofline profiles
Datasheet FLOPs lie in production: kernel regressions after a runtime update, rack thermal throttling, or degraded NVLink lanes can slow a pool by
30%. Frame performance prediction as an online ML regression service:- Prediction target and labels: predict batch wall-clock time (
ms) for a prefill chunk or single decode step, plus poolfailures_per_gpu_hrfrom expired leases. EveryDonemessage supplies ground-truth batch timings (millionsof labeled batches/day). - Physics-informed roofline model (one lightweight linear model per
profiles.key, fit via exponentially decayed weighted least squares over a 24-hour window, seeded by a 20-minute micro-benchmark sweep whenever a new software/hardware key appears):
prefill_chunk_ms = a0 + a1 * new_tokens + a2 * causal_attention_token_pairs decode_step_ms = b0 + b1 * active_batch_size + b2 * total_kv_tokens_readUnlike an opaque deep neural net, a roofline-shaped linear model extrapolates safely to unseen batch sizes, and its slopes have physical meaning (
b2equalsbytes_per_kv_token / achieved_hbm_bandwidth, making bad fits trivial to sanity-check). Evaluate offline onp90shard runtime error (target < 15%), 95% confidence-interval calibration, and replay simulations of week-long production traces.Scoring candidate plans and preventing stale-profile collapse:
plan_cost(shard, plan) = E[gpu_seconds] * pool_price + failure_rate * E[lost_gpu_s] + link_shadow_cost predicted_finish = replica_queue_wait_s + E[shard_run_s]Four guardrails stop feedback loops where one optimistic or stale profile breaks routing:
- Continuous residual check: if actual vs. predicted median error exceeds
20%over10 minutes, flip the profile tosuspect, widen its time buffer, and cap new assignments to that pool until refit. - Software-versioned keys: bumping CUDA, driver, or vLLM/TensorRT-LLM version creates a fresh key requiring a benchmark sweep before taking full traffic.
- Epsilon exploration (
~3%): keep~3%of eligible shards flowing to under-routed pools so a pool that suffered temporary thermal throttling keeps generating fresh timing samples and recovers automatically once healthy. - Queue-aware damping: include live replica queue wait in
predicted_finishand cap pool share shifts to<= 20%per5 minutesso the router never stampedes100%of work onto one pool.
- Prediction target and labels: predict batch wall-clock time (
Deep dive 2: prefill/decode disaggregation under a network budget
In online chat serving, disaggregation protects interactive typing smoothness; in offline batch processing, nobody watches tokens stream, so disaggregation must pay for its KV network transfer in pure dollars saved.
Notice the asymmetry: decode savings scale with output tokens (
~$0.17saved per1Moutput tokens on Pool A vs. Pool H), whereas network transfer scales with prompt tokens (320 KiBmoved per prompt token):Workload shape KV moved Output saved Output tokens saved per MB moved ------------------------------------ ----------- ------------ -------------------------------- Balanced generation (1,000 in/1,000) 328 MB 1,000 tok 3.05 output tokens / MB Long-doc extraction (8,000 in / 50) 2,621 MB 50 tok 0.019 output tokens / MB (160x worse!)- Greedy knapsack routing: estimate output length from historical runs of that tenant's job template—or run a 1% pilot slice first to measure empirical output lengths. Every
30 seconds, sort queued shards bypredicted_output_tokens / kv_megabytes_movedand assign top shards toSplit(H, A)until predicted inter-pool traffic hits70%of link capacity (280 Gb/son a400 Gb/slink) or Pool A fills up; route remaining shards toColocate(H). (Ranking by value-per-weight solves the fractional knapsack problem—maximizing total dollars saved subject to a fixed bandwidth cap.) - Cutting bytes and latency per transfer:
- Layer-wise RDMA overlap: streaming each of the
80layers as soon as it finishes hides52 msof100 Gb/stransfer inside180 msof H100 prefill. - Prefix deduplication: for shards sharing a
1,500-token system prompt, Pool A caches that prefix KV once so only the500-token user suffix (164 MBinstead of655 MB) crosses the wire. - Zero-reshuffle head mapping: Pool H uses
TP = 4(2KV heads/GPU) and Pool A usesTP = 8(1KV head/GPU); each H100 streams Head 0 to one A100 and Head 1 to a second A100 with zero tensor slicing, keepingBF16KV intact since A100 lacks nativeFP8tensor cores.
- Layer-wise RDMA overlap: streaming each of the
- When the router colocates anyway: long-prompt/short-output tasks, congested inter-pool links, full or degraded Pool A, tight deadline slack (splitting adds a second queue and failure domain), unsupported precision, or off-peak hours when Pool H GPUs would otherwise sit idle.
- Greedy knapsack routing: estimate output length from historical runs of that tenant's job template—or run a 1% pilot slice first to measure empirical output lengths. Every
Deep dive 3: admission control, deadlines, fair share, and batching
Balance strict deadlines, multi-tenant fairness, and large GPU batches across three layers:
- Admission control (
<= 80%sold capacity): after tokenizing an uploaded job, computeest_gpu_secondsandrequired_rate = est_gpu_seconds / (deadline - now - safety_margin)(withsafety_margin = max(30 min, 10% of window)). Accept the job only if cumulativerequired_rateacross admitted jobs stays<= 80%of measured pool throughput; otherwise return409withearliest_feasible. Keeping20%unsold absorbs output-length variance and hardware hiccups. - Urgency + GPU-second fairness: define each job's slack—the spare time left before we must run flat-out to make its deadline (
slack = deadline - now - remaining_work / allocated_rate).- Jobs with
slack < 2 hoursenter an at-risk priority lane scheduled in least-slack-first order. - Normal jobs share capacity via deficit round robin—a weighted fair queuing loop where each tenant accumulates a credit counter measured in GPU-seconds (never raw request count, so
32k-token prompts pay their true compute cost!). Enforce a 40% per-tenant cap whenever other tenants have queued shards, while remaining work-conserving: if the cluster is quiet, one tenant's huge batch may borrow100%of idle GPUs and hand borrowed slots back at shard boundaries (~2-4 minutes) as soon as peers arrive. - Distant-deadline low-priority "filler" shards soak up leftover
20%headroom so fleet utilization stays near95%+.
- Jobs with
- Hardware-friendly batching: prefill uses chunked prefill (
16k-token fixed chunks from one length bucket for predictable step times); decode uses continuous batching—swapping new sequences into finished batch slots after any single token step so short answers never wait for4,000-token essays. On8x A100(640 GBHBM minus140 GBweights minus~70 GBactivation/CUDA/NCCL buffers =~430 GBKV space), one replica holds430 GB / (2,500 * 320 KiB) ~= 525concurrent sequences.
- Admission control (
Model placement, retries, pool loss, and switchback testing
Amortizing model swaps. Streaming
140 GBof weights from local NVMe (~5 GB/s) stalls an 8-GPU replica for~30 seconds(minutes from object storage). A placement controller adjusts replica counts every5 minuteswith hysteresis: switch a replica's loaded model only when queue imbalance persists>= 10 minutesand pays back the30 sreload cost within30 minutes.Leases, checkpoints, and surviving a full pool outage:
- 60-second leases + manifest fencing: if a worker dies, its
60 sheartbeat lease expires and the shard re-queues asattempt + 1. Even if a zombie worker wakes up later, atomicmanifestfencing rejects stale attempts, ensuring at-least-once execution with exactly-once output. Seeding token sampling fromhash(job_seed, custom_id, token_idx)keeps random draws reproducible across retries. - 256-token partial checkpoints & poison isolation: long
4,000-token decodes flush token IDs topartialsevery256tokens; after a crash, another replica re-prefillsprompt + partial_tokens, losing at most~8 secondsof decode work. Requests crashing workers twice are quarantined as per-item errors so one malformed input never kills a whole job. - When an entire pool disappears mid-job: within
60 s, expired leases return in-flight shards to the scheduler while completed shards remain safe in object storage. If Pool A vanishes completely, its23,100 output tok/sworkload requires23,100 / (6,900 / 8) ~= 27H100 GPUs running colocated—more than Pool H's11spare GPUs (52total minus41busy). The scheduler immediately pauses low-priority filler work, dedicates Pool H to high-priority and least-slack jobs, resumes interrupted long decodes frompartials, and pushes updated finish-time alerts to affected standard-tier jobs.
Evaluating router upgrades via switchback tests. You cannot A/B test two cluster schedulers by splitting jobs
50/50simultaneously because both policies compete for the same GPU queues and RDMA links! Validate first in a week-long trace-replay simulator, then run a production switchback test—alternating the entire cluster between Router v1 and Router v2 in randomized2-hourtime blocks over two weeks (discarding the first20 minutesof each block while carry-over shards drain), comparing$/million tokensunder strict deadline-hit-rate and fairness guardrails.- 60-second leases + manifest fencing: if a worker dies, its
Summarize the design trade-offs
- Selective disaggregation vs. universal splitting. Splitting prefill (
H100) and decode (A100) saves~$0.17/Moutput tokens (~8.5%fleet cost) but moves320 KiB/prompt token; ranking shards by output-tokens-per-MB under a70%RDMA link cap captures nearly all the savings without saturating the network. - Live roofline models vs. static datasheets. Regression models trained on live
Donetimings adapt to driver changes and throttling, while versioned keys,20%-error circuit caps,3%exploration, and damped shifts prevent feedback collapse. - 80% admission cap + filler work vs. 100% booking. Leaving
20%capacity unpromised protects99%deadline guarantees against variance and node failures, while low-priority filler shards recover high GPU utilization. - GPU-second fair share vs. giant single-tenant batches. Deficit round robin on GPU-seconds with work-conserving
40%pool caps stops32k-prompt whales from monopolizing the cluster while still letting idle GPUs run full batches.
- Selective disaggregation vs. universal splitting. Splitting prefill (
Intuition & how it works
Picture an overnight commercial bakery with two kinds of machines: brand-new industrial flash ovens (Pool H, H100 GPUs) that bake whole trays of dough in parallel at blazing speed, and older, much cheaper packaging lines (Pool A, A100 GPUs, plus Pool V, V100 GPUs for small items) that box baked cookies one by one. LLM inference splits into the exact same two jobs: prefill processes all input prompt tokens in parallel (heavy math, where H100s are 1.5x cheaper per token), while decode generates output tokens one step at a time, bottlenecked by reading memory (memory-bandwidth-bound, where A100s are 1.25x cheaper per output token). The catch is the conveyor belt between rooms: handing a request from Pool H to Pool A means shipping its KV cache (the per-layer attention memory built from the prompt—320 KiB per prompt token for a 70B model, or 655 MB for a 2,000-token prompt) across the datacenter network.
A naive platform either runs everything on expensive H100s, blindly ships every prompt's KV cache across the network (instantly clogging a 400 Gb/s link and losing money on long-prompt/short-answer jobs), or routes using static datasheet specs that go wrong after a single GPU driver update or thermal throttle. It also lets one customer upload a 10-million-prompt batch and freeze everyone else's deadlines for a day.
Watch how our router handles two 512-request shards (bite-sized chunks of a batch job) arriving together:
- Shard 1 (
1,000prompt tokens -> ~1,000output tokens, essay generation): Moving328 MBof KV saves1,000expensive H100 decode tokens (3.05tokens saved per MB moved). Because the400 Gb/sRDMA (direct GPU-to-GPU network) link is below its70%budget and Pool A has room, the scheduler reserves decode slots on Pool A first, prefills on4x H100, streams KV layer-by-layer while computing, and decodes cheaply on8x A100. - Shard 2 (
8,000prompt tokens -> ~50output tokens, document classification): Moving2.62 GBof KV would save only50output tokens (0.019tokens/MB—160xworse payoff!). The router keeps Shard 2 colocated on Pool H, skipping network transfer completely. - Fairness and live feedback: Both tenants pay from GPU-second fair-share budgets so long
8,000-token prompts cannot hog the cluster, and when both shards finish, theirDonemessages report exact batch runtimes back to the Profile Service to keep our hardware speed models honest.
Key trade-offs
- Selective disaggregation vs. colocated execution in offline workloads. Unlike live chat—where splitting prefill and decode protects interactive typing speed—offline batch jobs care only about deadlines and total dollars. Because
70BBF16decode saves~$0.17per million output tokens on Pool A while KV transfer costs320 KiBper prompt token, greedily splitting only highoutput_tokens / kv_MBshards up to a70%link cap captures most of the~8.5%(~$340/day) cost savings without saturating inter-pool networking. - Physics-based roofline regression vs. static specs or black-box ML. Static datasheet numbers miss driver regressions and thermal throttling, whereas black-box neural nets extrapolate poorly to unseen batch sizes. Fitting a linear roofline model (predicting batch time from new tokens, causal attention pairs, batch size, and KV bytes read) per software-versioned hardware key adapts in real time while staying physically interpretable—at the cost of maintaining residual alerts,
~3%exploration probes, and rate-limited traffic shifts. - 80% admission control + filler queues vs. 100% capacity booking. Promising
100%of cluster throughput guarantees missed deadlines whenever output lengths run long or nodes fail. Capping deadline-committed admissions at80%protects our>= 99%deadline SLA, while filling idle cycles with distant-deadline low-priority "filler" shards wins back high GPU utilization. - GPU-second fair share vs. maximum single-job batching. Enforcing deficit round robin (weighted fair queuing) on GPU-seconds with a
40%per-tenant cap slightly fragments one whale tenant's uniform batches when the cluster is busy, but prevents starvation; making the cap work-conserving lets large jobs borrow100%of idle GPUs during quiet periods and yield at shard boundaries (~2-4 minutes). - Shard granularity (
~512requests) and256-token checkpoints. Tiny shards add scheduling chatter and weaken system-prompt prefix sharing; giant shards waste hours on retries and react sluggishly to fairness changes. Multi-minute shards paired with256-token partial decode checkpoints bound lost work on crashes to seconds. - Model-swap hysteresis vs. instant queue rebalancing. Reloading
140 GBof70Bweights takes~30 secondseven from local NVMe SSDs (~5 GB/s). Requiring a10-minutesustained imbalance and a30-minutepayback window avoids thrashing GPUs on brief traffic blips. - Hardware pinning vs. routing flexibility. Cross-GPU floating-point differences and dynamic continuous batching shapes can alter greedy token choices. Offering
pin_hardwareplus batch-invariant kernels satisfies strict reproducibility tenants at the price of narrower pool choices and slightly lower kernel throughput.
Common mistakes
- Assuming "older GPUs for decode" is unconditionally cheaper. Decode is HBM-bandwidth- and KV-capacity-bound, so older cards win only when measured
(tokens/sec per dollar)minus failure retry waste beats newer cards—and32 GBV100s lackBF16/FP8support and cannot hold140 GB70Bweights without awkward 8-way splitting, making them suited to8BFP16jobs instead. - Ignoring KV cache network volume. Forgetting that
115,700 prompt tok/s * 320 KiB/tokgenerates~303 Gb/sof continuous cross-pool traffic, which easily chokes datacenter links if long-prompt classification jobs are split blindly. - Running prefill before reserving downstream decode KV memory, trapping gigabytes of finished KV cache inside scarce H100 HBM while Pool A is full.
- Mismatched tensor-parallel KV head layouts or unsupported KV formats, such as choosing tensor parallelism (TP) degrees that do not evenly divide the
8GQA KV heads (forcing expensive network reshuffles) or streamingFP8KV tensors to A100s without accounting for software dequantization overhead. - Silently quantizing weights (
BF16 -> INT4/FP16) inside the router to squeeze a job onto older hardware; precision changes alter model accuracy and must be explicitly chosen by the tenant. - Metering fairness by request count instead of GPU-seconds, letting a tenant sending
32k-token prompts consume30xmore cluster compute than a tenant sending1k-token prompts. - Evaluating two routing policies with a simultaneous 50/50 job split, ignoring shared-queue interference where Policy B's pool congestion slows Policy A's jobs, instead of running time-alternating switchback tests.
Follow-up questions
- Under what workload or cluster conditions should the scheduler keep prefill and decode on the same replica even if disaggregated pools would improve per-chip utilization? Colocate whenever KV transfer costs or operational risk outweigh the decode price gap: first, on long-prompt, short-output shards (such as
8,000tokens in and50tokens out, yielding just0.019saved decode tokens per MB moved vs.3.05on balanced generation). Second, colocate when the inter-pool RDMA link approaches its70%bandwidth cap, when the decode pool is full, draining, or showing elevated failure rates, or when a job's slack (spare time before missing its deadline) is tight enough that adding a second queue and network hop risks a miss. Finally, colocate when the job's model or precision (FP8) is unsupported on older pools, or during off-peak hours when Pool H H100s would otherwise sit idle anyway. - What safeguards stop outdated or miscalibrated hardware speed models from triggering herd stampedes or starving a throttled pool of fresh measurements? Key every profile by
(hardware SKU, driver, runtime, model, precision, TP degree)so software upgrades automatically expire old coefficients and trigger a short benchmark sweep before taking full load. Continuously compare liveDonebatch durations against predictions: if median error exceeds20%for10 minutes, mark the profilesuspect, widen its uncertainty penalty, and cap new shard assignments to that pool until refit. Finally, include live replica queue wait in routing scores, rate-limit pool allocation shifts to at most20%per5 minutesto prevent herd stampedes onto one "fast-looking" pool, and maintain~3%exploration traffic across all eligible pools so temporarily throttled hardware keeps getting measured and recovers smoothly. - Walk through how in-flight shards, partial token generation, and deadline commitments recover if an entire accelerator pool goes offline mid-run. Within
~60 seconds, missed heartbeats expire active shard leases on the lost pool and return those shards to the scheduler, while already-completed shards stay safe in object storage behind the atomicmanifest(preserving exactly-once output) and interrupted long decodes resume elsewhere by re-prefillingprompt + 256-token partials. The scheduler immediately recomputes every job's slack against the smaller fleet: our20%unsold admission buffer absorbs single-node or rack losses seamlessly, whereas losing all of Pool A shifts23,100 output tok/s(~27H100s of colocated decode work) onto Pool H, which has only~11spare H100s. Consequently, the scheduler pauses low-priority filler work, prioritizes high-priority and least-slack jobs, and sends early revised completion estimates to at-risk standard jobs; once Pool A returns, it runs a verification benchmark and ramps traffic back gradually under the20%-per-5-minute rate limit.
Follow-up questions
- Under what workload or cluster conditions should the scheduler keep prefill and decode on the same replica even if disaggregated pools would improve per-chip utilization?
- What safeguards stop outdated or miscalibrated hardware speed models from triggering herd stampedes or starving a throttled pool of fresh measurements?
- Walk through how in-flight shards, partial token generation, and deadline commitments recover if an entire accelerator pool goes offline mid-run.
Similar questions
- Natural-Language Image Search Architecture
- Align Asynchronous Cycle-Count Traces Onto Shared Timestamps
- LRU Cache Implementation
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models