LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 177 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/8
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/11
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageClustering and PCACore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/24
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernanceData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/16
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/19
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning & Test-Time Compute
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnProject Deep DivesDeep Dive - vLLM
🚀HardInference Optimization

Deep Dive - vLLM

Read vLLM as a living serving system: PagedAttention's memory idea, the V1 engine loop, block-pool caching, scheduling, kernels, APIs, and production tradeoffs.

20 min read
Learning path
Step 161 of 177 in the full curriculum
AI Lab Technical PresentationDeep Dive - SkyRL

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

When a chat service gets busy, GPU arithmetic usually isn't the first problem. Requests arrive with different prompt lengths, generate for different amounts of time, and hold different amounts of Key and Value (KV) state. A serving engine has to keep all those partial jobs moving without turning GPU memory into a fragmented heap.

vLLM is an open-source inference and serving engine built around that systems problem. Its public API can look like an OpenAI-compatible endpoint, but its interesting work happens below the HTTP boundary: scheduling tokens, mapping logical sequences to physical KV blocks, launching model runners, and returning streamed output. This lesson follows that path from request to kernel and back.

Use time to first token (TTFT), inter-token latency (ITL), and KV-cache occupancy to follow that path. TTFT measures the wait for the first generated token, ITL measures gaps between later tokens, and the KV cache holds per-request attention state that saves recomputation during decoding.

What vLLM is for

The project supports two broad entry paths. The LLM Python class runs offline batches in one process. The online server accepts requests, streams responses, and exposes OpenAI-compatible routes such as chat completions, completions, embeddings, scoring, and reranking.[1]Reference 1vLLM Architecture Overviewhttps://docs.vllm.ai/en/stable/design/arch_overview/[2]Reference 2Online Servinghttps://docs.vllm.ai/en/stable/serving/online_serving/

That makes vLLM useful for several workloads:

WorkloadWhy the engine helpsWhat to measure
Interactive chatMix short decodes with long promptsTTFT, ITL, tail latency
Code completionKeep many small sessions activeITL and scheduler delay
Retrieval-augmented generation (RAG)Reuse stable system and document prefixesPrefix-cache hit rate, prefill time
Batch generationFill GPU with different prompt lengthsTokens per second and queue wait
Multimodal requestsLoad media, tokenize, then run modelMedia limits, CPU load, end-to-end latency
Embedding or reranking serviceShare one engine shape across API routesBatch size, throughput, accuracy contract
Reinforcement-learning rolloutsExpose a fast generation endpoint to trainersGeneration throughput and weight version

Project identity

The project began in UC Berkeley's Sky Computing Lab around the PagedAttention paper. A broad open-source community now maintains it. Governance says committers earn authority through sustained contributions, reviews, and subsystem ownership; companies can participate, but committer status belongs to individuals.[3]Reference 3Efficient Memory Management for Large Language Model Serving with PagedAttention.https://arxiv.org/abs/2309.06180[4]Reference 4vLLM Governance Processhttps://github.com/vllm-project/vllm/blob/main/docs/governance/process.md

FieldCurrent project fact
OriginUC Berkeley's Sky Computing Lab; the PagedAttention paper names Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, and collaborators.[3]Reference 3Efficient Memory Management for Large Language Model Serving with PagedAttention.https://arxiv.org/abs/2309.06180
StewardshipThe vLLM Project community uses lead maintainers, committers, and area ownership rather than company seats.[4]Reference 4vLLM Governance Processhttps://github.com/vllm-project/vllm/blob/main/docs/governance/process.md
Contributor pathContributors earn committer status through sustained code, review, and subsystem work. Use the current governance roster instead of a static "top contributors" list.[4]Reference 4vLLM Governance Processhttps://github.com/vllm-project/vllm/blob/main/docs/governance/process.md
Source licenseApache-2.0 for the pinned source snapshot.[5]Reference 5vLLM Apache License 2.0https://github.com/vllm-project/vllm/blob/c67fe497a25d5af10a6ca0be9d18bcdd42cac4f1/LICENSE
Commercial boundaryCompanies fund, integrate, and operate vLLM, but participation doesn't turn the community repository into one vendor's product.[4]Reference 4vLLM Governance Processhttps://github.com/vllm-project/vllm/blob/main/docs/governance/process.md
Asset boundaryThe source license doesn't grant rights to model weights, tokenizers, datasets, or remote code loaded through the engine. Check each artifact separately.

