MiniCPM4.1 & MiniCPM4
MiniCPM 文本系列
根据运行环境选择 Transformers、vLLM、SGLang 或 CPM.cu,按需了解稠密与稀疏推理、混合思考和投机采样。MiniCPM4.1 还提供 llama.cpp 与 Ollama 的使用入口,请留意每一节适用的模型版本。
模型推理
你可以使用 Huggingface Transformers、vLLM、SGLang、CPM.cu 对模型进行推理。
若关注推理效率,可以优先尝试 CPM.cu。
MiniCPM4 / MiniCPM4.1 支持稠密推理与稀疏推理两种模式,其中 vLLM 与 SGLang 目前只支持了稠密推理模式。如果想要使用稀疏推理模式,请使用 Huggingface Transformers 及 CPM.cu。
- 稠密注意力推理:vLLM、SGLang、Huggingface Transformers
- 稀疏注意力推理:Huggingface Transformers、CPM.cu
混合思考(MiniCPM4.1)
MiniCPM4.1 支持混合思考模式,可以用于深度思考和非思考模式。用户可以通过设置 enable_thinking=True 来启用混合思考模式,设置 enable_thinking=False 来启用非思考模式。同样,用户可以直接在查询末尾添加 /no_think 来启用非思考模式。如果未添加任何特殊标记或在查询末尾添加 /think,模型将启用思考模式。
# Enable reasoning mode
prompt_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True
)
# Enable non-reasoning mode
prompt_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False
)
Huggingface Transformers
稠密注意力推理
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
torch.manual_seed(0)
path = 'openbmb/MiniCPM4.1-8B'
device = "cuda"
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True)
# User can directly use the chat interface
# responds, history = model.chat(tokenizer, "Write an article about Artificial Intelligence.", temperature=0.7, top_p=0.7)
# print(responds)
# User can also use the generate interface
messages = [
{"role": "user", "content": "Write an article about Artificial Intelligence."},
]
prompt_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
model_inputs = tokenizer([prompt_text], return_tensors="pt").to(device)
model_outputs = model.generate(
**model_inputs,
max_new_tokens=32768,
top_p=0.95,
temperature=0.6
)
output_token_ids = [
model_outputs[i][len(model_inputs[i]):] for i in range(len(model_inputs['input_ids']))
]
responses = tokenizer.batch_decode(output_token_ids, skip_special_tokens=True)[0]
print(responses)
稀疏注意力推理
本模型支持稀疏注意力机制 InfLLM v2,可高效处理长序列推理。如需启用该功能,请先安装依赖库 infllmv2_cuda_impl。
运行以下命令即可安装:
git clone -b feature_infer https://github.com/OpenBMB/infllmv2_cuda_impl.git
cd infllmv2_cuda_impl
git submodule update --init --recursive
pip install -e . # or python setup.py install
启用 InfLLM v2 需在 config.json 配置文件中添加 sparse_config 字段:
{
...,
"sparse_config": {
"kernel_size": 32,
"kernel_stride": 16,
"init_blocks": 1,
"block_size": 64,
"window_size": 2048,
"topk": 64,
"use_nope": false,
"dense_len": 8192
}
}
配置参数说明
| 参数 | 默认值 | 作用说明 |
|---|---|---|
kernel_size | 32 | 语义核大小 |
kernel_stride | 16 | 相邻语义核之间的步长 |
init_blocks | 1 | 每个 query token 关注的初始块数量,用于确保模型能够关注序列开头部分 |
block_size | 64 | key-value blocks 的块大小 |
window_size | 2048 | 局部滑动窗口 大小 |
topk | 64 | 每个 token 仅与最相关的 top-k 个 key-value blocks 计算注意力 |
use_nope | false | 是否在块选择中使用 NOPE 技术,以提升性能 |
dense_len | 8192 | 当 token 长度低于该阈值时,自动切换为标准注意力; 设为 -1 时,强制始终使用稀疏注意力 |
长度扩展
MiniCPM4.1 原生支持 65,536 tokens 的上下文长度。若对话总长度(输入 + 输出)远超此限制,建议通过 RoPE 缩放技术扩展上下文。通过调整 LongRoPE 因子,模型可稳定支持 131,072 tokens 的超长上下文。
修改方法:在 config.json 文件中调整 rope_scaling 字段参数即可。
{
...,
"rope_scaling": {
"rope_type": "longrope",
"long_factor": [0.9982316082870437, 1.033048153422584, 1.0749920956484724, 1.1255096879436193, 1.1863348602111476, 1.259543828902579, 1.3476188888731149, 1.4535223827776373, 1.5807816745852985, 1.7335856049489526, 1.9168922912975785, 2.1365471404135326, 2.3994084200118646, 2.713475511863602, 3.0880118452194134, 3.533650295140154, 4.062463396503134, 4.687974098908333, 5.425075306704039, 6.289818967956352, 7.29902962722721, 8.6357018163639, 10.210822723989212, 12.053807765671676, 14.193944598909404, 16.65780676784363, 19.463620727694074, 22.628311203524586, 26.150106147261315, 30.02526691405111, 34.23183327975347, 38.73811934094828, 43.502489489729555, 48.47627117965394, 53.61139491762471, 58.857366522037935, 64.16798299215064, 69.51359464319125, 74.86555458220285, 80.21497790341579, 85.55322183307433, 90.89611806932027, 96.26245306514224, 101.68269304046481, 107.18619510219668, 112.82253283014026, 118.63764063163615, 119.88866203644656, 120.9462882391725, 121.837565139014, 122.58663780572562, 123.2147719894291, 123.74049454862576, 124.17980424685767, 124.54641761955492, 124.85202548028222, 125.10654406389756, 125.31835105170659, 125.49450117164764, 125.64091910903052, 125.76256945356558, 125.86360463815589, 125.94749252260765, 126.01712561287873],
"short_factor": [0.9982316082870437, 1.033048153422584, 1.0749920956484724, 1.1255096879436193, 1.1863348602111476, 1.259543828902579, 1.3476188888731149, 1.4535223827776373, 1.5807816745852985, 1.7335856049489526, 1.9168922912975785, 2.1365471404135326, 2.3994084200118646, 2.713475511863602, 3.0880118452194134, 3.533650295140154, 4.062463396503134, 4.687974098908333, 5.425075306704039, 6.289818967956352, 7.29902962722721, 8.6357018163639, 10.210822723989212, 12.053807765671676, 14.193944598909404, 16.65780676784363, 19.463620727694074, 22.628311203524586, 26.150106147261315, 30.02526691405111, 34.23183327975347, 38.73811934094828, 43.502489489729555, 48.47627117965394, 53.61139491762471, 58.857366522037935, 64.16798299215064, 69.51359464319125, 74.86555458220285, 80.21497790341579, 85.55322183307433, 90.89611806932027, 96.26245306514224, 101.68269304046481, 107.18619510219668, 112.82253283014026, 118.63764063163615, 119.88866203644656, 120.9462882391725, 121.837565139014, 122.58663780572562, 123.2147719894291, 123.74049454862576, 124.17980424685767, 124.54641761955492, 124.85202548028222, 125.10654406389756, 125.31835105170659, 125.49450117164764, 125.64091910903052, 125.76256945356558, 125.86360463815589, 125.94749252260765, 126.01712561287873],
"original_max_position_embeddings": 65536
}
}
vLLM
你可以使用投机采样加速模型生成,也可以使用标准模式部署模型。
投机采样
使用 vLLM 进行加速推理的投机采样步骤如下:
- 下载 MiniCPM4.1 草稿模型
cd /your_path
git clone https://huggingface.co/openbmb/MiniCPM4.1-8B-Eagle3
- 安装 EAGLE3 兼容的 vLLM
EAGLE3 的 vLLM PR 已经提交。目前请使用我们的仓库进行安装:
git clone https://github.com/LDLINGLINGLING/vllm.git
cd vllm
pip install -e .
- 启动带有投机采样的 vLLM 服务
请确保在 speculative-config 中将模型路径更新为下载的 MiniCPM4_1-8B-Eagle3-bf16 文件夹:
VLLM_USE_V1=1 \
vllm serve openbmb/MiniCPM4.1-8B \
--seed 42 \
--trust-remote-code \
--speculative-config '{
"model": "your/path/MiniCPM4_1-8B-Eagle3-bf16",
"num_speculative_tokens": 3,
"method": "eagle3",
"draft_tensor_parallel_size": 1
}'
- 客户端使用示例
客户端使用方式在标准解码和投机采样下保持一致:
import openai
client = openai.Client(base_url="http://localhost:8000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="openbmb/MiniCPM4.1-8B",
messages=[
{"role": "user", "content": "Write an article about Artificial Intelligence."},
],
temperature=0.6,
max_tokens=32768,
extra_body=dict(add_special_tokens=True), # 确保在聊天模板中加入特殊符号
)
print(response.choices[0].message.content)
配置参数说明
| 参数 | 默认值 / 示例 | 作用说明 |
|---|---|---|
VLLM_USE_V1 | 1 | 启用 vLLM v1 API |
--speculative-config | JSON 配置 | 投机采样相关配置,用于指定草稿模型、推测 token 数量、采样方法等参数 |
model | 草稿模型路径 | 指定投机采样 中使用的草稿模型路径 |
num_speculative_tokens | 3 | 每次推测生成的 token 数量 |
method | eagle3 | 指定投机采样方法 |
draft_tensor_parallel_size | 1 | 草稿模型的张量并行大小 |
--seed | 随机种子 | 设置随机种子,用于保证结果可复现 |
--trust-remote-code | 无 | 允许执行远程代码,以支持自定义模型结构或模型实现 |
标准推理(不使用投机采样)
目前你需要安装最新版本的 vLLM。
pip install -U vllm \
--pre \
--extra-index-url https://wheels.vllm.ai/nightly
然后可以用 vLLM 推理 MiniCPM4.1-8B:
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
model_name = "openbmb/MiniCPM4.1-8B"
prompt = [{"role": "user", "content": "Write an article about Artificial Intelligence."}]
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
input_text = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
llm = LLM(
model=model_name,
trust_remote_code=True,
max_num_batched_tokens=65536,
dtype="bfloat16",
gpu_memory_utilization=0.8,
)
sampling_params = SamplingParams(top_p=0.95, temperature=0.6, max_tokens=32768)
outputs = llm.generate(prompts=input_text, sampling_params=sampling_params)
print(outputs[0].outputs[0].text)
你也可以通过以下命令启动推理服务:
vllm serve openbmb/MiniCPM4.1-8B --trust-remote-code
注意: 在 vLLM 的 chat API 中,
add_special_tokens默认是 False。这意味着重要的特殊符号——比如序列开始符(BOS token)——不会被自动加入。为了确保输入提示对模型格式正确,建议显式设置extra_body={"add_special_tokens": True}。
然后可以通过以下代码使用聊天接口:
import openai
client = openai.Client(base_url="http://localhost:8000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="openbmb/MiniCPM4.1-8B",
messages=[
{"role": "user", "content": "Write an article about Artificial Intelligence."},
],
temperature=0.6,
max_tokens=32768,
extra_body=dict(add_special_tokens=True), # 确保在聊天模板中加入特殊符号
)
print(response.choices[0].message.content)
SGLang
你可以使用投机采样加速模型生成,也可以使用标准模式部署模型。
投机采样
使用投机采样进行加速推理的步骤如下:
- 下载 MiniCPM4.1 草稿模型
cd /your_path
git clone https://huggingface.co/openbmb/MiniCPM4.1-8B-Eagle3
- 安装 EAGLE3 兼容的 SGLang
EAGLE3 的适配 PR 已经提交。目前请使用我们的仓库进行安装:
git clone https://github.com/LDLINGLINGLING/sglang.git
cd sglang
pip install -e .
- 启动带有投机采样的 SGLang 服务
python -m sglang.launch_server \
--model-path "openbmb/MiniCPM4.1-8B" \
--host "127.0.0.1" \
--port 30002 \
--mem-fraction-static 0.9 \
--speculative-algorithm EAGLE3 \
--speculative-draft-model-path "your/path/MiniCPM4_1-8B-Eagle3-bf16" \
--speculative-num-steps 3 \
--speculative-eagle-topk 1 \
--speculative-num-draft-tokens 32 \
--temperature 0.7
- 客户端使用示例
客户端使用方式在标准解码和投机采样下保持一致:
import openai
client = openai.Client(base_url=f"http://localhost:30002/v1", api_key="None")
response = client.chat.completions.create(
model="openbmb/MiniCPM4.1-8B",
messages=[
{"role": "user", "content": "Write an article about Artificial Intelligence."},
],
temperature=0.6,
max_tokens=32768,
)
print(response.choices[0].message.content)
注意:请确保在客户端代码中更新端口号,以匹配服务端端口(在投机采样示例中为 30002)。
配置参数说明
| 参数 | 默认值 / 示例 | 作用说明 |
|---|---|---|
--speculative-algorithm | EAGLE3 | 启用 EAGLE3 投机采样算法。 |
--speculative-draft-model-path | 草稿模型路径 | 指定投机采样中使用的草稿模型路径。 |
--speculative-num-steps | 3 | 推测步数,即每轮投机采样向前推测的步数。 |
--speculative-eagle-topk | 1 | EAGLE 的 top-k 参数,用于控制草稿 token 候选范围。 |
--speculative-num-draft-tokens | 32 | 草稿模型生成的 draft token 数量。 |
--mem-fraction-static | 0.9 | 静态分配的显存比例,用于控制推理服务预分配显存的占比。 |
标准推理(不使用投机采样)
目前你需要安装我们 fork 的 SGLang 版本。
git clone -b openbmb https://github.com/OpenBMB/sglang.git
cd sglang
pip install --upgrade pip
pip install -e "python[all]"
你可以通过以下命令启动推理服务:
python -m sglang.launch_server --model openbmb/MiniCPM4.1-8B --trust-remote-code --port 30000 --chat-template chatml
然后可以通过以下代码使用聊天接口:
import openai
client = openai.Client(base_url=f"http://localhost:30000/v1", api_key="None")
response = client.chat.completions.create(
model="openbmb/MiniCPM4.1-8B",
messages=[
{"role": "user", "content": "Write an article about Artificial Intelligence."},
],
temperature=0.6,
max_tokens=32768,
)
print(response.choices[0].message.content)
CPM.cu
我们推荐使用 CPM.cu 对 MiniCPM4 和 MiniCPM4.1 模型进行推理。CPM.cu 是面壁开发的一个集合了高效稀疏、投机采样、量化等技术的 CUDA 推理框架,能够完全发挥 MiniCPM4 和 MiniCPM4.1 的效率优势。
你可以通过以下脚本安装 CPM.cu 并进行推理:
git clone https://github.com/OpenBMB/CPM.cu.git --recursive
cd CPM.cu
python3 setup.py install
你可以通过以下命令进行推理并查看模型的运行速度。
python3 tests/long_prompt_gen.py # 生成 prompt.txt
python3 tests/test_generate.py --prompt-file prompt.txt
你可以通过一下命令使用 EAGLE3 进行投机推理。
python3 -m cpmcu.cli \
--model-path $BASE_MODEL_PATH \
--draft-model-path $EAGLE3_DRAFT_MODEL_PATH \
--prompt-text "Tell me about Tsinghua University" \
--use-eagle3 true
更多关于 CPM.cu 的细节,请参考 CPM.cu 仓库。
llama.cpp
你可以从 huggingface 下载 MiniCPM4.1-8B 的 GGUF 格式模型,并使用 llama.cpp 进行推理。
# case 1: main-cli
./build/bin/llama-cli -m MiniCPM4.1-8B-Q4_K_M.gguf -p "Write an article about Artificial
Intelligence." -n 1500
# case 2: server
## launch server
./build/bin/llama-server -m MiniCPM4.1-8B-Q4_K_M.gguf --host 127.0.0.1 --port 8080 -c
4096 -fa on &
## send request
curl -X POST http://127.0.0.1:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Write an article about Artificial
Intelligence."}],
"max_tokens": 1500
}'
Ollama
请前往 模型库 下载模型。安装好 Ollama 后,可以通过以下命令使用 MiniCPM4.1:
ollama run openbmb/minicpm4.1