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,模型将启用思考模式。
Python
# 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
稠密注意力推理
Python
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)