That distinction matters when you evaluate vLLM. Its compatibility surface is intentionally wide, while its design values put performance, ease of use, hardware coverage, production readiness, and extensibility side by side. A feature can help one deployment and still need a different backend, topology, or security boundary in another.

The historical idea: page KV memory

Autoregressive generation appends one token at a time. For every request, attention needs the Key and Value vectors for all earlier tokens. A naive allocator reserves one contiguous KV-cache region for each request's maximum length. Most requests finish early, so those reservations leave holes unavailable to a different-length request. The memory is free in aggregate, but not free in the shape the allocator needs.

PagedAttention borrowed a familiar operating-system idea: split each sequence's KV state into fixed-size blocks and keep a logical block table. A logical sequence can grow from block 0 to block 1 without owning adjacent physical addresses. A kernel follows the table to load the right physical blocks when it computes attention.[3]Reference 3Efficient Memory Management for Large Language Model Serving with PagedAttention.https://arxiv.org/abs/2309.06180

Consider block size four and token IDs A B C D E F G:

Logical positionTokensPhysical block
0 to 3A B C D12
4 to 7E F G41

Request code sees one sequence. The GPU sees two physical block IDs. When the sequence grows, vLLM can allocate any free physical block instead of searching for four adjacent cache rows. The table is the indirection layer that makes fragmentation manageable.

Compact vLLM KV map: R0 and R1 logical four-token blocks point to non-contiguous physical slots; both first blocks share slot 12 with reference count 2, while suffixes use slots 41 and 73. An LRU queue shows zero-reference slots 88, 52, and 19 with 88 at the eviction head. Compact vLLM KV map: R0 and R1 logical four-token blocks point to non-contiguous physical slots; both first blocks share slot 12 with reference count 2, while suffixes use slots 41 and 73. An LRU queue shows zero-reference slots 88, 52, and 19 with 88 at the eviction head.
Two logical rows converge on physical slot 12 for the shared full prefix; distinct suffixes land in slots 41 and 73. The LRU row shows zero-reference blocks, with 88 at the eviction head.

The paper's 2023 experiments reported 2x to 4x throughput over FasterTransformer and Orca at comparable latency on the evaluated workloads.[3]Reference 3Efficient Memory Management for Large Language Model Serving with PagedAttention.https://arxiv.org/abs/2309.06180 Those numbers come from the paper's workloads and don't predict every model, GPU, or vLLM release. The lasting contribution is the memory layout and its scheduling consequences.

PagedAttention isn't one current backend

The paper's name remains useful shorthand, but today's vLLM has a backend matrix. V1 model runners select attention implementations for the model, hardware, data type, and feature set. A backend can use paged KV addresses while relying on a fused attention kernel, FlashAttention family kernel, Triton path, or a hardware plugin. Some model families, such as state-space or hybrid models, don't have the same KV semantics as a decoder-only Transformer.

The stable idea is the logical-to-physical contract. To learn which CUDA kernel a current request uses, inspect the V1 model runner and its attention backend registry, followed by the backend's block-table arguments and shape checks.

V1 request path: separate processes, one engine loop

V1 separates request handling from scheduling and GPU execution. The API server parses the request, tokenizes text, loads approved media, and streams results. It connects through ZMQ to all engine-core processes, one per data-parallel rank. Each engine core owns a scheduler and KV-cache manager, then dispatches work to one worker process per GPU. With data parallelism, API-server count defaults to the DP size and routing between API servers and engine cores is many-to-many; a conditional coordinator can balance ranks.[1]Reference 1vLLM Architecture Overviewhttps://docs.vllm.ai/en/stable/design/arch_overview/[6]Reference 6vLLM V1 User Guidehttps://docs.vllm.ai/en/stable/usage/v1_guide/

