Skip to content

采样、量化与部署 — 概念

采样器链 (Sampler Chain)

sampler-chain 采样器链是一个管道,logits 依次经过多个采样器处理:

常见采样器

采样器作用
Temperature缩放 logits 温度
Top-K只保留概率最高的 K 个
Top-P只保留累积概率前 P 的 token
Min-P过滤概率低于最大概率 × min_p 的 token
Typical基于信息熵的采样
Mirostat自适应温度控制
Grammar基于语法约束输出格式
Penalties重复惩罚、频率惩罚
Logit Bias手动调整特定 token 的概率

量化 (Quantization)

quantization 将模型权重从 F16 压缩为低比特整数:

量化类型对比

类型比特/权重模型大小 (7B)质量损失
F161613.5 GB基准
Q8_08.57.2 GB极小
Q5_15.54.7 GB
Q5_05.04.3 GB
Q4_14.53.9 GB中等
Q4_04.53.8 GB中等
IQ4_XS4.253.6 GB中等
Q3_K_S3.53.0 GB较大
Q2_K2.752.4 GB

Block Quantization

量化以 block 为单位(通常 32 个权重):

Block Q4_0 (18 bytes for 32 weights):
┌──────────┬──────────────────────┐
│ d (F16)  │ 16 × uint8 (4-bit × 32) │
│ scale    │ quantized values        │
└──────────┴──────────────────────┘

dequantize: weight = (quantized - 8) × d

Importance Matrix (imatrix)

imatrix 通过在校准数据上统计各张量的重要性,指导量化时保留关键权重:

bash
# 生成 imatrix
./llama-imatrix -m model.gguf -f calibration.txt -o imatrix.dat

# 使用 imatrix 量化
./llama-quantize --imatrix imatrix.dat model.gguf model-Q4_K_M.gguf Q4_K_M

llama-server

llama-server 提供 OpenAI 兼容 API:

bash
# 启动服务器
./llama-server -m model.gguf --port 8080

# 调用 chat completion
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"model","messages":[{"role":"user","content":"Hello"}]}'

支持的端点:

  • /v1/chat/completions — Chat Completion
  • /v1/completions — Text Completion
  • /v1/embeddings — Embeddings
  • /v1/models — 模型列表
  • /health — 健康检查

相关概念