LLM Inference Engineering and Self-Improving Agent Harnesses: From Kernels to Production Systems
Primary references:
Large language model (LLM) inference is no longer only about running a model on a GPU. It is a full-stack engineering discipline spanning CUDA kernels, KV-cache management, quantization, batching, model parallelism, autoscaling, routing, observability, and cost control.
This document covers three complementary areas:
- Inference engineering: how to make a single model instance fast, memory-efficient, and production-ready.
- Memory-constrained inference: how AirLLM runs very large models on small GPUs by streaming model layers.
- Agent-harness self-improvement: how RRSI improves the prompts, tools, memory, control flow, and context management around a frozen model.
A source-coverage note: the Pinterest VLM serving, Anyscale Ray Serve, vLLM explainers, AWS Bedrock and SageMaker posts, Kaggle competition, KiroCrew, Archestra routing, Harvard course, Dream-RSI, autoresearch, tiny-llm, and MDPI paper links were not fully verified from their primary pages in this pass. They are included as a reading list, not as verified technical claims.
Part 1: Foundations
What inference engineering is
Inference engineering is the discipline of serving generative AI models in production faster, cheaper, and more reliably. The 100 Days of LLM Inference project frames it as three layers: runtime, infrastructure, and tooling. github
+-------------------------------------------------------------+
| Inference stack |
+-------------------------------------------------------------+
| Tooling |
| - benchmarking, profiling, metrics, tracing, dashboards |
+-------------------------------------------------------------+
| Infrastructure |
| - GPUs, containers, autoscaling, routing, queues, clouds |
+-------------------------------------------------------------+
| Runtime |
| - tokenization, attention, KV cache, kernels, quantization |
+-------------------------------------------------------------+
The runtime layer determines how efficiently one model instance uses one GPU. The infrastructure layer determines how many requests a cluster can serve reliably. The tooling layer makes both debuggable. github
Inference versus training
Training and inference have different objectives.
| Dimension | Training | Inference |
|---|---|---|
| Goal | Learn model weights | Generate outputs from fixed weights |
| Compute pattern | Large forward and backward passes | Usually forward-only generation |
| Memory pressure | Gradients, optimizer state, activations | Weights, activations, and KV cache |
| Latency metric | Time to converge | Time to first token and time between tokens |
| Cost driver | GPU-hours and data throughput | Tokens, concurrency, cache reuse, and hardware utilization |
| Typical optimization | Data loading, parallelism, mixed precision | Batching, caching, quantization, decoding strategy |
A large language model (LLM) is a neural network trained to model sequences of tokens. During inference, it processes a prompt and generates output tokens one at a time in an autoregressive loop. github
Key inference metrics
| Metric | Definition | Why it matters |
|---|---|---|
| TTFT | Time to first token | Perceived responsiveness |
| TBT | Time between tokens | Streaming smoothness |
| Throughput | Tokens or requests per second | Capacity and cost |
| Queue depth | Requests waiting to be served | Saturation signal |
| GPU utilization | Fraction of GPU capacity in use | Efficiency signal |
| KV-cache hit rate | Share of requests reusing cached context | Cost and latency optimization |
| Cost per token | Infrastructure cost divided by generated tokens | Unit economics |
The 100 Days project explicitly includes TTFT, TBT, queue depth, GPU utilization, KV-cache hit rates, and end-to-end latency breakdowns in its production-system curriculum. github
Part 2: Runtime Optimization
The generation loop
A simplified autoregressive inference loop is:
Prompt tokens
|
v
Prefill: process all prompt tokens
|
v
Generate token 1
|
v
Append token to KV cache
|
v
Generate token 2
|
v
Repeat until stop condition
Prefill processes the entire prompt in parallel. Decode generates one token at a time, reusing the key-value cache from prior tokens. This distinction is central to inference optimization. github
KV cache
The KV cache stores the key and value projections produced by attention layers for previously processed tokens. Without it, every new token would require recomputing attention over the entire prompt and all previously generated tokens.
Prompt: [t1 t2 t3 t4]
KV cache after prefill:
Layer 1: K1, V1
Layer 2: K2, V2
...
New token t5:
Uses cached K/V from t1..t4
Adds K/V for t5
KV-cache memory grows with:
- Number of layers.
- Number of attention heads.
- Head dimension.
- Batch size.
- Sequence length.
- Precision.
The 100 Days curriculum treats KV cache, prefix caching, cache-aware routing, and cache managers as first-class runtime topics. github
Prefix caching
Prefix caching reuses the KV cache for a shared prompt prefix.
Request A:
[System prompt][User A message]
Request B:
[System prompt][User B message]
Shared prefix:
[System prompt]
Optimization:
Compute KV cache for system prompt once.
Reuse it for both requests.
This is especially valuable for:
- Shared system prompts.
- Few-shot examples.
- Repeated document contexts.
- Multi-turn conversations.
- Agent harnesses with stable instructions.
The 100 Days project includes hash-based prefix-cache deduplication and cache-aware routing as practical projects. github
PagedAttention and continuous batching
vLLM introduced two influential serving optimizations:
- PagedAttention: manages KV-cache memory in blocks, similar to virtual-memory paging.
- Continuous batching: adds new requests to a running batch as prior requests finish, rather than waiting for an entire batch to complete.
Traditional static batching:
Request 1 ------>
Request 2 ------>
Request 3 ------>
Wait for all requests to finish before admitting new ones.
Continuous batching:
Request 1 ------>
Request 2 ----> new request joins
Request 3 --> new request joins
GPU remains busy as requests complete at different times.
The 100 Days curriculum covers vLLM, PagedAttention, continuous batching, SGLang, TensorRT-LLM, and NVIDIA Dynamo as major runtime systems. github
Quantization
Quantization reduces the numerical precision used to represent model weights, activations, or both.
| Format | Typical benefit | Trade-off |
|---|---|---|
| FP16 or BF16 | High accuracy | Higher memory and bandwidth |
| FP8 | Good speed and memory balance | Hardware-dependent |
| INT8 | Strong memory reduction | Requires calibration and validation |
| INT4 | Large memory reduction | Greater quality risk |
| NVFP4 | Hardware-accelerated low precision | Hardware-dependent |
The 100 Days curriculum covers FP8, INT8, INT4, NVFP4, GPTQ, AWQ, and SmoothQuant. github
A simplified quantization-and-dequantization operation is:
\[\hat{w} = \text{dequantize}(\text{quantize}(w))\]The goal is to minimize quality loss while reducing memory footprint and improving throughput. Quantization should always be evaluated on task-specific quality metrics, not merely model perplexity.
Speculative decoding
Speculative decoding uses a smaller draft model to propose several tokens. The larger target model then verifies them in parallel.
Draft model proposes:
[t5, t6, t7]
Target model verifies:
t5 accepted
t6 accepted
t7 rejected
Output:
t5, t6
Then target model generates a replacement for t7
If the draft model’s proposals are accepted, the system generates multiple tokens for approximately one target-model verification pass. The 100 Days project includes draft-target, Medusa, and EAGLE speculative decoding, plus acceptance-rate measurement by draft-model size. github
Part 3: Scaling Across GPUs and Clusters
Model parallelism
When a model does not fit on one GPU, or when throughput requires more compute, use parallelism.
| Type | What is split | Best for |
|---|---|---|
| Tensor parallelism | Individual matrix multiplications across GPUs | Large dense layers |
| Pipeline parallelism | Model layers across GPUs | Very deep models |
| Expert parallelism | Mixture-of-experts experts across GPUs | Sparse MoE models |
| Data parallelism | Requests across model replicas | High request throughput |
The 100 Days curriculum includes tensor, expert, pipeline, and data parallelism, plus simulations of splitting matrix multiplication across workers. github
Disaggregated serving
Disaggregated serving separates prefill and decode into different pools of hardware.
Requests
|
v
+----------------+
| Prefill pool |
| Compute-heavy |
+-------+--------+
|
v
+----------------+
| Decode pool |
| Memory-heavy |
+----------------+
Prefill is compute-heavy because it processes many prompt tokens in parallel. Decode is more memory-bandwidth-sensitive because it generates tokens sequentially. Splitting them allows each pool to be sized and scaled independently. github
Autoscaling and routing
A production inference service must decide:
- How many replicas to run.
- When to scale up or down.
- How to route a request.
- How to queue or reject excess traffic.
- How to handle cold starts.
- How to route across clouds or regions.
Client request
|
v
+------------------+
| Load balancer |
+--------+---------+
|
+-- cache-aware route --> replica with matching prefix cache
|
+-- least-connections --> least-loaded healthy replica
|
+-- geo-aware route ----> nearest healthy region
|
v
+------------------+
| Inference replica|
+------------------+
The 100 Days curriculum covers concurrency, batching, cold starts, routing, load balancing, queueing, multi-cloud capacity management, zero-downtime deployment, and cost estimation. github
Observability
A production inference service should emit metrics and traces for every request.
Useful signals include:
- Request arrival rate.
- Queue depth.
- Batch size.
- TTFT.
- TBT.
- Tokens generated.
- GPU utilization.
- GPU memory usage.
- KV-cache hit rate.
- Error rate.
- Model version.
- Routing decision.
- Cost estimate.
The 100 Days project includes Prometheus metrics, Grafana dashboards, OpenTelemetry tracing, Locust load testing, and Nsight Systems profiling. github
Part 4: AirLLM and Memory-Constrained Inference
The problem
Large models often cannot fit in GPU memory. A 70B-parameter model in full precision can require far more memory than a consumer GPU provides.
AirLLM reduces inference memory usage by keeping only one transformer layer on the GPU at a time and streaming the remaining layers from disk. github
Traditional inference:
All model layers resident in GPU memory.
AirLLM inference:
Load layer 1 -> compute -> free
Load layer 2 -> compute -> free
Load layer 3 -> compute -> free
...
This trades latency and disk bandwidth for a dramatically smaller GPU-memory footprint.
Reported capabilities
AirLLM reports the following examples: github
| Model | Size | Reported GPU VRAM |
|---|---|---|
| Qwen3, Mistral, or Phi, approximately 8B | 8B | About 1–2 GB |
| Qwen3-30B or Mixtral MoE | 30–47B | About 1–3 GB |
| Qwen3.8-27B dense vision-language model | 27B | 3.33 GB |
| Qwen3.8-Flash-Next | About 180B | 5.95 GB |
| Qwen3-235B MoE | 235B | About 3 GB |
| Llama 3.x 70B, full precision | 70B | About 4 GB |
| Llama 3.1 405B | 405B | About 8 GB |
| DeepSeek-V3 | 671B | About 12 GB |
| Kimi K3 | 2.8T | 3.72 GB |
These figures are reported by the AirLLM repository under its specific hardware, precision, model format, and streaming configuration. They do not imply that these configurations are fast enough for interactive production serving. github
Why it works
AirLLM’s central trick is that GPU memory need depends on the size of the currently active layer, not the total model size. github
For a model with $L$ layers, traditional inference keeps all layer weights resident:
\[M_{\text{traditional}} \approx \sum_{l=1}^{L} W_l\]AirLLM keeps only one layer resident at a time:
\[M_{\text{AirLLM}} \approx \max_l W_l\]where:
- $W_l$ is the memory required by layer $l$.
- $M$ is GPU memory usage.
The trade-off is that weights must be repeatedly read from disk or host memory, making the approach highly sensitive to storage bandwidth, caching, and prefetching.
Compression
AirLLM also supports 4-bit and 8-bit block-wise quantization-based compression. The repository states that this can speed inference by up to 3 times with almost negligible accuracy loss in its evaluated setting. github
The key distinction it draws is:
- Conventional quantization: often quantizes weights and activations to improve compute speed.
- AirLLM compression: primarily reduces the model-loading size because the bottleneck is disk loading. github
Example inference code
The following example is adapted from the AirLLM repository’s quickstart. github
from airllm import AutoModel
MAX_LENGTH = 128
model = AutoModel.from_pretrained("Qwen/Qwen3-32B")
input_text = ["What is the capital of United States?"]
input_tokens = model.tokenizer(
input_text,
return_tensors="pt",
return_attention_mask=False,
truncation=True,
max_length=MAX_LENGTH,
padding=False,
)
generation_output = model.generate(
input_tokens["input_ids"].to(model.device),
max_new_tokens=20,
use_cache=True,
return_dict_in_generate=True,
)
output = model.tokenizer.decode(generation_output.sequences[0])
print(output)
Example training configuration
AirLLM also supports fine-tuning large models on small GPUs by streaming frozen base weights one layer at a time while keeping adapters resident. github
python air_llm/examples/train_qwen38_flash_next_lora.py \
--data my_data.jsonl \
--seq-len 512 \
--epochs 1 \
--save-adapter qwen38-flash-next-lora.pt
The repository reports that Qwen3.8-Flash-Next, a 125B model, can train under 6 GB VRAM, and Qwen3.8-27B can train in approximately 2 GB at sequence length 512. github
When to use AirLLM-style inference
| Use case | Fit |
|---|---|
| Experimenting with a very large model on limited hardware | Strong fit |
| Offline batch inference where latency is not critical | Possible fit |
| Low-latency interactive production serving | Usually poor fit |
| High-throughput production API | Usually poor fit |
| Edge inference with abundant fast storage | Possible fit |
| Training or evaluating huge models on small GPUs | Strong fit |
AirLLM optimizes memory footprint, not necessarily end-to-end latency or throughput. Production systems usually prefer quantization, batching, parallelism, and KV-cache optimization when latency and throughput matter.
Part 5: Agent Harnesses
What is an agent harness?
An agent harness is everything around a frozen model that determines how it behaves in an agent system:
- System and task prompts.
- Control flow.
- Tools.
- Memory.
- Context management.
- Skills.
- Sub-agents.
- Configuration.
- Evaluation logic.
RRSI defines an LLM agent’s capability as largely determined by this harness. github
+----------------------------------------------------+
| Agent harness |
| |
| Prompt + control flow + tools + memory + context |
+-------------------------+--------------------------+
|
v
+------------------+
| Frozen LLM |
+------------------+
The model may remain fixed while the harness evolves.
Why harnesses matter
A powerful model can still perform poorly if its harness:
- Gives unclear instructions.
- Provides the wrong tools.
- Fails to manage context.
- Loses important memory.
- Uses poor control flow.
- Repeats failed strategies.
- Overfits to a narrow evaluation set.
RRSI argues that evolving a harness against a fixed evolve set is effective but prone to overfitting: gains on training tasks may shrink or disappear out of distribution. github
The RRSI approach
RRSI, or Regularized Recursive Self-Improvement, keeps the harness edit space open while regularizing the search trajectory through it. github
Current harness H_t
|
v
+----------------------+
| Analyst |
| Analyze failures |
+----------+-----------+
|
v
+----------------------+
| Proposer |
| Propose edits |
+----------+-----------+
|
v
+----------------------+
| Critic |
| Screen for leakage |
+----------+-----------+
|
v
+----------------------+
| Evaluator |
| Measure score, cost |
+----------+-----------+
|
v
+----------------------+
| Selector |
| Accept, reject, prune|
+----------+-----------+
|
v
Next harness H_t+1
This is a conceptual reconstruction of the RRSI improvement loop. github
What can be edited
RRSI allows edits to: github
- Prompts.
- Control flow.
- Configuration.
- Context management.
- Tools.
- Skills.
- Memory.
- Sub-agents.
The constraint is not on what the harness may contain, but on how the search moves through the space of possible harnesses. github
Regularization mechanisms
RRSI uses several mechanisms to reduce overfitting and wasteful search. github
| Mechanism | Purpose |
|---|---|
| Annealed edit budget | Limits how many independent edits a candidate can bundle |
| Full edit-history conditioning | Prevents revisiting falsified hypotheses |
| Stall detection | Redirects search toward unused components |
| Critic screening | Blocks suite-specific leakage before evaluation |
| Noise-adjusted floor | Rejects gains within evaluation variance |
| Cost rule | Requires added inference tokens to be paid for by measured gain |
| Component pruning | Removes components that stop helping |
| Novelty tracking | Encourages exploration of unused component types |
The cost rule is particularly important for production systems: a harness change that improves quality slightly but dramatically increases token cost may not be a real improvement.
Git-worktree evaluation
Every candidate harness is drafted, screened, and evaluated in its own Git worktree on a branch derived from evolve/<domain>. Accepting a candidate fast-forwards the branch, so the incumbent harness is always a commit. github
evolve/domain
|
+-- candidate worktree A
|
+-- candidate worktree B
|
+-- evaluation
|
+-- accept winner
|
v
evolve/domain advances
This provides auditable evidence: each edit records the component, hypothesis, measured score, cost change, and verdict. github
RRSI results
RRSI reports results with Claude Opus 4.8 as the frozen policy model, measured against the unevolved harness $H_0$. github
| Domain | Benchmark | Role | Baseline | RRSI | Change |
|---|---|---|---|---|---|
| Coding | Terminal-Bench 2.1 | Evolve | 74.2 | 80.2 | +6.0 |
| Coding | SWE-bench Verified | OOD | 82.0 | 83.8 | +1.8 |
| Agentic workspace | Harvey LAB | Evolve | 89.4 | 90.5 | +1.1 |
| Agentic workspace | Harvey LAB | In-distribution held-out | 86.9 | 89.2 | +2.3 |
| Agentic workspace | JobBench | OOD | 36.0 | 40.7 | +4.7 |
| Agentic workspace | GDPval | OOD | 48.8 | 52.3 | +3.5 |
| Agentic workspace | APEX-Agents | OOD | 34.2 | 37.9 | +3.7 |
| Engineering design | EngDesign | Evolve | 50.0 | 54.9 | +4.9 |
| Engineering design | Frontier-Eng | OOD | 17.7 | 22.0 | +4.3 |
RRSI also reports that, with Gemini 3.5 Flash as the frozen policy, the coding instance improves from 64.6 to 78.7 on Terminal-Bench 2.1 and from 76.8 to 79.0 on SWE-bench Verified. github
These results are specific to RRSI’s benchmarks, evaluation windows, models, and harness configurations. They should not be interpreted as universal improvements for every agent system.
Part 6: Production Inference Architecture
Reference production stack
Clients
|
v
+------------------+
| API gateway |
| Auth, rate limit |
+--------+---------+
|
v
+------------------+
| Router |
| Cache-aware route|
| Model routing |
+--------+---------+
|
v
+------------------+
| Queue / batcher |
+--------+---------+
|
v
+---------------------------+
| Inference replicas |
| vLLM / SGLang / TensorRT |
+--------+------------------+
|
v
+------------------+
| Observability |
| Metrics, traces |
+------------------+
Model routing
A production system may route requests to different models based on:
- Task complexity.
- Required latency.
- Confidence.
- Cost budget.
- Language.
- Modality.
- Available capacity.
- Cache affinity.
Request
|
v
Router
|
+-- simple task ---------> small model
|
+-- complex task --------> large model
|
+-- low confidence ------> reasoner
|
+-- high cache affinity -> cache-friendly replica
This is the same basic pattern used in decision cascades: use a fast path for most traffic and reserve expensive paths for uncertainty.
Capacity-aware fallback
Capacity-aware inference handles the case where a preferred instance type is unavailable or saturated. The system can fall back to another instance type while preserving availability.
A useful routing policy is:
Preferred GPU pool available?
|
+-- yes --> route to preferred pool
|
+-- no ---> fallback pool
|
+-- quality acceptable --> serve
|
+-- quality unacceptable -> queue, downgrade, or reject
This is general distributed-systems context; the AWS capacity-aware inference link in the source list should be consulted directly for its exact product behavior.
Deployment checklist
- Containerize the inference server.
- Pin model and dependency versions.
- Use health and readiness probes.
- Configure autoscaling on queue depth, concurrency, and GPU utilization.
- Set request timeouts and cancellation policies.
- Track model version in every response and log.
- Use blue-green or canary deployment for model updates.
- Load-test before launch.
- Monitor TTFT, TBT, throughput, error rate, cache hit rate, and cost.
- Maintain a rollback path.
The 100 Days project includes production Dockerfiles, NIM-compatible containers, autoscaling simulation, cold-start measurement, blue-green deployment, Prometheus metrics, Grafana dashboards, tracing, Locust load testing, and reusable benchmark harnesses. github
Part 7: Comparisons and Trade-Offs
Inference optimization techniques
| Technique | Primary benefit | Main cost | Best for |
|---|---|---|---|
| Continuous batching | Higher GPU utilization | More complex scheduling | High-concurrency serving |
| PagedAttention | Reduced KV-cache fragmentation | More complex memory management | Variable-length workloads |
| Prefix caching | Lower TTFT and cost for shared prefixes | Cache management complexity | Shared prompts and agents |
| Quantization | Lower memory and higher throughput | Potential quality loss | Memory- or cost-constrained serving |
| Speculative decoding | Lower decode latency | Extra draft-model compute | Latency-sensitive generation |
| Tensor parallelism | Larger models and faster compute | Communication overhead | Large dense models |
| Expert parallelism | Scales MoE models | Routing and load-balancing complexity | Sparse MoE models |
| Disaggregation | Independent prefill and decode scaling | More infrastructure complexity | Heterogeneous workloads |
| Layer streaming | Very low GPU memory footprint | Much higher latency | Memory-constrained experimentation |
Small fast model versus large streaming model
| Dimension | Small optimized model | Large model with layer streaming |
|---|---|---|
| Latency | Low | Often high |
| Throughput | High | Usually low |
| GPU memory | Low to moderate | Very low |
| Disk or host bandwidth | Lower | High |
| Capability | Limited by model size | Potentially much higher |
| Production complexity | Lower | Higher |
| Best use | Interactive production serving | Research, offline jobs, constrained hardware |
AirLLM demonstrates that very large models can run on small GPUs, but its layer-streaming approach is primarily a memory optimization rather than a latency optimization. github
Part 8: Limitations and Open Questions
Inference limitations
- KV-cache memory can become the dominant constraint for long contexts.
- Quantization can degrade quality, especially for sensitive tasks or low-bit formats.
- Speculative decoding helps only when draft proposals are accepted often enough.
- Parallelism introduces communication overhead and operational complexity.
- Autoscaling cannot eliminate cold starts entirely.
- Cost per token depends heavily on utilization, batching, cache reuse, and hardware generation.
Agent-harness limitations
- Harness optimization can overfit an evolve set.
- Evaluation noise can cause false improvements.
- More tools, memory, and sub-agents can increase cost and failure modes.
- A better harness does not fix a fundamentally weak base model.
- Automatic self-improvement requires strong leakage controls and auditable evaluation.
RRSI addresses some of these issues with critic screening, noise-adjusted floors, cost rules, pruning, and held-out evaluation, but these mechanisms do not eliminate the underlying risks. github
Open questions
- What is the optimal division of labor between a frozen model and an evolving harness?
- How should agent systems trade quality gains against token cost and latency?
- Can harness self-improvement generalize reliably across domains without task-specific guards?
- How should cache-aware routing balance prefix reuse against load balancing?
- When is layer streaming preferable to quantization or model distillation?
- How should production systems evaluate long-term agent value rather than short-term benchmark pass rate?
Resources
- 100 Days of LLM Inference — structured curriculum covering CUDA kernels, KV cache, vLLM, quantization, speculative decoding, parallelism, autoscaling, observability, and production deployment.
- AirLLM — layer-streaming inference and training for very large models on small GPUs.
- RRSI — regularized recursive self-improvement of agent harnesses.
- RRSI paper — research paper behind the RRSI repository.
- Pinterest VLM serving on NVIDIA Dynamo — recommended reading on production vision-language-model serving.
- Anyscale: Production-ready distributed inference with Ray Serve — recommended reading on distributed inference orchestration.
- AWS: Capacity-aware inference — recommended reading on instance fallback for managed endpoints.
- tiny-llm — recommended reading for implementing LLM inference components from scratch.
- ai-engineering-from-scratch — recommended reading for foundational AI engineering concepts.
Final Technical Takeaways
- Central mechanism: LLM inference performance is determined by the interaction of model architecture, KV cache, batching, kernels, precision, hardware, and request routing.
- Main runtime insight: Prefill and decode have different computational profiles; optimizing them separately through caching, batching, and disaggregation can materially improve serving efficiency. github
- Important memory insight: AirLLM reduces GPU memory by keeping only one layer resident at a time, enabling very large models on small GPUs at the cost of higher latency and storage bandwidth. github
- Important agent insight: An agent’s capability is shaped as much by its harness—prompts, tools, memory, context, and control flow—as by the frozen model itself. github
- Key production trade-off: Quality, latency, throughput, memory, and cost cannot all be maximized simultaneously; choose the constraint that matters most for the workload.
- Main limitation: Automatic self-improvement and aggressive inference optimization can overfit benchmarks or degrade quality unless supported by held-out evaluation, cost controls, and observability. github
- Broader engineering implication: Treat inference as a full-stack systems problem: optimize the runtime, design the infrastructure, and instrument both. github