Diagram showing 1. API server HTTP + tokenize, 2. Engine core request queue, 3. Unified scheduler token budget, and 4. KV block pool reserve + map. Diagram showing 1. API server HTTP + tokenize, 2. Engine core request queue, 3. Unified scheduler token budget, and 4. KV block pool reserve + map.
1. API server HTTP + tokenize, 2. Engine core request queue, 3. Unified scheduler token budget, and 4. KV block pool reserve + map.
Compact vLLM V1 graph: API, engine core, scheduler, KV block pool, and GPU worker nodes pass one request forward; a stream node returns output to the API. A six-token bar allocates one decode token and five prefill tokens. Compact vLLM V1 graph: API, engine core, scheduler, KV block pool, and GPU worker nodes pass one request forward; a stream node returns output to the API. A six-token bar allocates one decode token and five prefill tokens.
A selected request moves API → engine core → scheduler → KV pool → GPU, then returns through the stream path. The six-token step reserves 1 decode token and 5 prefill tokens.

The process-count formula is concrete. Let A be API-server count, DP data-parallel size, and N total GPUs. V1 starts A + DP + N, plus one coordinator when DP > 1. A four-GPU, single-replica deployment is one API server, one engine core, and four GPU workers: six processes. With TP=2 and DP=4 on eight GPUs, the documented example has four API servers, four engine cores, eight workers, and one coordinator: 17 processes.[1]Reference 1vLLM Architecture Overviewhttps://docs.vllm.ai/en/stable/design/arch_overview/

This split makes failures easier to place. A slow tokenizer or media download is API-server work. Scheduler delay and block allocation are engine-core work. A kernel launch, CUDA graph, or tensor-parallel collective is worker work. CPU limits matter because every process participates in the hot path; V1's optimization guide calls out engine-core scheduling latency and worker CPU resources as throughput factors.[7]Reference 7Optimization and Tuning.https://docs.vllm.ai/en/latest/configuration/optimization.html

The V1 scheduler: one token budget

Older serving designs often described prefill and decode as separate queues. V1 represents both with a request-to-token count and schedules against a fixed token budget. A decode request may need one new token. A new prompt may need hundreds, but chunked prefill lets the scheduler admit only a slice. The same allocation interface can therefore combine decode, prefill, prefix hits, and speculative work.[6]Reference 6vLLM V1 User Guidehttps://docs.vllm.ai/en/stable/usage/v1_guide/

Here is a small trace with max_num_batched_tokens = 6:

StepReady workScheduler choiceWhy
0Decode R0 needs 1; prefill R1 needs 91 token from R0, 5 from R1Keep decode moving, start a chunk
1Decode R0 needs 1; R1 has 4 left1 token from R0, 4 from R1Finish prefill within budget
2Decode R0 needs 1; R1 can decode1 token eachBoth requests now decode

These counts illustrate the scheduler's token budget; they are not benchmark results. The script models decode-first selection followed by one prefill slice, so changing the budget shows which work remains.

token-budget-trace.py
1budget = 6 2decode_tokens = 1 3prefill_remaining = 9 4 5decode_now = min(decode_tokens, budget) 6prefill_now = min(prefill_remaining, budget - decode_now) 7 8print(f"decode now: {decode_now}") 9print(f"prefill now: {prefill_now}") 10print(f"prefill remaining: {prefill_remaining - prefill_now}") 11print(f"budget used: {decode_now + prefill_now}/{budget}")
Output
1decode now: 1 2prefill now: 5 3prefill remaining: 4 4budget used: 6/6

Continuous batching and chunked prefill

Continuous batching means a request can join or leave the active set between model steps. The batch isn't a fixed list of sequences built once at the beginning. V1 prioritizes pending decodes, then fills unused budget with prefills. If a prompt doesn't fit, it gets split into chunks. Smaller budgets tend to protect ITL; larger budgets tend to improve TTFT by doing more prompt work per step.[7]Reference 7Optimization and Tuning.https://docs.vllm.ai/en/latest/configuration/optimization.html

