DeepSeek Inference Acceleration In-Depth Tutorial
Comprehensively master DeepSeek model inference acceleration techniques. In-depth comparison of four major engines: vLLM, SGLang, TensorRT-LLM, llama.cpp, from deployment to tuning, from single GPU to distributed, a complete inference acceleration solution.
Start LearningWhy is inference acceleration needed?
DeepSeek-V3 has 671B parameters, and DeepSeek-R1 is driven by reinforcement learning for reasoning capabilities. With such a large model, using native PyTorch for inference is extremely inefficient. Dedicated inference engines can increase inference throughput by 10-50 times and reduce latency by over 80% through techniques such as KV Cache optimization, Continuous Batching, quantization compression, and operator fusion.
Inference Engine Overview
The inference engine is the middle layer that connects trained model weights with production inference requests. It is responsible for memory management, batch scheduling, and computation optimization, and is the core component that determines inference performance and cost.
Key Metrics for Inference Performance
| Throughput | Total number of tokens processed per unit time (tokens/s). Measures the overall processing capability of the system; higher is better. |
| Time to First Token (TTFT) | Time from sending the request to receiving the first token. A key metric affecting user experience. |
| Time Per Output Token (TPOT) | Average time to generate each token. Affects the smoothness of streaming output. |
| VRAM Usage | GPU memory (GB) occupied during model loading and inference. Directly affects the deployable model size and batch size. |
Mainstream Inference Engine Ecosystem
| Engine | Developer | Core Advantages | Use Cases |
|---|---|---|---|
| vLLM | UC Berkeley | PagedAttention memory management, extremely high throughput | Production API services |
| SGLang | Stanford/LMSYS | RadixAttention prefix caching, structured generation | Multi-turn dialogue, Agent scenarios |
| TensorRT-LLM | NVIDIA | Extreme GPU optimization, FP8/INT4 quantization | Extreme performance on NVIDIA GPUs |
| llama.cpp | ggerganov | CPU/GPU hybrid inference, GGUF quantization | Personal computers, edge devices |
Core Technology Stack for Inference Acceleration
- KV Cache Management: Cache the computed Key-Value matrices to avoid redundant computation. PagedAttention manages KV Cache in pages, improving memory utilization by 2-4x.
- Continuous Batching: Dynamic batching; requests are replaced immediately upon completion, keeping GPU utilization consistently high.
- Quantization: Compress FP16 weights to INT8/INT4/FP8, reducing memory usage by 50%-75% with minimal accuracy loss.
- Kernel Fusion: Merge multiple CUDA kernels into one, reducing memory reads/writes and improving computational efficiency.
- Tensor Parallelism: Split layer weights across multiple GPUs to break through single-GPU memory limits.
- Speculative Decoding: Use a small model to quickly generate candidate tokens, and a large model to verify, speeding up by 2-3x.
Selection Recommendations
For production API services, vLLM is the first choice; for multi-turn dialogue and Agent scenarios, SGLang is recommended; for extreme GPU performance, choose TensorRT-LLM; for personal computers and edge devices, use llama.cpp. For more model details, see DeepSeek Model Architecture Details.
Deploy DeepSeek with vLLM
vLLM is currently the most popular open-source inference engine, developed by UC Berkeley. Its core innovation, PagedAttention, manages KV Cache like operating system paging, increasing GPU memory utilization by 2-4x and throughput by 10-30x.
PagedAttention Principle
Traditional inference engines pre-allocate contiguous GPU memory for each request to store KV Cache, leading to severe memory fragmentation and waste (utilization only 20%-40%). PagedAttention divides KV Cache into fixed-size blocks, allocates on demand, and dynamically maps them, achieving memory utilization over 96%.
- KV Cache Blocking: Each block stores Key and Value vectors for a fixed number of tokens
- On-demand Allocation: Blocks are allocated only when requests arrive, no pre-allocation of contiguous space
- Memory Sharing: In parallel sampling and Beam Search scenarios, KV Cache for the same prompt can be shared
- Copy-on-Write: Blocks are copied only when written, maximizing sharing
vLLM Installation and Configuration
DeepSeek-V3/R1 Deployment Commands
DeepSeek-V3 and R1 are 671B-parameter MoE models that require multi-GPU deployment. Below are complete commands for deploying with vLLM:
vLLM Performance Tuning Parameters
| Parameter | Description | Recommended Value |
|---|---|---|
| --max-num-seqs | Maximum number of concurrent requests | 128-256 |
| --max-num-batched-tokens | Maximum number of tokens per batch | 8192-16384 |
| --gpu-memory-utilization | GPU memory utilization upper limit | 0.90-0.95 |
| --enable-prefix-caching | Enable prefix caching (shared prompts automatically reuse KV Cache) | Enabled |
| --enable-chunked-prefill | Chunked prefill, long prompts do not block other requests | Enabled |
Python API Call Example
Tip
vLLM's OpenAI-compatible API can directly replace any application using the OpenAI SDK without modifying code logic. In production, it is recommended to use Nginx for load balancing and rate limiting.
Deploy DeepSeek with SGLang
SGLang, jointly developed by Stanford University and the LMSYS organization, is a next-generation inference engine for LLM services. Its core innovations, RadixAttention and structured generation language, significantly outperform vLLM in complex prompt scenarios.
How RadixAttention Works
RadixAttention is an automatic KV Cache reuse technology based on a prefix tree (Radix Tree). Traditional KV Cache can only be reused per request, while RadixAttention automatically identifies common prefixes between different requests and reuses the cache, greatly improving performance in scenarios such as few-shot learning, multi-turn dialogue, and Agent.
- Prefix tree storage: KV Caches of all requests are organized into a tree structure by prefix
- Automatic matching: When a new request arrives, it automatically matches the longest common prefix and reuses the KV Cache
- LRU eviction: Uses LRU strategy to manage cache, maximizing cache hit rate under memory constraints
- No configuration: RadixAttention works fully automatically, no manual prefix setting required
SGLang Installation and Configuration
DeepSeek Deployment Commands
SGLang Frontend Programming Language
SGLang provides a DSL (Domain-Specific Language) that allows declaratively writing complex LLM interaction logic in Python, automatically implementing optimizations such as prefix caching and parallel calls:
Prefix Cache Optimization Effect
| Scenario | TTFT without cache | TTFT with cache | Speedup |
|---|---|---|---|
| Multi-turn dialogue (5 turns) | 450ms | 120ms | 3.75x |
| Few-shot prompting (10-shot) | 820ms | 150ms | 5.46x |
| Agent tool calling | 380ms | 90ms | 4.22x |
Deploying DeepSeek with TensorRT-LLM
TensorRT-LLM is NVIDIA's official inference engine, deeply integrated with the CUDA and TensorRT ecosystem. Through graph optimization, kernel auto-tuning, and quantization techniques, it achieves the highest inference performance on NVIDIA GPUs.
Key Features of TensorRT-LLM
- Graph Optimization: Automatically performs layer fusion, constant folding, dead code elimination, and other computational graph optimizations
- Kernel Auto-Tuning: Automatically selects the optimal CUDA kernel for specific GPU architectures (H100/A100/L40S)
- Native FP8 Support: H100's FP8 Tensor Core acceleration, doubling throughput
- INT4/INT8 Quantization: Supports Weight-Only and SmoothQuant quantization schemes
- In-flight Batching: NVIDIA's implementation of Continuous Batching, resulting in lower latency
Installing TensorRT-LLM
Model Compilation and Conversion
TensorRT-LLM requires converting the Hugging Face model to TensorRT Engine format first:
DeepSeek FP8 Quantized Inference
H100 GPUs support native FP8 computation, and with TensorRT-LLM, near-lossless quantized inference can be achieved:
INT4 Weight-Only Quantization
For memory-constrained scenarios, INT4 quantization can compress the model size by 75%:
TensorRT-LLM Use Cases
TensorRT-LLM is best suited for production scenarios that require pure NVIDIA GPU environments and ultimate inference performance. The downside is that the deployment process is complex, requiring model compilation steps, and it is less flexible than vLLM and SGLang. If you use Triton Inference Server as your inference platform, TensorRT-LLM is the preferred backend.
llama.cpp Local Inference
llama.cpp is an inference engine implemented in pure C/C++, optimized for CPU and edge devices. Through the GGUF quantization format, DeepSeek distilled models can run on ordinary laptops without high-end GPUs.
GGUF Quantization Format
GGUF (GGML Unified Format) is the model file format used by llama.cpp, supporting multiple quantization levels:
| Quantization Type | Bit Width | File Size Ratio | Quality | Recommended Use Case |
|---|---|---|---|---|
| Q4_K_M | ~4.5 bit | ~25% | Excellent | Best value, recommended first choice |
| Q5_K_M | ~5.5 bit | ~30% | Excellent | For higher quality |
| Q8_0 | 8 bit | ~50% | Almost lossless | Use when VRAM is sufficient |
| IQ3_M | ~3.5 bit | ~20% | Good | Extremely limited VRAM |
Installing llama.cpp
DeepSeek Model GGUF Download and Deployment
Python Bindings Call
Apple Silicon (Metal) Optimization
llama.cpp has special Metal optimizations for Apple Silicon chips (M1/M2/M3/M4), leveraging the unified memory architecture for GPU acceleration:
Personal Computer Deployment Guide
| Hardware Configuration | Recommended Model | Quantization | Expected Speed |
|---|---|---|---|
| 16GB RAM + RTX 4060 | DeepSeek-R1-Distill-Qwen-7B | Q4_K_M | 30-50 tok/s |
| 32GB RAM + RTX 4090 | DeepSeek-R1-Distill-Qwen-32B | Q4_K_M | 20-35 tok/s |
| M3 Max 36GB | DeepSeek-R1-Distill-Qwen-32B | Q4_K_M | 15-25 tok/s |
| M2 Ultra 64GB | DeepSeek-R1-Distill-Llama-70B | Q4_K_M | 8-15 tok/s |
Inference Engine Performance Comparison
The four inference engines show significant performance differences across various scenarios. The following benchmark data is based on the DeepSeek-R1-Distill-Llama-70B model, tested on 2x A100 80GB with a batch size of 64.
Throughput Comparison (tokens/s)
| Engine | Input 128 tok | Input 512 tok | Input 2048 tok | Output 256 tok |
|---|---|---|---|---|
| vLLM (FP16) | 3,420 | 2,890 | 2,150 | 2,680 |
| SGLang (FP16) | 3,510 | 3,120 | 2,380 | 2,920 |
| TensorRT-LLM (FP8) | 5,820 | 4,950 | 3,680 | 4,580 |
| llama.cpp (Q4) | 580 | 420 | 280 | 380 |
Latency Comparison (TTFT, ms)
| Engine | Idle TTFT | 16 Concurrent TTFT | 64 Concurrent TTFT | TPOT |
|---|---|---|---|---|
| vLLM (FP16) | 85ms | 210ms | 580ms | 32ms |
| SGLang (FP16) | 72ms | 185ms | 510ms | 28ms |
| TensorRT-LLM (FP8) | 80ms | 195ms | 530ms | 30ms |
| llama.cpp (Q4) | 1,250ms | 2,800ms | 8,500ms | 180ms |
GPU Memory Usage Comparison (GB)
| Engine | Model Weights | KV Cache | Other Overhead | Total |
|---|---|---|---|---|
| vLLM (FP16) | 140GB | 12GB | 4GB | 156GB |
| SGLang (FP16) | 140GB | 10GB | 4GB | 154GB |
| TensorRT-LLM (FP8) | 70GB | 6GB | 3GB | 79GB |
| llama.cpp (Q4) | 38GB | 4GB | 2GB | 44GB |
Benchmark Conclusions
- TensorRT-LLM FP8 achieves the highest throughput and lowest memory usage on NVIDIA GPUs.
- SGLang offers the lowest latency in long-context and multi-turn conversation scenarios (thanks to RadixAttention).
- vLLM has the most mature ecosystem, the most active community, and is the easiest to deploy.
- llama.cpp performs far worse than the previous three in GPU environments, but offers the best experience on CPU and edge devices.
Deep Dive into Quantized Inference
Quantization is one of the most important techniques for inference acceleration. By reducing the numerical precision of model weights, memory usage can be reduced by 50%-75%, while accuracy loss is typically kept within 1%.
Comparison of Quantization Methods
| Quantization Method | Bit Width | Compression Ratio | Accuracy Loss | Supported Engines |
|---|---|---|---|---|
| AWQ | INT4 | 4x | < 0.5% | vLLM, TensorRT-LLM, SGLang |
| GPTQ | INT4 | 4x | < 1% | vLLM, TensorRT-LLM |
| GGUF | 2-8 bit | 2-8x | < 1% (Q4+) | llama.cpp |
| FP8 | 8 bit | 2x | Almost lossless | TensorRT-LLM (H100) |
| SmoothQuant | INT8 | 2x | < 0.5% | TensorRT-LLM |
AWQ Quantization Principle and Usage
AWQ (Activation-aware Weight Quantization) identifies and protects important weight channels by analyzing the distribution of activations, achieving high-precision INT4 quantization without calibration:
Memory Savings Calculation
| Model | FP16 Memory | FP8 Memory | INT4 Memory | Savings |
|---|---|---|---|---|
| DeepSeek-V3 (671B) | 1,342 GB | 671 GB | 336 GB | 75% |
| R1-Distill-Llama-70B | 140 GB | 70 GB | 35 GB | 75% |
| R1-Distill-Qwen-32B | 64 GB | 32 GB | 16 GB | 75% |
| R1-Distill-Qwen-7B | 14 GB | 7 GB | 3.5 GB | 75% |
Quantization Accuracy Loss Analysis
- FP8: Accuracy loss is almost zero (< 0.1%), because FP8 uses floating-point representation with a large dynamic range. However, it requires hardware supporting FP8 such as H100/H200.
- INT8 (SmoothQuant): Accuracy loss is < 0.5%, achieved by smoothing outliers in activations. It has good generality and works on both A100 and H100.
- INT4 (AWQ): Accuracy loss < 0.5%, protects important channels by analyzing activation value distribution. Currently the most recommended INT4 solution
- INT4 (GPTQ): Accuracy loss < 1%, requires calibration data, but the quantization process is more stable
- Q4_K_M (GGUF): Accuracy loss < 1%, widely used in the llama.cpp ecosystem, best cost-performance
Quantization Selection Recommendations
If you have H100, prefer FP8 (highest throughput); for A100 environments, AWQ INT4 is recommended (significant VRAM savings and high accuracy); for personal computers, use GGUF Q4_K_M (small file size, good compatibility). Reducing VRAM by 75% means you can deploy the same model with far fewer GPUs, or serve more concurrent users on the same hardware.
Batching and Concurrency Optimization
Batching is the core determinant of inference engine throughput. From static batching to Continuous Batching, and then to Chunked Prefill, each evolution in batching technology has brought significant performance improvements.
Comparison of Three Batching Methods
| Batching Method | Principle | GPU Utilization | Applicable Engines |
|---|---|---|---|
| Static Batching | Wait for a fixed number of requests then process together, release only after the slowest request completes | Low (30-50%) | HuggingFace TGI (old version) |
| Dynamic Batching | Requests join the batch as they arrive, but release only after all requests complete | Medium (50-70%) | ONNX Runtime |
| Continuous Batching | After each token generation, check immediately; completed requests are removed immediately, new requests are added immediately | High (80-95%) | vLLM, SGLang, TensorRT-LLM |
Continuous Batching Workflow
- Iteration-level scheduling: Re-evaluate the batch queue after each token generation, rather than waiting for the entire sequence to complete
- Immediate replacement: When a request completes, it is immediately removed from the batch, and GPU resources are immediately allocated to waiting new requests
- Preemptive scheduling: Supports priority queues; high-priority requests can preempt compute resources from low-priority requests
- Fair scheduling: Prevents long-sequence requests from starving short-sequence requests, ensuring fairness through round-robin or weighted scheduling
Chunked Prefill Optimization
When users send long prompts (e.g., 100K token document analysis), the Prefill phase consumes significant compute resources, causing other requests to wait. Chunked Prefill splits the Prefill of long prompts into multiple small chunks, interleaving them with Decode requests:
Concurrent User Optimization Strategies
| Strategy | Description | Effect |
|---|---|---|
| max-num-seqs | Set the maximum number of concurrent sequences, adjust according to VRAM capacity | 128-256 is optimal |
| Queueing Policy | FIFO (First In, First Out) vs Priority vs Shortest-Job-First | SJF has the lowest average latency |
| Request Rate Limiting | Limit the number of concurrent requests via API gateway to prevent overload | Improved stability |
| Timeout and Retry | Set reasonable timeout (30-60s) with exponential backoff retry | Improved user experience |
Request Scheduling Engine Configuration
Distributed Inference
DeepSeek-V3 has 671B parameters, requiring 336GB of VRAM even with INT4 quantization, far exceeding the capacity of a single GPU. Distributed inference makes it possible to run such large models by coordinating multiple GPUs and nodes.
Tensor Parallelism
Tensor Parallelism splits the weight matrices of a single Transformer layer across multiple GPUs, either by columns or rows. Each GPU computes a portion, and results are aggregated via AllReduce communication:
- Column-wise splitting: Split the weight matrix W into [W1, W2, ..., Wn] by columns. Each GPU holds W_i, computes independently, then aggregates via AllReduce
- Row-wise splitting: Split the weight matrix by rows. Each GPU computes partial outputs, then concatenates via AllGather
- Communication overhead: Each Transformer layer requires 2 AllReduce operations, demanding high NVLink bandwidth. It is recommended to use GPU groups interconnected with NVLink
- Optimal GPU count: Typically 2-8 GPUs. Beyond 8, communication overhead begins to outweigh computational gains
Pipeline Parallelism
Pipeline Parallelism splits the model by layers across multiple GPUs, forming a pipeline. GPU0 processes the first N layers, GPU1 the middle N layers, GPU2 the last N layers:
- Layer-wise splitting: Communication only occurs at pipeline stage boundaries, with much lower communication volume than Tensor Parallelism
- Micro-Batch: Split large batches into multiple micro-batches. Pipeline stages process different micro-batches simultaneously
- Pipeline bubbles: GPU idle time exists during pipeline startup and drain. Increasing the number of micro-batches reduces the bubble ratio
- Use cases: Cross-node inference (limited inter-node bandwidth), can be combined with Tensor Parallelism
DeepSeek-V3 671B Distributed Deployment Options
| Option | GPU Configuration | Parallelism Strategy | Expected Throughput |
|---|---|---|---|
| 8x H100 80GB (FP8) | Single node, 8 GPUs | TP=8 | 3,500 tok/s |
| 16x A100 80GB (FP8) | 2 nodes x 8 GPUs | TP=8, PP=2 | 4,800 tok/s |
| 16x A100 80GB (INT4) | 2 nodes x 8 GPUs | TP=4, PP=4 | 5,200 tok/s |
| 32x H100 80GB (FP8) | 4 nodes x 8 GPUs | TP=8, PP=4 | 8,500 tok/s |
vLLM Multi-Node Deployment Commands
Special Considerations for MoE Models
DeepSeek-V3 uses the MoE (Mixture of Experts) architecture, where each token only activates a subset of experts (approximately 37B parameters), providing unique opportunities for inference optimization:
- Expert Parallelism: Distribute different experts across different GPUs, each token only accesses a subset of GPUs, reducing communication overhead.
- Expert Load Balancing: Use Auxiliary Loss or dynamic routing to ensure balanced load across experts, avoiding idle GPUs.
- Expert Caching: Cache weights of popular experts in the VRAM of all GPUs to reduce cross-GPU access.
- Sparse Activation: Each inference activates only 8 experts (out of 256), resulting in much lower computation than a Dense model with equivalent parameters.
Cost Optimization Practices
GPU inference cost is one of the largest expenses for AI applications. Through proper GPU selection, instance strategies, and architecture design, inference costs can be reduced by 50%-80%.
Cloud GPU Selection Comparison
| GPU | VRAM | FP8 Support | On-Demand Price/Hour | Suitable Models |
|---|---|---|---|---|
| H100 80GB | 80 GB | Supported | $2.50-$3.50 | V3 671B (8x), 70B (2x) |
| A100 80GB | 80 GB | Not supported | $1.80-$2.50 | V3 671B (16x INT4), 70B (2x) |
| A100 40GB | 40 GB | Not supported | $1.20-$1.80 | 32B models (single GPU), 70B (2x) |
| L40S 48GB | 48 GB | Supported | $0.80-$1.20 | 32B models (single GPU FP8) |
| RTX 4090 24GB | 24 GB | Not supported | Self-built: ~$0.30 | 7B/14B models |
On-Demand vs Reserved Instance Comparison
| Instance Type | Discount | Commitment Term | Flexibility | Recommended Scenarios |
|---|---|---|---|---|
| On-Demand | Full price | None | Extremely high | Development testing, uncertain loads |
| Reserved | 40-60% | 1-3 years | Low | Stable production environments |
| Spot/Preemptible | 60-90% | None | Can be reclaimed anytime | Offline batch processing, fault-tolerant tasks |
| Hybrid strategy | 50-70% | Flexible | Medium | Reserved baseline + Spot elasticity |
Inference Cost Calculation
Self-hosted vs Cloud Services Comparison
| Comparison Dimension | Self-hosted Inference | DeepSeek Official API | Cloud Inference Service |
|---|---|---|---|
| Initial Cost | High (GPU purchase/rental) | Zero | Medium |
| Operational Cost | High (requires dedicated maintenance) | Zero | Medium |
| Data Privacy | Fully controllable | Data passes through third party | Depends on configuration |
| High Load Cost | Low marginal cost | Linear growth | Medium |
| Elastic Scaling | Limited | Unlimited | Good |
Cost Optimization Best Practices
- Load Tiering: Use 7B/14B distilled models for simple questions, route complex questions to 70B/671B large models, saving 60% cost
- Cache Strategy: Cache answers for popular questions (semantic cache), hit rate can reach 30-50%, directly saving inference cost
- Quantization for Cost Reduction: FP8 quantization reduces memory by 50%, INT4 by 75%, serving more users on the same hardware
- Spot Instances: Use spot instances for offline batch processing and asynchronous tasks, reducing cost by 60-90%
- Auto Scaling: Automatically adjust GPU instance count based on QPS, scale down to 0 during off-peak, saving 40-60% cost
- Checkpointing: Save KV Cache state when spot instances are reclaimed, resume inference after recovery, avoiding waste
Cost Optimization Recommendations
When daily token volume is below 1 million, using the DeepSeek official API is most economical; when daily tokens are between 1 million and 10 million, self-hosting a 32B/70B distilled model inference service offers the best cost-performance; when daily tokens exceed 10 million, deploy the full 671B model with quantization and spot instances. For more deployment options, see DeepSeek Deployment Tutorial.
DeepSeek Inference Acceleration FAQ
DeepSeek Related Tutorials
Dive deeper into using, deploying, and ecosystem tools for DeepSeek models.
How to Use DeepSeek Models
Four usage methods, zero-basics beginner tutorial.
DeepSeek Deployment Tutorial
Deployment options with Ollama, Docker, vLLM, K8s.
DeepSeek RAG Knowledge Base
Document loading, vector embeddings, ChromaDB retrieval, Q&A with source citations.
DeepSeek Model Architecture
Technical architecture, benchmarks, model comparison.
DeepSeek Open Source Models
Complete catalog of 6 series and 20+ models.
DeepSeek Model Download
Download guides for Ollama, Hugging Face, GitHub.