Million-Token Inference on Specialized Chips: Cost, Deployment, and Validation
A practical guide to estimating memory requirements and evaluating the cost of million-token inference on specialized hardware. It covers fused kernels, sparse attention, MoE, FP8 quantization, batching, and deployment through an OpenAI-compatible API, with an emphasis on validating quality and throughput against real workloads.
Key Takeaway: Four Layers Determine Cost
The cost per million tokens for long-context inference depends on two numbers: how many tokens the system processes per hour and how much the entire machine costs per hour. Reducing that cost requires coordinated optimization across four layers: model architecture, numerical precision, attention algorithms, and execution scheduling. Optimizing only one layer usually delivers limited gains.
Before deployment, prioritize three checks: calculate whether the model and its caches fit in device memory, test quality on your own data, and measure throughput under your own workload. The following sections follow that sequence.
1. Cost Modeling and Memory Estimates
Why decoding is often memory-bound
Autoregressive decoding reads model weights and the existing key-value (KV) cache for every token it generates. The arithmetic workload is relatively small compared with the volume of memory access, so hardware often spends time waiting for data rather than executing multiply-accumulate operations. Improving memory-bandwidth utilization and reducing the bytes read per token can therefore be more effective than adding compute capacity.
A mixture-of-experts (MoE) model reads only the expert weights activated for each token. During large-batch decoding, however, different requests activate different experts. The combined set of experts accessed across the batch grows quickly and can approach the full expert set. MoE therefore offers more substantial memory-traffic savings at small batch sizes, with smaller savings at larger batch sizes.
Sparse attention reduces the number of KV bytes read per token, but does not, by itself, reduce the memory occupied by the KV cache.
Estimating KV cache size
Use the following approximation:
KV cache bytes ≈ 2 × number of layers× number of KV heads× head dimension× context length× concurrent sequences× bytes per element× (1 + overhead ratio)
The initial factor of two accounts for the separate K and V tensors.
The KV head count is the number of key-value heads. In grouped-query attention (GQA), this is smaller than the number of query heads. Use the KV head count—not the query head count—in the calculation.
The number of concurrent sequences determines how many long-context requests can remain active simultaneously. In production serving, this can matter more than the memory requirement of a single sequence.
The overhead ratio accounts for paging metadata, FP8 scaling factors, and memory fragmentation. It depends on the inference engine and should be measured rather than assigned a fixed value.
Consider a hypothetical configuration with 60 layers, eight KV heads, a head dimension of 128, a one-million-token context, and one sequence. Excluding overhead, its FP8 KV cache requires:
2 × 60 × 8 × 128 × 10^6 × 1 byte ≈ 123 GB
At two bytes per element, BF16 requires approximately 246 GB. These are illustrative parameters, not the configuration of a specific model.
Serving two concurrent one-million-token sequences would require approximately 246 GB for the FP8 KV cache alone.
Budgeting for weights and the KV cache
Calculate memory requirements in this order:
- Model weights.
- KV cache.
- Additional headroom for activations, communication buffers, and fragmentation.
For a model with 320 billion total parameters, weights occupy approximately 320 GB in FP8 or 640 GB in BF16. The combined weight and KV cache footprint must remain below total usable device memory, with sufficient headroom.
If weights are sharded across multiple accelerators, include the communication buffers required on each device.
2. When Fused Kernels Are Worth the Effort
The main benefits of large fused kernels are fewer kernel launches and fewer round trips to device memory for intermediate results.
In a conventional execution path, each layer includes multiple operations: QKV projection, attention, output projection, normalization, MoE routing, expert computation, and residual merging. Each operation launches separately. Intermediate results are written to device memory and then read by the next operation.
During small-batch decoding, launch overhead and memory round trips can account for a significant share of execution time.
Compiling multiple stages within a layer into one or two kernels offers three main benefits:
- Lower fixed overhead from kernel launches and transitions.
- Less device-memory traffic because intermediate tensors remain in on-chip storage.
- Less waiting between different compute units.
The trade-off is engineering effort. Fused kernels often require manual tuning for a specific chip architecture. Changing the hardware or model architecture can require redevelopment and validation. Include that work in the total cost assessment.
Start with profiling. If kernel-launch overhead and memory stalls dominate layer execution time, fusion can deliver substantial gains. If large matrix multiplications are already the bottleneck, the benefit is likely to be limited.
3. Choosing Attention for a Million-Token Context
The available public materials do not disclose the exact attention combinations, window sizes, or number of active blocks used by the engines discussed here. The following covers common approaches and their trade-offs, rather than attributing a specific implementation to any engine.
- Local-window attention: Applies full attention only to a recent span of tokens. Information from more distant positions is carried through mechanisms such as anchor tokens or summary vectors. This approach is relatively simple, but important details outside the window can be lost if the information-transfer mechanism does not preserve them. Anchor tokens are only one possible implementation; mechanisms vary by engine.
- Block-retrieval attention: Organizes the KV cache into blocks and uses lightweight scoring during decoding to select a small set of relevant blocks. This can suit retrieval tasks, but scoring errors may exclude critical blocks.
- Layer-wise hybrid attention: Uses sparse attention in most layers while retaining full attention in a few important layers. This can provide a useful balance between quality and cost, but requires layer-by-layer evaluation to identify where full attention is necessary.
Begin by identifying the task types most sensitive to errors in your application. Then compare each approach with a full-attention baseline on identical inputs. Common metrics include answer agreement and recall of key information.
Does sparse attention reduce quality?
It can, and the impact depends on the task. Retrieval and multi-hop reasoning are sensitive to distant information and carry a higher risk of degradation. Summarization and everyday conversation are often more stable.
Evaluate with your own application data rather than relying exclusively on general benchmarks.
Can sparse attention be combined with FP8?
Yes, but validate them separately first. Both introduce approximation errors, and those errors can accumulate when combined.
Enable each optimization independently, verify acceptable quality, and then test the combination before production rollout. Keep a readily accessible rollback switch.
4. Benefits and Limits of MoE and FP8 Quantization
Sparse activation in MoE
MoE activates only a small subset of experts for each token. For example, a model with 320 billion total parameters and roughly 18 billion active parameters has per-token computation closer to that of an 18-billion-parameter dense model, while retaining a much larger total parameter capacity. This is the primary source of its FLOP reduction.
However, in a typical single-machine deployment with all weights resident in device memory, every expert’s parameters must remain loaded. Sparse activation does not reduce the memory required to store those weights.
Offloading experts to host memory, distributing them across machines, or using tiered storage changes this constraint, but adds access latency. Evaluate those options against the actual latency budget.
FP8 quantization
Describe FP8 benefits against an explicit baseline. Relative to BF16, FP8 reduces weight storage from two bytes to one byte per element. Weight memory is therefore approximately halved, and weight-related bandwidth demand falls accordingly. This directly benefits memory-bound decoding.
Quantization also requires additional data, such as scaling factors, so actual savings are slightly smaller than the theoretical maximum.
Savings for KV caches and activations depend on their respective implementations. Do not assume they match the weight-storage reduction.
Quality evaluation
Include four areas in the evaluation:
- General capabilities: Compare BF16 and FP8 scores on a fixed evaluation set.
- Long-context capabilities: Use needle-in-a-haystack or similar retrieval tests to measure information recall at different context positions.
- Production metrics: Monitor output-length distributions, refusal rates, and user feedback.
- Fallback options: Retain higher precision for sensitive components, such as the MoE router and output layer, and prepare a configuration that can switch back to BF16.
Dynamic batching
Important settings include the maximum number of tokens per batch, request priorities, KV cache page size, and swapping policies.
Agent workloads often have long inputs and repeated prefixes, so monitor the prefix-cache hit rate separately. A higher hit rate reduces the number of tokens that actually require prefill processing, lowering the effective cost per million tokens.
5. Deployment with an OpenAI-Compatible API
The deployment goal is to let existing clients call /v1/chat/completions without changing their API integration. The following steps apply to inference services that expose this endpoint.
Startup argument names vary by engine. Replace the illustrative arguments with the corresponding options in your engine’s official documentation.
Step 1: Prepare environment variables
Inject secrets through a secret-management service. Do not hard-code them in source code or configuration files, or write them to logs.
export MODEL_PATH=/data/models/<model_directory>export SERVE_HOST=0.0.0.0export SERVE_PORT=8000export MAX_MODEL_LEN=1048576export MAX_NUM_SEQS=<concurrent_sequence_count>export KV_CACHE_DTYPE=fp8export SERVE_API_KEY="$(cat /run/secrets/serve_api_key)"
Step 2: Start the service
<inference_engine_launch_command> \--model "$MODEL_PATH" \--host "$SERVE_HOST" \--port "$SERVE_PORT" \--max-model-len "$MAX_MODEL_LEN" \--max-num-seqs "$MAX_NUM_SEQS" \--kv-cache-dtype "$KV_CACHE_DTYPE" \--api-key "$SERVE_API_KEY"
MAX_MODEL_LEN must be at least as large as the maximum context required by your application. Otherwise, long requests will be rejected at the entry point.
Determine MAX_NUM_SEQS using the KV cache formula in Section 1, allowing sufficient memory headroom.
Step 3: Check service health
curl -sS "http://127.0.0.1:${SERVE_PORT}/v1/models" \-H "Authorization: Bearer ${SERVE_API_KEY}"
The response should include the model name. If it returns HTTP 401, verify that the key matches the startup configuration. If the connection fails, check whether the service has finished loading the weights.
Step 4: Run a non-streaming smoke test
curl -sS "http://127.0.0.1:${SERVE_PORT}/v1/chat/completions" \-H "Content-Type: application/json" \-H "Authorization: Bearer ${SERVE_API_KEY}" \-d '{"model": "<model_name>","messages": [{"role": "user", "content": "Answer in one sentence: What is 1 plus 1?"}],"max_tokens": 32,"stream": false}'
Step 5: Test streaming output
Follow the non-streaming smoke test with a streaming-output test.