Tune max_num_batched_tokens against the service SLO. Code-completion services with strict ITL may prefer a smaller cap, while batch document summarizers may prefer larger prefill slices. Frequent preemptions call for more KV capacity or fewer active sequences alongside any token-cap change.

When KV blocks run out, V1's default preemption mode is recompute. The engine releases a request's blocks, keeps enough request state to retry, and recomputes the prefix when capacity returns. Recompute avoids swap traffic in this architecture, but it adds latency and duplicated compute. Monitor cumulative preemptions, KV usage, queue wait, TTFT, and ITL together.[7]Reference 7Optimization and Tuning.https://docs.vllm.ai/en/latest/configuration/optimization.html

Block pool, prefix cache, and eviction

The block pool is preallocated when the KV-cache manager starts. Each KVCacheBlock has an immutable physical ID, a hash once full, a reference count, and pointers for a doubly linked free queue. The cache maps block hashes to physical IDs. A request maps its own ID to the block IDs it currently uses.[8]Reference 8Automatic Prefix Cachinghttps://docs.vllm.ai/en/latest/features/automatic_prefix_caching/

The prefix hash is chained. Conceptually:

text
1block_hash = H(parent_hash, block_tokens, extra_hashes) 2extra_hashes = LoRA IDs + multimodal hashes + optional cache_salt

Including the parent means the same block tokens after different prefixes don't collide semantically. Including exact tokens reduces accidental matches. Extra hashes distinguish a multimodal input, adapter, or trust group.

Automatic Prefix Caching (APC) reuses only full blocks. Suppose block size is four and two requests share the first eight tokens. The second request can touch the first two cached blocks, increment their reference counts, and allocate fresh blocks for its nonmatching suffix. A seven-token shared prefix still hits only the first four-token block; the partially matching second block must be recomputed.[8]Reference 8Automatic Prefix Cachinghttps://docs.vllm.ai/en/latest/features/automatic_prefix_caching/

Reference counts protect live requests. When a request finishes, blocks with count zero move to the tail of the free queue. The next allocation pops the head, which is the least-recently-used (LRU) candidate. If that block is cached, vLLM removes its hash before reusing the physical storage. The reverse-free ordering makes recently completed suffix blocks more likely to leave first because longer suffixes are less likely to be reused.[8]Reference 8Automatic Prefix Cachinghttps://docs.vllm.ai/en/latest/features/automatic_prefix_caching/

Cache salt adds a trust boundary. A tenant can send a salt that participates in the first block hash, so another tenant with the same text but a different salt won't reuse its KV data. Salt doesn't encrypt memory or replace authorization; it reduces timing-based prefix-content inference when callers share an engine.[8]Reference 8Automatic Prefix Cachinghttps://docs.vllm.ai/en/latest/features/automatic_prefix_caching/

From scheduler output to GPU kernels

The engine core emits a scheduler output containing request IDs, token counts, block tables, sampling metadata, and model-execution inputs. GPU workers receive that output and the model runner prepares tensors for the selected model. The runner owns weight loading, input layout, CUDA graph capture or eager execution, forward calls, and sampling handoff.

At the attention boundary, the runner supplies logical sequence lengths and physical block IDs. The backend turns those into memory addresses. At the model boundary, parallelism controls how weights and layers are distributed:

KnobSplitMain benefitMain cost
Tensor parallelism (TP)Matrix dimensions across GPUsOne request uses more memory and computeCollectives in each layer
Pipeline parallelism (PP)Layer depth across stagesFit deeper models or cross nodesPipeline bubbles and stage latency
Data parallelism (DP)Full replicas across request groupsMore independent throughputMore weight memory and routing
Expert parallelism (EP)Mixture-of-Experts expertsBalance expert computeRouting and communication

