
DeepSeek-R1 đại diện cho một bước tiến đáng kể trong các Mô hình Ngôn ngữ Lớn (LLM) có khả năng suy luận, đặc biệt thông qua việc sử dụng sáng tạo học tăng cường từ phản hồi của con người (RLHF) và tự chơi với trọng tâm vào các dấu vết suy luận. Bài viết này phân tích các nền tảng kiến trúc của DeepSeek-R1 và các biến thể chắt lọc của nó, cung cấp hướng dẫn thực tế để triển khai cục bộ, các chiến lược lượng tử hóa và tối ưu hóa hiệu suất bằng cách sử dụng vLLM và TensorRT-LLM.
Compare token costs, prompt caching discounts & context margins
Model monthly token economics across Gemini 2.5 Flash, DeepSeek R1/V3, Claude 3.5 Sonnet, and GPT-4o with prompt caching discounts, token counter, and markdown export.
Đổi mới cốt lõi của DeepSeek-R1 nằm ở phương pháp đào tạo của nó, nhấn mạnh việc tạo và tinh chỉnh các bước suy luận rõ ràng. Không giống như các mô hình học suy luận một cách ngầm định, DeepSeek-R1 được đào tạo để tạo ra các quy trình tư duy có cấu trúc, thường được gói gọn trong các khối <think>, trước khi đưa ra câu trả lời cuối cùng. Cách tiếp cận này được lấy cảm hứng từ lời nhắc Chain-of-Thought (CoT) nhưng được tích hợp trực tiếp vào mục tiêu đào tạo của mô hình.
Quá trình đào tạo bao gồm:
<think> và </think> để phân định quá trình suy luận nội bộ của nó. Điều này làm cho việc ra quyết định của mô hình minh bạch và dễ gỡ lỗi hơn.Xem xét một tương tác DeepSeek-R1:
User: What is the capital of France, and what is its population?
Assistant: <think>
1. Identify the capital of France.
2. Find the current population of Paris.
3. Combine the information.
</think>
The capital of France is Paris. Its population is approximately 2.1 million (as of 2023).
Cấu trúc suy luận rõ ràng này rất quan trọng đối với các tác vụ phức tạp như giải quyết vấn đề toán học, tạo mã và suy luận logic, nơi các bước trung gian cũng quan trọng như câu trả lời cuối cùng.
Các biến thể chắt lọc của DeepSeek-R1, thường dựa trên kiến trúc Llama hoặc Qwen, tận dụng khả năng suy luận này bằng cách chắt lọc kiến thức từ mô hình DeepSeek-R1 lớn hơn thành các mô hình nhỏ hơn, hiệu quả hơn. Việc chắt lọc này thường bao gồm:
Triển khai LLM lớn cục bộ đòi hỏi lượng tử hóa mạnh mẽ để phù hợp với các ràng buộc bộ nhớ GPU và cải thiện thông lượng suy luận. Chúng tôi tập trung vào FP8 (Float8) và AWQ (Activation-aware Weight Quantization) do sự cân bằng giữa hiệu suất và độ chính xác của chúng.
Lượng tử hóa FP8, đặc biệt là sử dụng định dạng E4M3 (4 bit số mũ, 3 bit mantissa) hoặc E5M2 (5 bit số mũ, 2 bit mantissa), mang lại khả năng tiết kiệm bộ nhớ đáng kể (giảm 8 lần so với FP64, 4 lần so với FP32, 2 lần so với FP16/BF16). Kiến trúc Hopper của NVIDIA và các GPU mới hơn cung cấp khả năng tăng tốc lõi tensor FP8 gốc, làm cho nó cực kỳ hiệu quả.
Quá trình này thường bao gồm:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Example: Loading a model with FP8 (requires specific libraries like NVIDIA's TransformerEngine or custom implementations)
# This is a conceptual example as direct FP8 loading via transformers is often through specific backend integrations.
# For actual FP8, you'd typically use TensorRT-LLM or a custom FP8-enabled inference engine.
model_id = "deepseek-ai/deepseek-llm-7b-base" # Or a distilled variant
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Placeholder for FP8 loading logic. In practice, this would involve
# converting the model to FP8 format using tools like `huggingface-cli convert`
# or TensorRT-LLM's build process.
# For demonstration, we'll show a standard load, but note FP8 requires specific hardware/software.
try:
# This would typically fail without a specific FP8 implementation or TRT-LLM
# model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float8_e4m3fn)
print("Direct FP8 loading via transformers is not standard. Use TensorRT-LLM or similar.")
except Exception as e:
print(f"Error loading with torch.float8_e4m3fn directly: {e}")
# A more realistic scenario for FP8 would be via TensorRT-LLM:
# (See TensorRT-LLM section below for full example)
AWQ là một phương pháp lượng tử hóa sau đào tạo (PTQ) tập trung vào việc lượng tử hóa trọng số trong khi giữ các kích hoạt ở FP16/BF16. Nó nhận thấy rằng không phải tất cả các trọng số đều quan trọng như nhau đối với hiệu suất mô hình; một số trọng số, đặc biệt là những trọng số được nhân với các kích hoạt lớn, nhạy cảm hơn với lỗi lượng tử hóa. AWQ chọn lọc lượng tử hóa trọng số dựa trên độ lớn kích hoạt của chúng.
Ý tưởng cốt lõi:
AWQ thường đạt được độ chính xác tốt hơn so với lượng tử hóa INT4 đơn giản với dữ liệu hiệu chuẩn tối thiểu. Nó được hỗ trợ tốt bởi các công cụ suy luận như vLLM.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Example: Loading a model with AWQ using vLLM's integration
# This requires the model to be pre-quantized or vLLM to perform on-the-fly quantization.
# For vLLM, you typically specify `quantization="awq"` during engine initialization.
# To prepare a model for AWQ, you might use AutoGPTQ or similar libraries.
# Example using AutoGPTQ for AWQ (conceptual, as vLLM handles the inference part):
# from accelerate import Accelerator
# from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
# model_id = "deepseek-ai/deepseek-llm-7b-base"
# quant_config = BaseQuantizeConfig(
# bits=4,
# group_size=128,
# desc_act=False, # For AWQ, often False
# quant_method="awq"
# )
#
# model = AutoGPTQForCausalLM.from_pretrained(model_id, quantize_config=quant_config)
# model.quantize(tokenizer.train_dataloader) # Requires a calibration dataset
# model.save_quantized("deepseek-llm-7b-awq")
# For vLLM, you just point to the AWQ-quantized model directory or specify the quantization method.
| Tính năng | FP8 (E4M3/E5M2) | AWQ (4-bit) |
|---|---|---|
| Dung lượng bộ nhớ | Giảm 8 lần (từ FP64), 2 lần (từ FP16) | Giảm 4 lần (từ FP16) |
| Hỗ trợ phần cứng | Gốc trên NVIDIA Hopper/Blackwell (Tensor Cores) | Không phụ thuộc GPU, được tối ưu hóa bởi các công cụ suy luận |
| Độ chính xác | Nói chung cao, đặc biệt với hiệu chuẩn | Tuyệt vời cho 4-bit, nhận biết kích hoạt |
| Độ phức tạp | Yêu cầu ngăn xếp phần cứng/phần mềm cụ thể | Sau đào tạo, tương đối đơn giản |
| Tốc độ suy luận | Cực nhanh với hỗ trợ phần cứng gốc | Nhanh, thông lượng tốt trên GPU tiêu dùng |
| Hiệu chuẩn | Khuyến nghị cho các yếu tố tỷ lệ tối ưu | Yêu cầu để xác định tầm quan trọng của trọng số |
| Trường hợp sử dụng | Trung tâm dữ liệu cao cấp, thông lượng tối đa | Triển khai cục bộ, GPU tiêu dùng, cân bằng tốt |
vLLM là một thư viện mã nguồn mở để suy luận LLM nhanh, tận dụng PagedAttention để quản lý bộ nhớ cache KV một cách hiệu quả. Nó cải thiện đáng kể thông lượng so với các triển khai đơn giản, đặc biệt đối với suy luận theo lô.
# Ensure you have a compatible CUDA toolkit installed
pip install vllm
Để triển khai DeepSeek-R1 hoặc biến thể chắt lọc của nó với vLLM, bạn có thể sử dụng API Python của nó hoặc khởi chạy một máy chủ.
from vllm import LLM, SamplingParams
# Model ID from Hugging Face Hub. Replace with your specific DeepSeek-R1 variant.
# For AWQ, ensure the model is either pre-quantized or vLLM supports on-the-fly AWQ for it.
model_id = "deepseek-ai/deepseek-llm-7b-base" # Example, use a distilled/quantized version for production
# Initialize the LLM engine
# For AWQ, you'd typically specify quantization="awq" if the model supports it or is pre-quantized.
# For FP8, you'd need TensorRT-LLM integration or a custom vLLM build.
llm = LLM(
model=model_id,
tensor_parallel_size=1, # Number of GPUs to use for tensor parallelism
dtype="auto", # Automatically detect dtype (e.g., bfloat16, float16)
gpu_memory_utilization=0.9, # Max GPU memory to use
quantization="awq" # Specify AWQ quantization if using an AWQ model
)
# Define sampling parameters
sampling_params = SamplingParams(
temperature=0.7,
top_p=0.95,
max_tokens=256,
stop=["<|im_end|>", "User:"] # Example stop tokens for chat models
)
# Generate prompts
prompts = [
"User: Explain the concept of PagedAttention in vLLM. Assistant:",
"User: What are the key differences between FP8 and AWQ quantization? Assistant:"
]
# Generate outputs
outputs = llm.generate(prompts, sampling_params)
# Print the outputs
for i, output in enumerate(outputs):
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
print("-" * 80)
Đối với một điểm cuối API sẵn sàng sản xuất:
# Start the vLLM API server
# Replace deepseek-ai/deepseek-llm-7b-base with your model path or HF ID.
# --quantization awq for AWQ models.
# --dtype bfloat16 for bfloat16 inference.
python -m vllm.entrypoints.api_server \
--model deepseek-ai/deepseek-llm-7b-base \
--tensor-parallel-size 1 \
--gpu-memory-utilization 0.9 \
--port 8000 \
--host 0.0.0.0 \
--quantization awq # Use this if your model is AWQ quantized
Sau đó, tương tác với nó bằng curl hoặc một máy khách Python:
import requests
import json
api_url = "http://localhost:8000/generate"
headers = {"Content-Type": "application/json"}
payload = {
"prompt": "User: Explain the concept of PagedAttention in vLLM. Assistant:",
"sampling_params": {
"temperature": 0.7,
"top_p": 0.95,
"max_tokens": 256,
"stop": ["<|im_end|>", "User:"]
}
}
response = requests.post(api_url, headers=headers, data=json.dumps(payload))
print(json.dumps(response.json(), indent=2))
Để đạt hiệu suất tối đa, đặc biệt với lượng tử hóa FP8 trên GPU NVIDIA, TensorRT-LLM là giải pháp ưu tiên. Nó biên dịch các biểu đồ LLM thành các công cụ TensorRT được tối ưu hóa cao.
Chuyển đổi mô hình Hugging Face sang định dạng TensorRT-LLM: Bước này liên quan đến việc chuyển đổi trọng số và kiến trúc của mô hình sang định dạng mà TensorRT-LLM có thể hiểu và tối ưu hóa.
# Example for Llama-based models (DeepSeek-R1 distilled variants)
# Ensure you have the TensorRT-LLM environment set up.
# This script is usually part of the TensorRT-LLM examples.
# Clone TensorRT-LLM if you haven't
# git clone https://github.com/NVIDIA/TensorRT-LLM.git
# cd TensorRT-LLM
# pip install -e .
# Navigate to the examples directory
# cd examples/llama
# Convert the Hugging Face model.
# Replace deepseek-ai/deepseek-llm-7b-base with your model.
# --dtype float8 for FP8 quantization.
# --output_dir specifies where the TensorRT-LLM engine will be saved.
python convert_checkpoint.py \
--model_dir deepseek-ai/deepseek-llm-7b-base \
--output_dir ./tllm_deepseek_7b_fp8 \
--dtype float8 \
--tp_size 1 # Tensor parallelism size
Xây dựng công cụ TensorRT-LLM: Bước này biên dịch mô hình đã chuyển đổi thành một công cụ TensorRT được tối ưu hóa.
# Navigate to the TensorRT-LLM root directory
# cd TensorRT-LLM
# Build the engine
# Replace the path to your converted model.
# --max_batch_size, --max_input_len, --max_output_len are crucial for performance tuning.
# --dtype float8 for FP8.
# --workers for parallel compilation.
trtllm-build --checkpoint_dir ./tllm_deepseek_7b_fp8 \
--output_dir ./tllm_deepseek_7b_fp8_engine \
--gemm_plugin float8 \
--max_batch_size 8 \
--max_input_len 512 \
--max_output_len 256 \
--workers 1 \
--dtype float8
Chạy suy luận với TensorRT-LLM: Sử dụng công cụ đã xây dựng để suy luận.
import tensorrt_llm
from tensorrt_llm.runtime import ModelRunner
import torch
# Load the tokenizer
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-llm-7b-base")
# Initialize the TensorRT-LLM runner
# Specify the engine directory and max_batch_size used during build.
runner = ModelRunner(
engine_dir='./tllm_deepseek_7b_fp8_engine',
lora_dir=None, # If using LoRA adapters
rank=0,
max_batch_size=8,
max_input_len=512,
max_output_len=256,
dtype='float8' # Must match the engine's dtype
)
prompts = [
"User: Explain the concept of PagedAttention in vLLM. Assistant:",
"User: What are the key differences between FP8 and AWQ quantization? Assistant:"
]
# Tokenize prompts
input_ids = [tokenizer.encode(p, return_tensors="pt").cuda() for p in prompts]
# Generate outputs
# The `generate` method takes a list of input_ids tensors.
# It returns a list of output_ids tensors.
output_ids = runner.generate(
input_ids,
max_new_tokens=256,
temperature=0.7,
top_p=0.95,
stop_words_list=[tokenizer.encode("<|im_end|>", add_special_tokens=False),
tokenizer.encode("User:", add_special_tokens=False)]
)
# Decode and print
for i, output in enumerate(output_ids):
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
print(f"Prompt: {prompts[i]!r}, Generated text: {generated_text!r}")
print("-" * 80)
Hết bộ nhớ GPU (CUDA out of memory):
max_model_len (vLLM), hoặc max_input_len/max_output_len (TensorRT-LLM) vượt quá VRAM khả dụng.tensor_parallel_size (nếu sử dụng nhiều GPU, đảm bảo nó được cấu hình đúng).gpu_memory_utilization trong vLLM (ví dụ: xuống 0.85).max_batch_size.max_model_len (vLLM) hoặc max_input_len/max_output_len (TensorRT-LLM).Thông lượng thấp/Độ trễ cao:
max_batch_size (đến giới hạn bộ nhớ) để tận dụng song song GPU.tensor_parallel_size được cấu hình đúng cho các thiết lập đa GPU.dtype (ví dụ: bfloat16 hoặc float16) được sử dụng, không phải float32.nvprof hoặc NVIDIA Nsight Systems để xác định các tắc nghẽn.Giảm chất lượng đầu ra mô hình sau lượng tử hóa:
Lỗi xây dựng công cụ TensorRT-LLM:
convert_checkpoint.py không chính xác, kiến trúc mô hình không tương thích hoặc các vấn đề về môi trường.model_dir, dtype và tp_size.--log_level verbose) để có thông báo lỗi chi tiết hơn.vLLM stop_tokens không hoạt động như mong đợi:
stop được mã hóa token đúng cách. Ví dụ, stop=["<|im_end|>", "User:"] phải là stop_token_ids=[tokenizer.encode("<|im_end|>", add_special_tokens=False), tokenizer.encode("User:", add_special_tokens=False)] nếu sử dụng các ID token thô. Đối số SamplingParams stop của vLLM xử lý khớp chuỗi, nhưng đối với các ID token cụ thể, stop_token_ids mạnh mẽ hơn.A1: Có, đặc biệt là các biến thể chắt lọc và lượng tử hóa. Một RTX 3090 (24GB VRAM) hoặc 4090 (24GB VRAM) có thể chạy thoải mái các mô hình 7B-13B tham số được lượng tử hóa thành 4-bit (AWQ) hoặc thậm chí một số mô hình 7B trong FP16/BF16 với vLLM. Đối với các mô hình lớn hơn hoặc FP8, cần nhiều GPU hoặc nhiều VRAM hơn. TensorRT-LLM với FP8 chủ yếu dành cho Hopper/Blackwell, nhưng các công cụ FP16/BF16 có thể chạy trên các card tiêu dùng.
<think> trong DeepSeek-R1 là gì?A2: Việc tạo rõ ràng các khối <think> làm tăng tổng số token được tạo ra, điều này ảnh hưởng trực tiếp đến độ trễ suy luận. Tuy nhiên, chi phí này thường được biện minh bằng chất lượng suy luận được cải thiện và giảm ảo giác. Quá trình đào tạo của mô hình đảm bảo các khối này ngắn gọn và phù hợp. Đối với các ứng dụng nhạy cảm về độ trễ, bạn có thể xử lý hậu kỳ để loại bỏ các khối này trước khi trình bày cho người dùng, hoặc tinh chỉnh một mô hình chắt lọc để tạo ra suy luận nhỏ gọn hơn.
A3:
A4: Có, việc tinh chỉnh các mô hình chắt lọc nhỏ hơn (ví dụ: 7B) là khả thi trên các GPU tiêu dùng với đủ VRAM (24GB+). Các kỹ thuật như LoRA (Low-Rank Adaptation) hoặc QLoRA (Quantized LoRA) rất được khuyến nghị để giảm dung lượng bộ nhớ. Bạn sẽ cần một tập dữ liệu phù hợp với tác vụ cụ thể của mình và một framework như Hugging Face transformers hoặc peft.
tensor_parallel_size trong vLLM và TensorRT-LLM là gì?A5: tensor_parallel_size chỉ định số lượng GPU để phân phối các lớp hoặc tensor của mô hình.
tensor_parallel_size=1.Một nhóm phát triển đang triển khai DeepSeek-R1 cho một ứng dụng thời gian thực quan trọng, nơi độ trễ suy luận là tối quan trọng. Họ đang xem xét cả vLLM và TensorRT-LLM để triển khai cục bộ và tối ưu hóa hiệu suất. Yếu tố nào sau đây là QUAN TRỌNG NHẤT khi lựa chọn giữa hai công cụ này để giảm thiểu độ trễ suy luận trong môi trường sản xuất?
Làm sạch log AI CLI, tạo biểu thức cron, giải mã JWT và tính quyền chmod offline.

Hướng dẫn kiến trúc chuyên sâu về giải mã suy đoán trong vLLM: tăng gấp ba thông lượng suy luận LLM với Eagle & Medusa cùng các ví dụ thực tế đã được kiểm chứng trong sản xuất.
Đọc tiếp
Hướng dẫn toàn diện về dynamic batching liên tục trong suy luận LLM: điểm chuẩn độ trễ của Orca, vLLM & TGI với kiến trúc cấp độ sản xuất và ví dụ mã.
Đọc tiếp
Hướng dẫn toàn diện so sánh sglang và vllm: suy luận LLM thông lượng cao, radixattention và giải mã có cấu trúc với kiến trúc cấp độ sản xuất và các ví dụ code.
Đọc tiếp