V1 exposes those costs. A larger TP group can leave more memory for KV blocks, but every decode step may pay all-reduce latency. A larger PP group can fit the model while exposing bubbles at low concurrency. DP adds engine cores and API servers. Benchmark each topology on target hardware because more GPUs can hurt small or low-concurrency workloads.[1]Reference 1vLLM Architecture Overviewhttps://docs.vllm.ai/en/stable/design/arch_overview/[7]Reference 7Optimization and Tuning.https://docs.vllm.ai/en/latest/configuration/optimization.html

The model runner also explains why vLLM can support many model families without copying an entire engine. A shared configuration object carries model, scheduler, cache, and parallelism choices. Model implementations expose a common runner contract while backend registries select hardware-specific kernels. That modularity is a strength for contributors, but compatibility is a matrix: model architecture, dtype, quantization, attention backend, and feature flags can interact.

APIs and the boundary of trust

The online server offers OpenAI-compatible JSON, but compatibility isn't the same as a complete security boundary. The documented API-key flag protects many /v1 inference routes, yet health, metrics, and other endpoints can remain unauthenticated. Put vLLM behind an authenticated gateway, restrict management routes, and expose only the API surface clients need.[9]Reference 9Securityhttps://docs.vllm.ai/en/stable/usage/security/[2]Reference 2Online Servinghttps://docs.vllm.ai/en/stable/serving/online_serving/

For multimodal requests, media URLs are an input capability. Allowlist domains and cap decoded image pixels, audio size, and audio duration. Otherwise an untrusted URL can target internal services (server-side request forgery, or SSRF), download a huge file, or expand compressed media into an out-of-memory event.[9]Reference 9Securityhttps://docs.vllm.ai/en/stable/usage/security/

Multi-node communication is insecure by default. PyTorch distributed, KV transfer, and tensor, pipeline, or data-parallel links don't provide an authorization protocol or encryption suitable for an untrusted network. Isolate those ports, set explicit host addresses, and firewall internal interfaces. An API key on /v1/chat/completions can't protect a reachable process-group port.[9]Reference 9Securityhttps://docs.vllm.ai/en/stable/usage/security/

Strengths and weaknesses

DimensionStrengthBoundary or weakness
MemoryFixed KV blocks, reuse, LRU evictionBlock metadata and page-table work add CPU complexity
SchedulingContinuous batching and one token budgetWrong cap can trade ITL against TTFT or trigger preemption
Model coverageShared runner plus many backendsNew models need backend and feature-matrix work
APIFamiliar OpenAI-compatible routesCompatibility doesn't secure every endpoint or behavior
HardwareNVIDIA, AMD, CPU, and plugin pathsTuning and kernel quality vary by platform and dtype
CommunityMeritocratic, multi-company governanceFast change means defaults and support status evolve
ScaleTP, PP, DP, EP, and cache transfer optionsCross-node links need isolation and can dominate latency

vLLM combines block-based KV memory, token scheduling, and specialized kernels. Each layer has its own tuning and failure modes, so production debugging needs traces and metrics rather than one throughput number.

Code-reading route

Use the local repository as a map. Read these files in order, and keep one request ID in your head:

  1. vllm/entrypoints/openai/api_server.py: HTTP request parsing, input processing, and streaming boundary.
  2. vllm/v1/engine/core.py: engine-core loop and handoff to workers.
  3. vllm/v1/core/sched/scheduler.py: token-budget scheduling, preemption, and scheduler output.
  4. vllm/v1/core/kv_cache_manager.py: computed-block lookup, allocation, touch, and free operations.
  5. vllm/v1/core/block_pool.py: physical block pool, free queue, hash map, and LRU behavior.
  6. vllm/v1/worker/gpu_model_runner.py: input tensors, model execution, graphs, and output preparation.

While reading, write down three invariants:

  • A request's logical token order is independent of physical block addresses.
  • A cached block can be reused only when its full hash and extra context match.
  • A worker can't execute tokens that the scheduler hasn't assigned and backed with block capacity.

A small failure drill

Suppose a dashboard shows rising ITL, low GPU utilization, and a growing preemption counter. Don't start by changing the attention kernel. Check, in order:

  1. KV-cache usage and free-block count. If blocks are exhausted, recompute work may be stealing GPU time.
  2. max_num_batched_tokens, max_num_seqs, and prompt-length distribution. An oversized active set can create a thrash loop.
  3. Engine-core CPU saturation and scheduler latency. V1's process split can make CPU starvation look like a GPU problem.
  4. TP and PP topology. A new parallelism size can add collective or pipeline wait.
  5. Prefix-cache hit rate. A workload with unique prompts won't benefit from APC, no matter how large the cache is.

For a request that never gets its first token, break TTFT into queue wait, scheduler delay, prefill compute, and worker launch time.

Research roots and current practice

The PagedAttention paper explains the original memory-management insight and its 2023 throughput evaluation.[3]Reference 3Efficient Memory Management for Large Language Model Serving with PagedAttention.https://arxiv.org/abs/2309.06180 The vLLM repository describes the practical engine that grew around it.[10]Reference 10vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttentionhttps://github.com/vllm-project/vllm Current architecture and V1 guides document the process split and unified scheduler, while optimization and prefix-caching guides describe chunking, recompute, hashes, reference counts, and LRU behavior.[1]Reference 1vLLM Architecture Overviewhttps://docs.vllm.ai/en/stable/design/arch_overview/[6]Reference 6vLLM V1 User Guidehttps://docs.vllm.ai/en/stable/usage/v1_guide/[7]Reference 7Optimization and Tuning.https://docs.vllm.ai/en/latest/configuration/optimization.html[8]Reference 8Automatic Prefix Cachinghttps://docs.vllm.ai/en/latest/features/automatic_prefix_caching/

Read those sources with dates in mind. vLLM V1 replaces older V0 assumptions, and backend support changes as models and accelerators change. A paper result can remain historically important without being a current service target. A documentation default can be correct for today's release and still need rechecking before a production rollout.

Key takeaways

  • vLLM treats serving as a joint scheduling and memory problem.
  • PagedAttention's logical-to-physical blocks reduce fragmentation; it doesn't name every current attention kernel.
  • V1's API server, engine core, and GPU workers separate request I/O, scheduling, cache management, and execution.
  • One token budget enables continuous batching, chunked prefill, and shared scheduling decisions.
  • APC hashes full blocks, protects live blocks with reference counts, and evicts zero-reference blocks through an LRU queue.
  • TP, PP, DP, and EP solve different fit and throughput constraints, each with communication or bubble costs.
  • Serving design must cover API keys, network isolation, media allowlists, and metrics.

Before moving on, explain one request from HTTP parse to streamed token without looking at the Mermaid diagram. Then explain what changes when its first eight tokens hit APC and what still has to run for every generated token.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.What does PagedAttention add to the logical sequence model?
2.In the documented single-node example with four GPUs and data parallel size one, how many V1 processes are counted?
3.Why does V1 chunk a long prefill when decode requests are waiting?
4.Which prefix can APC reuse?
5.What does a zero reference count mean in the block pool?
6.What is a likely cost of increasing tensor-parallel size for decode?
7.A service has low APC hits and no preemptions. Which conclusion is best?
8.Why should a multi-node vLLM deployment isolate internal ports even when the HTTP API has an API key?

8 questions remaining.

Next Step
Continue to Deep Dive - SkyRL

vLLM showed how a serving engine schedules requests, memory blocks, and GPU work. SkyRL tackles a different system: coordinating rollouts, environments, inference, and reinforcement-learning updates.

PreviousAI Lab Technical Presentation
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

vLLM Architecture Overview

vLLM Project · 2026

Online Serving

vLLM Project · 2026

Efficient Memory Management for Large Language Model Serving with PagedAttention.

Kwon, W., et al. · 2023 · SOSP 2023

vLLM Governance Process

vLLM Project · 2026

vLLM Apache License 2.0

vLLM Project · 2026

vLLM V1 User Guide

vLLM Project · 2026

Optimization and Tuning.

vLLM · 2026

Automatic Prefix Caching

vLLM · 2026

Security

vLLM Project · 2026

vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention

vLLM Team · 2024

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.